lang
stringclasses 1
value | license
stringclasses 13
values | stderr
stringlengths 0
350
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 7
45.1k
| new_contents
stringlengths 0
1.87M
| new_file
stringlengths 6
292
| old_contents
stringlengths 0
1.87M
| message
stringlengths 6
9.26k
| old_file
stringlengths 6
292
| subject
stringlengths 0
4.45k
|
---|---|---|---|---|---|---|---|---|---|---|---|
Java | apache-2.0 | 60fd61a50070e12caaa0083f3cadd59da63d3574 | 0 | b2ihealthcare/snow-owl,IHTSDO/snow-owl,b2ihealthcare/snow-owl,IHTSDO/snow-owl,IHTSDO/snow-owl,IHTSDO/snow-owl,b2ihealthcare/snow-owl,b2ihealthcare/snow-owl | /*
* Copyright 2011-2015 B2i Healthcare Pte Ltd, http://b2i.sg
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.b2international.snowowl.datastore.cdo;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Strings.nullToEmpty;
import static com.google.common.base.Suppliers.memoize;
import static com.google.common.cache.CacheBuilder.newBuilder;
import static com.google.common.collect.Maps.newHashMap;
import static java.util.Collections.unmodifiableMap;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.annotation.Nullable;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtensionRegistry;
import org.eclipse.core.runtime.Platform;
import org.eclipse.emf.cdo.common.id.CDOID;
import org.eclipse.emf.cdo.common.model.CDOPackageRegistry;
import org.eclipse.emf.cdo.common.model.CDOPackageUnit;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EPackage.Registry;
import org.eclipse.net4j.util.lifecycle.Lifecycle;
import org.eclipse.net4j.util.lifecycle.LifecycleUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.b2international.commons.CompareUtils;
import com.b2international.commons.StringUtils;
import com.b2international.snowowl.core.api.NsUri;
import com.b2international.snowowl.datastore.index.AbstractIndexEntry;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.base.Supplier;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.Iterables;
import com.google.common.collect.Iterators;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
/**
* Basic CDO container implementation.
*
*/
public abstract class CDOContainer<T extends ICDOManagedItem<T>> extends Lifecycle implements ICDOContainer<T> {
/**Shared logger.*/
protected static final Logger LOGGER = LoggerFactory.getLogger(CDOContainer.class);
private static final LoadingCache<String, NsUri> CACHE;
static {
CACHE = CacheBuilder.newBuilder().build(new CacheLoader<String, NsUri>() {
@Override public NsUri load(final String nsUri) throws Exception {
return StringUtils.isEmpty(nsUri) ? NsUri.NULL_IMPL : new NsUri(nsUri);
}
});
}
private static final String REPOSITORY_EXT_ID = "com.b2international.snowowl.datastore.repository";
private static final String NS_URI_ELEMENT = "nsUri";
private static final String URI_ATTRIBUTE = "uri";
private static final String UUID_ATTRIBUTE = "uuid";
private static final String NAME_ATTRIBUTE = "name";
private static final String TOOLING_ID_ATTRIBUTE = "toolingId";
private static final String NAMESPACE_ID_ATTRIBUTE = "namespaceId";
private static final String META_REPOSITORY_ATTRIBUTE = "meta";
private static final String DEPENDS_ON_ATTRIBUTE = "dependsOn";
private final Supplier<Map<String, String>> masterToSlaveMappings = memoize(new Supplier<Map<String, String>>() {
public Map<String, String> get() {
final Map<String, String> masterToSlaveMappings = newHashMap();
for (final String uuid : uuidKeySet()) {
final T managedItem = getByUuid(uuid);
final String masterUuid = managedItem.getMasterUuid();
if (null != masterUuid) {
masterToSlaveMappings.put(masterUuid, uuid);
}
}
return unmodifiableMap(masterToSlaveMappings);
}
});
private final LoadingCache<Class<?>, T> classToItemCache = newBuilder().build(new CacheLoader<Class<?>, T>() {
public T load(final Class<?> clazz) throws Exception {
checkNotNull(clazz, "clazz");
for (final Iterator<T> itr = iterator(); itr.hasNext(); /**/) {
final T item = itr.next();
final CDOPackageRegistry packageRegistry = item.getPackageRegistry();
final CDOPackageUnit[] packageUnits = packageRegistry.getPackageUnits();
for (final CDOPackageUnit packageUnit : packageUnits) {
final EPackage[] ePackages = packageUnit.getEPackages(true);
for (final EPackage ePackage : ePackages) {
for (final EClassifier classifier : ePackage.getEClassifiers()) {
if (clazz == classifier.getInstanceClass()) {
return CDOContainer.this.get(ePackage);
}
}
}
}
}
throw new IllegalArgumentException("Cannot find managed item for class: " + clazz.getName());
}
});
/**Mapping between the EClasses and the unique model namespace URIs. Supports lazy loading.*/
private LoadingCache<EClass, NsUri> eclassToNsUriMap;
/**Mapping between the Ecore model namespace URIs and managed item UUIDs.*/
private Map<NsUri, String> nsUriToUuidMap;
/**Mapping between the UUID to the actual managed items.*/
private Map<String, T> uuidToItems;
/**Mapping between the unique repository namespace IDs and the managed item UUIDs.*/
private Map<Byte, String> namespaceToUuidMap;
/**Mapping between the Ecore model namespace URIs and the managed items.*/
private Map<NsUri, T> nsUriToItems;
@Override
public T get(final Class<?> clazz) {
return classToItemCache.getUnchecked(checkNotNull(clazz, "clazz"));
}
@Override
public T get(final EPackage ePackage) {
checkActive();
Preconditions.checkNotNull(ePackage, "EPackage argument cannot be null.");
return get(ePackage.getNsURI());
}
@Override
public T get(final String nsUri) {
checkActive();
return get(getOrCreateNsUri(Preconditions.checkNotNull(nsUri, "Namespace URI argument cannot be null.")));
}
@Override
public T get(final NsUri nsUri) {
checkActive();
Preconditions.checkNotNull(nsUri, "Namespace URI argument cannot be null.");
final String uuid = nsUriToUuidMap.get(nsUri);
if (StringUtils.isEmpty(uuid)) {
LOGGER.warn("Cannot find matching UUID for namespace URI: " + nsUri);
return null;
}
final T item = getByUuid(uuid);
if (null == item) {
LOGGER.warn("Cannot find managed item for namespace URI: " + nsUri);
return null;
}
LifecycleUtil.checkActive(item);
return item;
}
@Override
public T get(final EClass eClass) {
checkActive();
Preconditions.checkNotNull(eClass, "EClass argument cannot be null.");
return get(eClass.getEPackage());
}
@Override
public T get(final long cdoId) {
checkActive();
final byte terminologyNamaspaceId = (byte) (cdoId >> 56L);
final String uuid = namespaceToUuidMap.get(terminologyNamaspaceId);
if (StringUtils.isEmpty(uuid)) {
LOGGER.warn("Cannot find matching UUID for CDO ID: " + cdoId);
return null;
}
final T item = getByUuid(uuid);
if (null == item) {
LOGGER.warn("Cannot find managed item for CDO ID: " + cdoId);
return null;
}
LifecycleUtil.checkActive(item);
return item;
}
@Override
public T get(final Object object) {
checkActive();
Preconditions.checkNotNull(object, "Object argument cannot be null.");
if (object instanceof EObject) {
return get(((EObject) object).eClass());
} else if (object instanceof AbstractIndexEntry) {
return get(((AbstractIndexEntry) object).getStorageKey());
}
return null;
}
@Override
public T get(final CDOID cdoId) {
checkActive();
Preconditions.checkNotNull(cdoId, "CDO ID argument cannot be null.");
Preconditions.checkState(!cdoId.isTemporary(), "CDO ID was temporary.");
return get(CDOIDUtils.asLong(cdoId));
}
@Override
public T getByUuid(final String uuid) {
checkActive();
Preconditions.checkNotNull(uuid, "UUID argument cannot be null.");
return null == uuid ? null : uuidToItems.get(uuid);
}
@Override
public Iterator<T> iterator() {
checkActive();
return Iterators.unmodifiableIterator(uuidToItems.values().iterator());
}
@Override
public Set<String> uuidKeySet() {
return uuidToItems.keySet();
}
@Override
public boolean isMeta(final String uuid) {
return getByUuid(checkNotNull(uuid, "uuid")).isMeta();
}
@Override
@Nullable public String getMasterUuid(final String uuid) {
return getByUuid(checkNotNull(uuid, "uuid")).getMasterUuid();
}
@Override
@Nullable public String getSlaveUuid(final T managedItem) {
return getSlaveUuid(checkNotNull(managedItem, "managedItem").getUuid());
}
@Override
@Nullable public String getSlaveUuid(final String uuid) {
return masterToSlaveMappings.get().get(uuid);
}
/**
* (non-API)
* <br>
* Returns with a collection of {@link NsUri namespace URI}s with the associated managed item.
* @param managedItem the managed item.
* @return a collection of namespace URIs.
*/
public synchronized Iterable<NsUri> getNsUris(final T managedItem) {
Preconditions.checkNotNull(managedItem, "Managed item argument cannot be null.");
final Set<NsUri> $ = Sets.newHashSet();
for (final Entry<NsUri, T> entry : nsUriToItems.entrySet()) {
if (managedItem.equals(entry.getValue())) {
$.add(entry.getKey());
}
}
return Collections.unmodifiableCollection($);
}
@Override
protected void doDeactivate() throws Exception {
LOGGER.info("Deactivating " + this.getClass().getSimpleName() + "...");
if (null != uuidToItems) {
for (final Iterator<T> itr = Iterators.unmodifiableIterator(uuidToItems.values().iterator()); itr.hasNext(); /* nothing */) {
itr.next().deactivate();
}
}
if (null != nsUriToUuidMap) {
nsUriToUuidMap.clear();
nsUriToUuidMap = null;
}
if (null != eclassToNsUriMap) {
eclassToNsUriMap.cleanUp();
eclassToNsUriMap = null;
}
if (null != namespaceToUuidMap) {
namespaceToUuidMap.clear();
namespaceToUuidMap = null;
}
if (null != nsUriToItems) {
nsUriToItems.clear();
nsUriToItems = null;
}
super.deactivate();
LOGGER.info(this.getClass().getSimpleName() + " has been successfully deactivated.");
}
/* (non-Javadoc)
* @see org.eclipse.net4j.util.lifecycle.Lifecycle#doBeforeActivate()
*/
@Override
protected void doBeforeActivate() throws Exception {
final Map<NsUri, T> _nsUriToItems = Maps.newHashMap();
final IExtensionRegistry registry = Platform.getExtensionRegistry();
final Map<String, String> namespaceIdsByRepositoryId = newHashMap();
//load all CDO repository extensions, instantiate repositories and apply inverse mapping to the namespace URI
for (final IConfigurationElement repositoryElement : registry.getConfigurationElementsFor(REPOSITORY_EXT_ID)) {
final Set<NsUri> nsUris = Sets.newHashSet();
for (final IConfigurationElement nsUriElement : repositoryElement.getChildren()) {
if (NS_URI_ELEMENT.equals(nsUriElement.getName())) {
nsUris.add(check(new NsUri(nsUriElement.getAttribute(URI_ATTRIBUTE))));
}
}
final String repositoryUuid = Preconditions.checkNotNull(
repositoryElement.getAttribute(UUID_ATTRIBUTE), "Repository name attribute was null.");
final String _namespaceId = Preconditions.checkNotNull(
repositoryElement.getAttribute(NAMESPACE_ID_ATTRIBUTE), "Repository namespace argument was null.");
@Nullable final String toolingId = repositoryElement.getAttribute(TOOLING_ID_ATTRIBUTE);
@Nullable final String repositoryName = repositoryElement.getAttribute(NAME_ATTRIBUTE);
@Nullable final String dependsOnRepositoryUuid = repositoryElement.getAttribute(DEPENDS_ON_ATTRIBUTE);
final boolean metaRepository = Boolean.parseBoolean(nullToEmpty(repositoryElement.getAttribute(META_REPOSITORY_ATTRIBUTE)));
String existingRepository = namespaceIdsByRepositoryId.put(_namespaceId, repositoryName);
Preconditions.checkState(Strings.isNullOrEmpty(existingRepository), "Another repository '%s' is already using namespaceId '%s' of '%s' repository.", existingRepository, _namespaceId, repositoryName);
Byte namespaceId = null;
try {
namespaceId = Byte.decode(_namespaceId);
Preconditions.checkState(-1 < namespaceId.byteValue(), "Repository namespace ID should be an unsigned byte. Repository: " + repositoryUuid);
} catch (final NumberFormatException e) {
throw new IllegalStateException("Cannot specify repository namespace ID for repository [" + repositoryUuid + "]");
}
final T managedItem = createItem(repositoryUuid, repositoryName, namespaceId, toolingId, dependsOnRepositoryUuid, metaRepository);
managedItem.setContainer(this);
for (final NsUri nsUri : nsUris) {
_nsUriToItems.put(nsUri, managedItem);
}
}
nsUriToItems = Collections.unmodifiableMap(_nsUriToItems);
super.doBeforeActivate();
}
/* (non-Javadoc)
* @see org.eclipse.net4j.util.lifecycle.Lifecycle#doActivate()
*/
@Override
protected void doActivate() throws Exception {
LOGGER.info("Activating " + this.getClass().getSimpleName() + "...");
final Map<String, T> _uuidToItems = Maps.newHashMap();
final Map<NsUri, String> _nsUriToUuidMap = Maps.newHashMap();
final Map<Byte, String> _namespaceToUuidMap = Maps.newHashMap();
//initialize mapping after activating managed items one by one
for (final Iterator<Entry<NsUri, T>> itr = nsUriToItems.entrySet().iterator(); itr.hasNext(); /* */) {
final Entry<NsUri, T> entry = itr.next();
//activate managed item
LifecycleUtil.activate(entry.getValue());
final String uuid = entry.getValue().getUuid();
_nsUriToUuidMap.put(entry.getKey(), uuid);
_uuidToItems.put(uuid, entry.getValue());
_namespaceToUuidMap.put(entry.getValue().getNamespaceId(), uuid);
}
nsUriToUuidMap = Collections.unmodifiableMap(_nsUriToUuidMap);
uuidToItems = Collections.unmodifiableMap(_uuidToItems);
namespaceToUuidMap = Collections.unmodifiableMap(_namespaceToUuidMap);
super.doActivate();
LOGGER.info(this.getClass().getSimpleName() + " has been successfully activated.");
}
/* (non-Javadoc)
* @see org.eclipse.net4j.util.lifecycle.Lifecycle#doAfterActivate()
*/
@Override
protected void doAfterActivate() throws Exception {
Preconditions.checkNotNull(uuidToItems, "UUID to repository cache is not initialized yet.");
Preconditions.checkNotNull(nsUriToUuidMap, "Namespace URI to repository UUID cache is not initialized yet.");
eclassToNsUriMap = CacheBuilder.newBuilder().build(new CacheLoader<EClass, NsUri>() {
@Override public NsUri load(final EClass eClass) throws Exception {
Preconditions.checkNotNull(eClass, "EClass argument cannot be null.");
final EPackage ePackage = eClass.getEPackage();
Preconditions.checkNotNull(ePackage, "Cannot specify package for EClass. EClass: '" + eClass + "'.");
final String nsURI = ePackage.getNsURI();
Preconditions.checkState(!StringUtils.isEmpty(nsURI), "Namespace URI is not specified for EPackage. EPackage: '" + ePackage + "'.");
final NsUri candidateNsUri = getOrCreateNsUri(nsURI);
for (final Iterator<NsUri> itr = Iterators.unmodifiableIterator(nsUriToUuidMap.keySet().iterator()); itr.hasNext(); /* nothing */) {
final NsUri $ = itr.next();
if ($.equals(candidateNsUri)) {
return $;
}
}
LOGGER.warn("Unsupported EClass type: '" + eClass + "'.");
return NsUri.NULL_IMPL;
}
});
super.doAfterActivate();
}
/**Returns with the first managed item in an indeterministic fashion.*/
protected final T getFirst() {
checkActive();
if (CompareUtils.isEmpty(iterator())) {
throw new IllegalStateException("Managed items is empty.");
}
final T managedItem = Iterables.get(this, 0);
LifecycleUtil.checkActive(managedItem);
return managedItem;
}
/**
* (non-API)
*
* Returns with an iterator of the managed item. Requires inactive state.
*
* @return
*/
public final Iterator<T> _iterator() {
checkInactive();
return Iterators.unmodifiableIterator(nsUriToItems.values().iterator());
}
/**Returns with the unique ID of the managed item*/
protected abstract String getUuid(final T managedItem);
/**Creates a managed item instance based on the repository UUID, human readable name and the unique namespace ID.*/
protected abstract T createItem(final String repositoryUuid, @Nullable final String repositoryName, final byte namespaceId,
@Nullable final String toolingId, @Nullable final String dependsOnRepositoryUuid, final boolean metaRepository);
/*checks the existence of the package against the namespace URI*/
private NsUri check(final NsUri nsUri) {
Preconditions.checkNotNull(nsUri, "Namespace URI argument cannot be null.");
Preconditions.checkNotNull(Registry.INSTANCE.getEPackage(nsUri.getNsUri()), "EPackage does not exist for namespace URI: " + nsUri);
return nsUri;
}
/*safely returns with the namespace URI instance .*/
private static NsUri getOrCreateNsUri(final String nsUri) {
try {
return CACHE.get(nsUri);
} catch (final Throwable t) {
LOGGER.warn("Cannot get the namespace URI from cache. Creating a new instance instead.", t);
return new NsUri(Strings.nullToEmpty(nsUri));
}
}
} | core/com.b2international.snowowl.datastore/src/com/b2international/snowowl/datastore/cdo/CDOContainer.java | /*
* Copyright 2011-2015 B2i Healthcare Pte Ltd, http://b2i.sg
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.b2international.snowowl.datastore.cdo;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Strings.nullToEmpty;
import static com.google.common.base.Suppliers.memoize;
import static com.google.common.cache.CacheBuilder.newBuilder;
import static com.google.common.collect.Maps.newHashMap;
import static java.util.Collections.unmodifiableMap;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.annotation.Nullable;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtensionRegistry;
import org.eclipse.core.runtime.Platform;
import org.eclipse.emf.cdo.common.id.CDOID;
import org.eclipse.emf.cdo.common.model.CDOPackageRegistry;
import org.eclipse.emf.cdo.common.model.CDOPackageUnit;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EPackage.Registry;
import org.eclipse.net4j.util.lifecycle.Lifecycle;
import org.eclipse.net4j.util.lifecycle.LifecycleUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.b2international.commons.CompareUtils;
import com.b2international.commons.StringUtils;
import com.b2international.snowowl.core.api.NsUri;
import com.b2international.snowowl.datastore.index.AbstractIndexEntry;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.base.Supplier;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.Iterables;
import com.google.common.collect.Iterators;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
/**
* Basic CDO container implementation.
*
*/
public abstract class CDOContainer<T extends ICDOManagedItem<T>> extends Lifecycle implements ICDOContainer<T> {
/**Shared logger.*/
protected static final Logger LOGGER = LoggerFactory.getLogger(CDOContainer.class);
private static final LoadingCache<String, NsUri> CACHE;
static {
CACHE = CacheBuilder.newBuilder().build(new CacheLoader<String, NsUri>() {
@Override public NsUri load(final String nsUri) throws Exception {
return StringUtils.isEmpty(nsUri) ? NsUri.NULL_IMPL : new NsUri(nsUri);
}
});
}
private static final String REPOSITORY_EXT_ID = "com.b2international.snowowl.datastore.repository";
private static final String NS_URI_ELEMENT = "nsUri";
private static final String URI_ATTRIBUTE = "uri";
private static final String UUID_ATTRIBUTE = "uuid";
private static final String NAME_ATTRIBUTE = "name";
private static final String TOOLING_ID_ATTRIBUTE = "toolingId";
private static final String NAMESPACE_ID_ATTRIBUTE = "namespaceId";
private static final String META_REPOSITORY_ATTRIBUTE = "meta";
private static final String DEPENDS_ON_ATTRIBUTE = "dependsOn";
private final Supplier<Map<String, String>> masterToSlaveMappings = memoize(new Supplier<Map<String, String>>() {
public Map<String, String> get() {
final Map<String, String> masterToSlaveMappings = newHashMap();
for (final String uuid : uuidKeySet()) {
final T managedItem = getByUuid(uuid);
final String masterUuid = managedItem.getMasterUuid();
if (null != masterUuid) {
masterToSlaveMappings.put(masterUuid, uuid);
}
}
return unmodifiableMap(masterToSlaveMappings);
}
});
private final LoadingCache<Class<?>, T> classToItemCache = newBuilder().build(new CacheLoader<Class<?>, T>() {
public T load(final Class<?> clazz) throws Exception {
checkNotNull(clazz, "clazz");
for (final Iterator<T> itr = iterator(); itr.hasNext(); /**/) {
final T item = itr.next();
final CDOPackageRegistry packageRegistry = item.getPackageRegistry();
final CDOPackageUnit[] packageUnits = packageRegistry.getPackageUnits();
for (final CDOPackageUnit packageUnit : packageUnits) {
final EPackage[] ePackages = packageUnit.getEPackages(true);
for (final EPackage ePackage : ePackages) {
for (final EClassifier classifier : ePackage.getEClassifiers()) {
if (clazz == classifier.getInstanceClass()) {
return CDOContainer.this.get(ePackage);
}
}
}
}
}
throw new IllegalArgumentException("Cannot find managed item for class: " + clazz.getName());
}
});
/**Mapping between the EClasses and the unique model namespace URIs. Supports lazy loading.*/
private LoadingCache<EClass, NsUri> eclassToNsUriMap;
/**Mapping between the Ecore model namespace URIs and managed item UUIDs.*/
private Map<NsUri, String> nsUriToUuidMap;
/**Mapping between the UUID to the actual managed items.*/
private Map<String, T> uuidToItems;
/**Mapping between the unique repository namespace IDs and the managed item UUIDs.*/
private Map<Byte, String> namespaceToUuidMap;
/**Mapping between the Ecore model namespace URIs and the managed items.*/
private Map<NsUri, T> nsUriToItems;
@Override
public T get(final Class<?> clazz) {
return classToItemCache.getUnchecked(checkNotNull(clazz, "clazz"));
}
@Override
public T get(final EPackage ePackage) {
checkActive();
Preconditions.checkNotNull(ePackage, "EPackage argument cannot be null.");
return get(ePackage.getNsURI());
}
@Override
public T get(final String nsUri) {
checkActive();
return get(getOrCreateNsUri(Preconditions.checkNotNull(nsUri, "Namespace URI argument cannot be null.")));
}
@Override
public T get(final NsUri nsUri) {
checkActive();
Preconditions.checkNotNull(nsUri, "Namespace URI argument cannot be null.");
final String uuid = nsUriToUuidMap.get(nsUri);
if (StringUtils.isEmpty(uuid)) {
LOGGER.warn("Cannot find matching UUID for namespace URI: " + nsUri);
return null;
}
final T item = getByUuid(uuid);
if (null == item) {
LOGGER.warn("Cannot find managed item for namespace URI: " + nsUri);
return null;
}
LifecycleUtil.checkActive(item);
return item;
}
@Override
public T get(final EClass eClass) {
checkActive();
Preconditions.checkNotNull(eClass, "EClass argument cannot be null.");
return get(eClass.getEPackage());
}
@Override
public T get(final long cdoId) {
checkActive();
final byte terminologyNamaspaceId = (byte) (cdoId >> 56L);
final String uuid = namespaceToUuidMap.get(terminologyNamaspaceId);
if (StringUtils.isEmpty(uuid)) {
LOGGER.warn("Cannot find matching UUID for CDO ID: " + cdoId);
return null;
}
final T item = getByUuid(uuid);
if (null == item) {
LOGGER.warn("Cannot find managed item for CDO ID: " + cdoId);
return null;
}
LifecycleUtil.checkActive(item);
return item;
}
@Override
public T get(final Object object) {
checkActive();
Preconditions.checkNotNull(object, "Object argument cannot be null.");
if (object instanceof EObject) {
return get(((EObject) object).eClass());
} else if (object instanceof AbstractIndexEntry) {
return get(((AbstractIndexEntry) object).getStorageKey());
}
return null;
}
@Override
public T get(final CDOID cdoId) {
checkActive();
Preconditions.checkNotNull(cdoId, "CDO ID argument cannot be null.");
Preconditions.checkState(!cdoId.isTemporary(), "CDO ID was temporary.");
return get(CDOIDUtils.asLong(cdoId));
}
@Override
public T getByUuid(final String uuid) {
checkActive();
Preconditions.checkNotNull(uuid, "UUID argument cannot be null.");
return null == uuid ? null : uuidToItems.get(uuid);
}
@Override
public Iterator<T> iterator() {
checkActive();
return Iterators.unmodifiableIterator(uuidToItems.values().iterator());
}
@Override
public Set<String> uuidKeySet() {
return uuidToItems.keySet();
}
@Override
public boolean isMeta(final String uuid) {
return getByUuid(checkNotNull(uuid, "uuid")).isMeta();
}
@Override
@Nullable public String getMasterUuid(final String uuid) {
return getByUuid(checkNotNull(uuid, "uuid")).getMasterUuid();
}
@Override
@Nullable public String getSlaveUuid(final T managedItem) {
return getSlaveUuid(checkNotNull(managedItem, "managedItem").getUuid());
}
@Override
@Nullable public String getSlaveUuid(final String uuid) {
return masterToSlaveMappings.get().get(uuid);
}
/**
* (non-API)
* <br>
* Returns with a collection of {@link NsUri namespace URI}s with the associated managed item.
* @param managedItem the managed item.
* @return a collection of namespace URIs.
*/
public synchronized Iterable<NsUri> getNsUris(final T managedItem) {
Preconditions.checkNotNull(managedItem, "Managed item argument cannot be null.");
final Set<NsUri> $ = Sets.newHashSet();
for (final Entry<NsUri, T> entry : nsUriToItems.entrySet()) {
if (managedItem.equals(entry.getValue())) {
$.add(entry.getKey());
}
}
return Collections.unmodifiableCollection($);
}
@Override
protected void doDeactivate() throws Exception {
LOGGER.info("Deactivating " + this.getClass().getSimpleName() + "...");
if (null != uuidToItems) {
for (final Iterator<T> itr = Iterators.unmodifiableIterator(uuidToItems.values().iterator()); itr.hasNext(); /* nothing */) {
itr.next().deactivate();
}
}
if (null != nsUriToUuidMap) {
nsUriToUuidMap.clear();
nsUriToUuidMap = null;
}
if (null != eclassToNsUriMap) {
eclassToNsUriMap.cleanUp();
eclassToNsUriMap = null;
}
if (null != namespaceToUuidMap) {
namespaceToUuidMap.clear();
namespaceToUuidMap = null;
}
if (null != nsUriToItems) {
nsUriToItems.clear();
nsUriToItems = null;
}
super.deactivate();
LOGGER.info(this.getClass().getSimpleName() + " has been successfully deactivated.");
}
/* (non-Javadoc)
* @see org.eclipse.net4j.util.lifecycle.Lifecycle#doBeforeActivate()
*/
@Override
protected void doBeforeActivate() throws Exception {
final Map<NsUri, T> _nsUriToItems = Maps.newHashMap();
final IExtensionRegistry registry = Platform.getExtensionRegistry();
//load all CDO repository extensions, instantiate repositories and apply inverse mapping to the namespace URI
for (final IConfigurationElement repositoryElement : registry.getConfigurationElementsFor(REPOSITORY_EXT_ID)) {
final Set<NsUri> nsUris = Sets.newHashSet();
for (final IConfigurationElement nsUriElement : repositoryElement.getChildren()) {
if (NS_URI_ELEMENT.equals(nsUriElement.getName())) {
nsUris.add(check(new NsUri(nsUriElement.getAttribute(URI_ATTRIBUTE))));
}
}
final String repositoryUuid = Preconditions.checkNotNull(
repositoryElement.getAttribute(UUID_ATTRIBUTE), "Repository name attribute was null.");
final String _namespaceId = Preconditions.checkNotNull(
repositoryElement.getAttribute(NAMESPACE_ID_ATTRIBUTE), "Repository namespace argument was null.");
@Nullable final String toolingId = repositoryElement.getAttribute(TOOLING_ID_ATTRIBUTE);
@Nullable final String repositoryName = repositoryElement.getAttribute(NAME_ATTRIBUTE);
@Nullable final String dependsOnRepositoryUuid = repositoryElement.getAttribute(DEPENDS_ON_ATTRIBUTE);
final boolean metaRepository = Boolean.parseBoolean(nullToEmpty(repositoryElement.getAttribute(META_REPOSITORY_ATTRIBUTE)));
Byte namespaceId = null;
try {
namespaceId = Byte.decode(_namespaceId);
Preconditions.checkState(-1 < namespaceId.byteValue(), "Repository namespace ID should be an unsigned byte. Repository: " + repositoryUuid);
} catch (final NumberFormatException e) {
throw new IllegalStateException("Cannot specify repository namespace ID for repository [" + repositoryUuid + "]");
}
final T managedItem = createItem(repositoryUuid, repositoryName, namespaceId, toolingId, dependsOnRepositoryUuid, metaRepository);
managedItem.setContainer(this);
for (final NsUri nsUri : nsUris) {
_nsUriToItems.put(nsUri, managedItem);
}
}
nsUriToItems = Collections.unmodifiableMap(_nsUriToItems);
super.doBeforeActivate();
}
/* (non-Javadoc)
* @see org.eclipse.net4j.util.lifecycle.Lifecycle#doActivate()
*/
@Override
protected void doActivate() throws Exception {
LOGGER.info("Activating " + this.getClass().getSimpleName() + "...");
final Map<String, T> _uuidToItems = Maps.newHashMap();
final Map<NsUri, String> _nsUriToUuidMap = Maps.newHashMap();
final Map<Byte, String> _namespaceToUuidMap = Maps.newHashMap();
//initialize mapping after activating managed items one by one
for (final Iterator<Entry<NsUri, T>> itr = nsUriToItems.entrySet().iterator(); itr.hasNext(); /* */) {
final Entry<NsUri, T> entry = itr.next();
//activate managed item
LifecycleUtil.activate(entry.getValue());
final String uuid = entry.getValue().getUuid();
_nsUriToUuidMap.put(entry.getKey(), uuid);
_uuidToItems.put(uuid, entry.getValue());
_namespaceToUuidMap.put(entry.getValue().getNamespaceId(), uuid);
}
nsUriToUuidMap = Collections.unmodifiableMap(_nsUriToUuidMap);
uuidToItems = Collections.unmodifiableMap(_uuidToItems);
namespaceToUuidMap = Collections.unmodifiableMap(_namespaceToUuidMap);
super.doActivate();
LOGGER.info(this.getClass().getSimpleName() + " has been successfully activated.");
}
/* (non-Javadoc)
* @see org.eclipse.net4j.util.lifecycle.Lifecycle#doAfterActivate()
*/
@Override
protected void doAfterActivate() throws Exception {
Preconditions.checkNotNull(uuidToItems, "UUID to repository cache is not initialized yet.");
Preconditions.checkNotNull(nsUriToUuidMap, "Namespace URI to repository UUID cache is not initialized yet.");
eclassToNsUriMap = CacheBuilder.newBuilder().build(new CacheLoader<EClass, NsUri>() {
@Override public NsUri load(final EClass eClass) throws Exception {
Preconditions.checkNotNull(eClass, "EClass argument cannot be null.");
final EPackage ePackage = eClass.getEPackage();
Preconditions.checkNotNull(ePackage, "Cannot specify package for EClass. EClass: '" + eClass + "'.");
final String nsURI = ePackage.getNsURI();
Preconditions.checkState(!StringUtils.isEmpty(nsURI), "Namespace URI is not specified for EPackage. EPackage: '" + ePackage + "'.");
final NsUri candidateNsUri = getOrCreateNsUri(nsURI);
for (final Iterator<NsUri> itr = Iterators.unmodifiableIterator(nsUriToUuidMap.keySet().iterator()); itr.hasNext(); /* nothing */) {
final NsUri $ = itr.next();
if ($.equals(candidateNsUri)) {
return $;
}
}
LOGGER.warn("Unsupported EClass type: '" + eClass + "'.");
return NsUri.NULL_IMPL;
}
});
super.doAfterActivate();
}
/**Returns with the first managed item in an indeterministic fashion.*/
protected final T getFirst() {
checkActive();
if (CompareUtils.isEmpty(iterator())) {
throw new IllegalStateException("Managed items is empty.");
}
final T managedItem = Iterables.get(this, 0);
LifecycleUtil.checkActive(managedItem);
return managedItem;
}
/**
* (non-API)
*
* Returns with an iterator of the managed item. Requires inactive state.
*
* @return
*/
public final Iterator<T> _iterator() {
checkInactive();
return Iterators.unmodifiableIterator(nsUriToItems.values().iterator());
}
/**Returns with the unique ID of the managed item*/
protected abstract String getUuid(final T managedItem);
/**Creates a managed item instance based on the repository UUID, human readable name and the unique namespace ID.*/
protected abstract T createItem(final String repositoryUuid, @Nullable final String repositoryName, final byte namespaceId,
@Nullable final String toolingId, @Nullable final String dependsOnRepositoryUuid, final boolean metaRepository);
/*checks the existence of the package against the namespace URI*/
private NsUri check(final NsUri nsUri) {
Preconditions.checkNotNull(nsUri, "Namespace URI argument cannot be null.");
Preconditions.checkNotNull(Registry.INSTANCE.getEPackage(nsUri.getNsUri()), "EPackage does not exist for namespace URI: " + nsUri);
return nsUri;
}
/*safely returns with the namespace URI instance .*/
private static NsUri getOrCreateNsUri(final String nsUri) {
try {
return CACHE.get(nsUri);
} catch (final Throwable t) {
LOGGER.warn("Cannot get the namespace URI from cache. Creating a new instance instead.", t);
return new NsUri(Strings.nullToEmpty(nsUri));
}
}
} | SO-2165 #resolve | core/com.b2international.snowowl.datastore/src/com/b2international/snowowl/datastore/cdo/CDOContainer.java | SO-2165 #resolve |
|
Java | apache-2.0 | 3fc29bd63af6b543dbd0530a1e7c099e0d028f0c | 0 | lsmaira/gradle,robinverduijn/gradle,gradle/gradle,gstevey/gradle,lsmaira/gradle,gradle/gradle,robinverduijn/gradle,gstevey/gradle,blindpirate/gradle,robinverduijn/gradle,lsmaira/gradle,blindpirate/gradle,gradle/gradle,robinverduijn/gradle,lsmaira/gradle,blindpirate/gradle,blindpirate/gradle,blindpirate/gradle,lsmaira/gradle,gradle/gradle,gstevey/gradle,robinverduijn/gradle,lsmaira/gradle,robinverduijn/gradle,gradle/gradle,blindpirate/gradle,robinverduijn/gradle,gstevey/gradle,lsmaira/gradle,lsmaira/gradle,robinverduijn/gradle,gradle/gradle,robinverduijn/gradle,gstevey/gradle,gradle/gradle,gstevey/gradle,gradle/gradle,lsmaira/gradle,gradle/gradle,blindpirate/gradle,robinverduijn/gradle,lsmaira/gradle,gstevey/gradle,blindpirate/gradle,gstevey/gradle,blindpirate/gradle,blindpirate/gradle,gstevey/gradle,robinverduijn/gradle,gradle/gradle | /*
* Copyright 2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.integtests.fixtures;
import org.junit.runner.Description;
import org.junit.runner.RunWith;
import org.junit.runner.Runner;
import org.junit.runner.manipulation.*;
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunListener;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.Suite;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.RunnerBuilder;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
/**
* A base class for those test runners which execute a test multiple times.
*/
public abstract class AbstractMultiTestRunner extends Runner implements Filterable, Sortable {
protected final Class<?> target;
private Description description;
private final List<Execution> executions = new ArrayList<Execution>();
protected AbstractMultiTestRunner(Class<?> target) {
this.target = target;
}
@Override
public Description getDescription() {
initDescription();
return description;
}
@Override
public void run(RunNotifier notifier) {
initDescription();
for (Execution execution : executions) {
execution.run(notifier);
}
}
public void filter(Filter filter) throws NoTestsRemainException {
initExecutions();
for (Execution execution : executions) {
execution.filter(filter);
}
invalidateDescription();
}
public void sort(Sorter sorter) {
initExecutions();
for (Execution execution : executions) {
execution.sort(sorter);
}
invalidateDescription();
}
private void initExecutions() {
if (executions.isEmpty()) {
try {
createExecutions();
for (Execution execution : executions) {
execution.init(target);
}
} finally {
executionsCreated();
}
}
}
private void initDescription() {
initExecutions();
if (description == null) {
description = Description.createSuiteDescription(target);
for (Execution execution : executions) {
execution.addDescriptions(description);
}
}
}
private void invalidateDescription() {
description = null;
}
protected abstract void createExecutions();
protected void executionsCreated() {}
protected void add(Execution execution) {
executions.add(execution);
}
protected static abstract class Execution implements Sortable, Filterable {
private Runner runner;
protected Class<?> target;
private final Map<Description, Description> descriptionTranslations = new HashMap<Description, Description>();
final void init(Class<?> target) {
this.target = target;
if (isEnabled()) {
try {
assertCanExecute();
runner = createExecutionRunner();
} catch (Throwable t) {
runner = new CannotExecuteRunner(getDisplayName(), target, t);
}
} else {
runner = new IgnoredExecutionRunner(getDisplayName(), target);
}
}
private Runner createExecutionRunner() throws InitializationError {
List<? extends Class<?>> targetClasses = loadTargetClasses();
RunnerBuilder runnerBuilder = new RunnerBuilder() {
@Override
public Runner runnerForClass(Class<?> testClass) throws Throwable {
for (Class<?> candidate = testClass; candidate != null; candidate = candidate.getSuperclass()) {
RunWith runWith = candidate.getAnnotation(RunWith.class);
if (runWith != null && !AbstractMultiTestRunner.class.isAssignableFrom(runWith.value())) {
try {
return (Runner)runWith.value().getConstructors()[0].newInstance(testClass);
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
}
}
return new BlockJUnit4ClassRunner(testClass);
}
};
return new Suite(runnerBuilder, targetClasses.toArray(new Class<?>[targetClasses.size()])) {
@Override
public void run(RunNotifier notifier) {
before();
try {
super.run(notifier);
} finally {
after();
}
}
};
}
final void addDescriptions(Description parent) {
if (runner != null) {
map(runner.getDescription(), parent);
}
}
final void run(final RunNotifier notifier) {
RunNotifier nested = new RunNotifier();
nested.addListener(new RunListener() {
@Override
public void testStarted(Description description) {
Description translated = translateDescription(description);
notifier.fireTestStarted(translated);
}
@Override
public void testFailure(Failure failure) {
Description translated = translateDescription(failure.getDescription());
notifier.fireTestFailure(new Failure(translated, failure.getException()));
}
@Override
public void testAssumptionFailure(Failure failure) {
Description translated = translateDescription(failure.getDescription());
notifier.fireTestAssumptionFailed(new Failure(translated, failure.getException()));
}
@Override
public void testIgnored(Description description) {
Description translated = translateDescription(description);
notifier.fireTestIgnored(translated);
}
@Override
public void testFinished(Description description) {
Description translated = translateDescription(description);
notifier.fireTestFinished(translated);
}
});
runner.run(nested);
}
private Description translateDescription(Description description) {
return descriptionTranslations.containsKey(description) ? descriptionTranslations.get(description) : description;
}
public void filter(Filter filter) throws NoTestsRemainException {
if (runner instanceof Filterable) {
((Filterable) runner).filter(filter);
}
}
public void sort(Sorter sorter) {
if (runner instanceof Sortable) {
((Sortable) runner).sort(sorter);
}
}
protected void before() {
}
protected void after() {
}
private void map(Description source, Description parent) {
for (Description child : source.getChildren()) {
Description mappedChild;
if (child.getMethodName()!= null) {
mappedChild = Description.createSuiteDescription(String.format("%s [%s](%s)", child.getMethodName(), getDisplayName(), child.getClassName()));
parent.addChild(mappedChild);
} else {
mappedChild = Description.createSuiteDescription(child.getClassName());
}
descriptionTranslations.put(child, mappedChild);
map(child, parent);
}
}
/**
* Returns a display name for this execution. Used in the JUnit descriptions for test execution.
*/
protected abstract String getDisplayName();
/**
* Returns true if this execution should be executed, false if it should be ignored. Default is true.
*/
protected boolean isEnabled() {
return true;
}
/**
* Checks that this execution can be executed, throwing an exception if not.
*/
protected void assertCanExecute() {
}
/**
* Loads the target classes for this execution. Default is the target class that this runner was constructed with.
*/
protected List<? extends Class<?>> loadTargetClasses() {
return Collections.singletonList(target);
}
private static class IgnoredExecutionRunner extends Runner {
private final Description description;
public IgnoredExecutionRunner(String displayName, Class<?> testClass) {
description = Description.createSuiteDescription(String.format("%s(%s)", displayName, testClass.getName()));
}
@Override
public Description getDescription() {
return description;
}
@Override
public void run(RunNotifier notifier) {
notifier.fireTestIgnored(description);
}
}
private static class CannotExecuteRunner extends Runner {
private final Description description;
private final Throwable failure;
public CannotExecuteRunner(String displayName, Class<?> testClass, Throwable failure) {
description = Description.createSuiteDescription(String.format("%s(%s)", displayName, testClass.getName()));
this.failure = failure;
}
@Override
public Description getDescription() {
return description;
}
@Override
public void run(RunNotifier notifier) {
Description description = getDescription();
notifier.fireTestStarted(description);
notifier.fireTestFailure(new Failure(description, failure));
notifier.fireTestFinished(description);
}
}
}
}
| subprojects/internal-integ-testing/src/main/groovy/org/gradle/integtests/fixtures/AbstractMultiTestRunner.java | /*
* Copyright 2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.integtests.fixtures;
import org.junit.internal.builders.IgnoredClassRunner;
import org.junit.internal.runners.ErrorReportingRunner;
import org.junit.runner.Description;
import org.junit.runner.RunWith;
import org.junit.runner.Runner;
import org.junit.runner.manipulation.*;
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunListener;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.Suite;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.RunnerBuilder;
import java.util.*;
/**
* A base class for those test runners which execute a test multiple times.
*/
public abstract class AbstractMultiTestRunner extends Runner implements Filterable, Sortable {
protected final Class<?> target;
private Description description;
private final List<Execution> executions = new ArrayList<Execution>();
protected AbstractMultiTestRunner(Class<?> target) {
this.target = target;
}
@Override
public Description getDescription() {
initDescription();
return description;
}
@Override
public void run(RunNotifier notifier) {
initDescription();
for (Execution execution : executions) {
execution.run(notifier);
}
}
public void filter(Filter filter) throws NoTestsRemainException {
initExecutions();
for (Execution execution : executions) {
execution.filter(filter);
}
invalidateDescription();
}
public void sort(Sorter sorter) {
initExecutions();
for (Execution execution : executions) {
execution.sort(sorter);
}
invalidateDescription();
}
private void initExecutions() {
if (executions.isEmpty()) {
try {
createExecutions();
for (Execution execution : executions) {
execution.init(target);
}
} finally {
executionsCreated();
}
}
}
private void initDescription() {
initExecutions();
if (description == null) {
description = Description.createSuiteDescription(target);
for (Execution execution : executions) {
execution.addDescriptions(description);
}
}
}
private void invalidateDescription() {
description = null;
}
protected abstract void createExecutions();
protected void executionsCreated() {}
protected void add(Execution execution) {
executions.add(execution);
}
protected static abstract class Execution implements Sortable, Filterable {
private Runner runner;
protected Class<?> target;
private final Map<Description, Description> descriptionTranslations = new HashMap<Description, Description>();
final void init(Class<?> target) {
this.target = target;
if (isEnabled()) {
try {
assertCanExecute();
runner = createExecutionRunner();
} catch (Throwable t) {
runner = new ErrorReportingRunner(target, t);
}
} else {
runner = createIgnoredExecutionRunner();
}
}
private Runner createExecutionRunner() throws InitializationError {
List<? extends Class<?>> targetClasses = loadTargetClasses();
RunnerBuilder runnerBuilder = new RunnerBuilder() {
@Override
public Runner runnerForClass(Class<?> testClass) {
try {
for (Class<?> candidate = testClass; candidate != null; candidate = candidate.getSuperclass()) {
RunWith runWith = candidate.getAnnotation(RunWith.class);
if (runWith != null && !AbstractMultiTestRunner.class.isAssignableFrom(runWith.value())) {
try {
return (Runner)runWith.value().getConstructors()[0].newInstance(testClass);
} catch (Exception e) {
return new ErrorReportingRunner(testClass, e);
}
}
}
return new BlockJUnit4ClassRunner(testClass);
} catch (InitializationError initializationError) {
return new ErrorReportingRunner(testClass, initializationError);
}
}
};
return new Suite(runnerBuilder, targetClasses.toArray(new Class<?>[targetClasses.size()])) {
@Override
public void run(RunNotifier notifier) {
before();
try {
super.run(notifier);
} finally {
after();
}
}
};
}
private Runner createIgnoredExecutionRunner() {
return new IgnoredClassRunner(target) {
@Override
public Description getDescription() {
return Description.createSuiteDescription(String.format("%s(%s)", getDisplayName(), target.getName()));
}
};
}
final void addDescriptions(Description parent) {
if (runner != null) {
map(runner.getDescription(), parent);
}
}
final void run(final RunNotifier notifier) {
RunNotifier nested = new RunNotifier();
nested.addListener(new RunListener() {
@Override
public void testStarted(Description description) {
Description translated = translateDescription(description);
notifier.fireTestStarted(translated);
}
@Override
public void testFailure(Failure failure) {
Description translated = translateDescription(failure.getDescription());
notifier.fireTestFailure(new Failure(translated, failure.getException()));
}
@Override
public void testAssumptionFailure(Failure failure) {
Description translated = translateDescription(failure.getDescription());
notifier.fireTestAssumptionFailed(new Failure(translated, failure.getException()));
}
@Override
public void testIgnored(Description description) {
Description translated = translateDescription(description);
notifier.fireTestIgnored(translated);
}
@Override
public void testFinished(Description description) {
Description translated = translateDescription(description);
notifier.fireTestFinished(translated);
}
});
runner.run(nested);
}
private Description translateDescription(Description description) {
return descriptionTranslations.containsKey(description) ? descriptionTranslations.get(description) : description;
}
public void filter(Filter filter) throws NoTestsRemainException {
if (runner instanceof Filterable) {
((Filterable) runner).filter(filter);
}
}
public void sort(Sorter sorter) {
if (runner instanceof Sortable) {
((Sortable) runner).sort(sorter);
}
}
protected void before() {
}
protected void after() {
}
private void map(Description source, Description parent) {
for (Description child : source.getChildren()) {
Description mappedChild;
if (child.getMethodName()!= null) {
mappedChild = Description.createSuiteDescription(String.format("%s [%s](%s)", child.getMethodName(), getDisplayName(), child.getClassName()));
parent.addChild(mappedChild);
} else {
mappedChild = Description.createSuiteDescription(child.getClassName());
}
descriptionTranslations.put(child, mappedChild);
map(child, parent);
}
}
/**
* Returns a display name for this execution. Used in the JUnit descriptions for test execution.
*/
protected abstract String getDisplayName();
/**
* Returns true if this execution should be executed, false if it should be ignored. Default is true.
*/
protected boolean isEnabled() {
return true;
}
/**
* Checks that this execution can be executed, throwing an exception if not.
*/
protected void assertCanExecute() {
}
/**
* Loads the target classes for this execution. Default is the target class that this runner was constructed with.
*/
protected List<? extends Class<?>> loadTargetClasses() {
return Collections.singletonList(target);
}
}
}
| Improved reporting of failures when MultiTestRunner cannot execute suite
| subprojects/internal-integ-testing/src/main/groovy/org/gradle/integtests/fixtures/AbstractMultiTestRunner.java | Improved reporting of failures when MultiTestRunner cannot execute suite |
|
Java | apache-2.0 | 9fd334e748dc9da51554355c8ac046048829d8d0 | 0 | dinithis/stratos,apache/stratos,pkdevbox/stratos,pubudu538/stratos,hsbhathiya/stratos,asankasanjaya/stratos,hsbhathiya/stratos,gayangunarathne/stratos,Thanu/stratos,apache/stratos,Thanu/stratos,anuruddhal/stratos,anuruddhal/stratos,anuruddhal/stratos,pkdevbox/stratos,asankasanjaya/stratos,apache/stratos,Thanu/stratos,asankasanjaya/stratos,gayangunarathne/stratos,hsbhathiya/stratos,dinithis/stratos,pubudu538/stratos,ravihansa3000/stratos,pkdevbox/stratos,anuruddhal/stratos,ravihansa3000/stratos,ravihansa3000/stratos,ravihansa3000/stratos,asankasanjaya/stratos,pubudu538/stratos,pkdevbox/stratos,gayangunarathne/stratos,ravihansa3000/stratos,dinithis/stratos,pkdevbox/stratos,apache/stratos,hsbhathiya/stratos,anuruddhal/stratos,gayangunarathne/stratos,ravihansa3000/stratos,hsbhathiya/stratos,pubudu538/stratos,pkdevbox/stratos,Thanu/stratos,Thanu/stratos,gayangunarathne/stratos,pubudu538/stratos,apache/stratos,Thanu/stratos,anuruddhal/stratos,dinithis/stratos,anuruddhal/stratos,Thanu/stratos,dinithis/stratos,pubudu538/stratos,asankasanjaya/stratos,pkdevbox/stratos,pubudu538/stratos,asankasanjaya/stratos,hsbhathiya/stratos,dinithis/stratos,gayangunarathne/stratos,apache/stratos,apache/stratos,gayangunarathne/stratos,asankasanjaya/stratos,ravihansa3000/stratos,hsbhathiya/stratos,dinithis/stratos | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.stratos.rest.endpoint.api;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.stratos.autoscaler.stub.*;
import org.apache.stratos.cloud.controller.stub.*;
import org.apache.stratos.common.beans.*;
import org.apache.stratos.common.beans.application.ApplicationBean;
import org.apache.stratos.common.beans.application.ApplicationNetworkPartitionIdListBean;
import org.apache.stratos.common.beans.application.GroupBean;
import org.apache.stratos.common.beans.application.domain.mapping.ApplicationDomainMappingsBean;
import org.apache.stratos.common.beans.application.domain.mapping.DomainMappingBean;
import org.apache.stratos.common.beans.application.signup.ApplicationSignUpBean;
import org.apache.stratos.common.beans.artifact.repository.GitNotificationPayloadBean;
import org.apache.stratos.common.beans.cartridge.CartridgeBean;
import org.apache.stratos.common.beans.kubernetes.KubernetesClusterBean;
import org.apache.stratos.common.beans.kubernetes.KubernetesHostBean;
import org.apache.stratos.common.beans.kubernetes.KubernetesMasterBean;
import org.apache.stratos.common.beans.partition.NetworkPartitionBean;
import org.apache.stratos.common.beans.policy.autoscale.AutoscalePolicyBean;
import org.apache.stratos.common.beans.policy.deployment.ApplicationPolicyBean;
import org.apache.stratos.common.beans.policy.deployment.DeploymentPolicyBean;
import org.apache.stratos.common.beans.topology.ApplicationInfoBean;
import org.apache.stratos.common.beans.topology.ClusterBean;
import org.apache.stratos.common.exception.InvalidEmailException;
import org.apache.stratos.manager.service.stub.StratosManagerServiceApplicationSignUpExceptionException;
import org.apache.stratos.manager.service.stub.StratosManagerServiceDomainMappingExceptionException;
import org.apache.stratos.rest.endpoint.Utils;
import org.apache.stratos.rest.endpoint.annotation.AuthorizationAction;
import org.apache.stratos.rest.endpoint.annotation.SuperTenantService;
import org.apache.stratos.rest.endpoint.exception.*;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
/**
* Stratos API v4.1 for Stratos 4.1.0 release.
*/
@Path("/")
public class StratosApiV41 extends AbstractApi {
private static final Log log = LogFactory.getLog(StratosApiV41.class);
@Context
HttpServletRequest httpServletRequest;
@Context
UriInfo uriInfo;
/**
* This method is used by clients such as the CLI to verify the Stratos manager URL.
*
* @return the response
* @throws RestAPIException the rest api exception
*/
@GET
@Path("/init")
@AuthorizationAction("/permission/admin/restlogin")
public Response initialize()
throws RestAPIException {
ResponseMessageBean response = new ResponseMessageBean(ResponseMessageBean.SUCCESS,
"Successfully authenticated");
return Response.ok(response).build();
}
/**
* This method gets called by the client who are interested in using session mechanism to authenticate
* themselves in subsequent calls. This method call get authenticated by the basic authenticator.
* Once the authenticated call received, the method creates a session and returns the session id.
*
* @return The session id related with the session
*/
@GET
@Path("/session")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/restlogin")
public Response getSession() {
HttpSession httpSession = httpServletRequest.getSession(true);//create session if not found
PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
httpSession.setAttribute("userName", carbonContext.getUsername());
httpSession.setAttribute("tenantDomain", carbonContext.getTenantDomain());
httpSession.setAttribute("tenantId", carbonContext.getTenantId());
String sessionId = httpSession.getId();
return Response.ok().header("WWW-Authenticate", "Basic").type(MediaType.APPLICATION_JSON).
entity(Utils.buildAuthenticationSuccessMessage(sessionId)).build();
}
/**
* Creates the cartridge definition.
*
* @param cartridgeDefinitionBean the cartridge definition bean
* @return 201 if cartridge is successfully created, 409 if cartridge already exists.
* @throws RestAPIException the rest api exception
*/
@POST
@Path("/cartridges")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/addCartridge")
public Response addCartridge(
CartridgeBean cartridgeDefinitionBean) throws RestAPIException {
String cartridgeType = cartridgeDefinitionBean.getType();
CartridgeBean cartridgeBean = StratosApiV41Utils.getCartridgeForValidate(cartridgeType);
if (cartridgeBean != null) {
String msg = String.format("Cartridge already exists: [cartridge-type] %s", cartridgeType);
log.warn(msg);
return Response.status(Response.Status.CONFLICT)
.entity(new ResponseMessageBean(ResponseMessageBean.ERROR, msg)).build();
}
StratosApiV41Utils.addCartridge(cartridgeDefinitionBean);
URI url = uriInfo.getAbsolutePathBuilder().path(cartridgeType).build();
return Response.created(url).entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Cartridge added successfully: [cartridge-type] %s", cartridgeType))).build();
}
/**
* Creates the Deployment Policy Definition.
*
* @param deploymentPolicyDefinitionBean the deployment policy bean
* @return 201 if deployment policy is successfully added
* @throws RestAPIException the rest api exception
*/
@POST
@Path("/deploymentPolicies")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/addDeploymentPolicy")
public Response addDeploymentPolicy(
DeploymentPolicyBean deploymentPolicyDefinitionBean) throws RestAPIException {
String deploymentPolicyID = deploymentPolicyDefinitionBean.getId();
try {
// TODO :: Deployment policy validation
StratosApiV41Utils.addDeploymentPolicy(deploymentPolicyDefinitionBean);
} catch (AutoscalerServiceInvalidDeploymentPolicyExceptionException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Deployment policy is not valid")).build();
} catch (AutoscalerServiceDeploymentPolicyAlreadyExistsExceptionException e) {
return Response.status(Response.Status.CONFLICT).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Deployment policy already exists")).build();
}
URI url = uriInfo.getAbsolutePathBuilder().path(deploymentPolicyID).build();
return Response.created(url).entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Deployment policy added successfully: " + "[deployment-policy-id] %s",
deploymentPolicyID))).build();
}
/**
* Get deployment policy by deployment policy id
*
* @return 200 if deployment policy is found, 404 if not
* @throws RestAPIException
*/
@GET
@Path("/deploymentPolicies/{deploymentPolicyId}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/getDeploymentPolicy")
public Response getDeploymentPolicy(
@PathParam("deploymentPolicyId") String deploymentPolicyId) throws RestAPIException {
DeploymentPolicyBean deploymentPolicyBean = StratosApiV41Utils.getDeployementPolicy(deploymentPolicyId);
if (deploymentPolicyBean == null) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Deployment policy not found")).build();
}
return Response.ok(deploymentPolicyBean).build();
}
/**
* Get deployment policies
*
* @return 200 with the list of deployment policies
* @throws RestAPIException
*/
@GET
@Path("/deploymentPolicies")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/getDeploymentPolicy")
public Response getDeploymentPolicies()
throws RestAPIException {
DeploymentPolicyBean[] deploymentPolicies = StratosApiV41Utils.getDeployementPolicies();
if (deploymentPolicies == null || deploymentPolicies.length == 0) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "No deployment policies found")).build();
}
return Response.ok(deploymentPolicies).build();
}
/**
* Updates the Deployment Policy Definition.
*
* @param deploymentPolicyDefinitionBean the deployment policy bean
* @return 200 if deployment policy is successfully updated
* @throws RestAPIException the rest api exception
*/
@PUT
@Path("/deploymentPolicies")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/updateDeploymentPolicy")
public Response updateDeploymentPolicy(
DeploymentPolicyBean deploymentPolicyDefinitionBean) throws RestAPIException {
String deploymentPolicyID = deploymentPolicyDefinitionBean.getId();
// TODO :: Deployment policy validation
try {
StratosApiV41Utils.updateDeploymentPolicy(deploymentPolicyDefinitionBean);
} catch (AutoscalerServiceInvalidPolicyExceptionException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Deployment policy is invalid")).build();
} catch (AutoscalerServiceInvalidDeploymentPolicyExceptionException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Deployment policy is invalid")).build();
} catch (AutoscalerServiceDeploymentPolicyNotExistsExceptionException e) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Deployment policy not found")).build();
}
URI url = uriInfo.getAbsolutePathBuilder().path(deploymentPolicyID).build();
return Response.ok(url).entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Deployment policy updated successfully: " + "[deployment-policy-id] %s",
deploymentPolicyID))).build();
}
/**
* Updates the Deployment Policy Definition.
*
* @param deploymentPolicyID the deployment policy id
* @return 200 if deployment policy is successfully removed
* @throws RestAPIException the rest api exception
*/
@DELETE
@Path("/deploymentPolicies/{depolymentPolicyID}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/removeDeploymentPolicy")
public Response removeDeploymentPolicy(
@PathParam("depolymentPolicyID") String deploymentPolicyID) throws RestAPIException {
try {
StratosApiV41Utils.removeDeploymentPolicy(deploymentPolicyID);
} catch (AutoscalerServiceDeploymentPolicyNotExistsExceptionException e) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Autoscaling policy not found")).build();
}
URI url = uriInfo.getAbsolutePathBuilder().path(deploymentPolicyID).build();
return Response.ok(url).entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Deployment policy removed successfully: " + "[deployment-policy-id] %s",
deploymentPolicyID))).build();
}
/**
* Updates the cartridge definition.
*
* @param cartridgeDefinitionBean the cartridge definition bean
* @return 201 if cartridge successfully updated
* @throws RestAPIException the rest api exception
*/
@PUT
@Path("/cartridges")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/updateCartridge")
public Response updateCartridge(
CartridgeBean cartridgeDefinitionBean) throws RestAPIException {
StratosApiV41Utils.updateCartridge(cartridgeDefinitionBean);
URI url = uriInfo.getAbsolutePathBuilder().path(cartridgeDefinitionBean.getType()).build();
return Response.ok(url)
.entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS, "Cartridge updated successfully"))
.build();
}
/**
* Gets all available cartridges.
*
* @return 200 if cartridges exists, 404 if no cartridges found
* @throws RestAPIException the rest api exception
*/
@GET
@Path("/cartridges")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/getCartridge")
public Response getCartridges()
throws RestAPIException {
//We pass null to searching string and multi-tenant parameter since we do not need to do any filtering
List<CartridgeBean> cartridges = StratosApiV41Utils.getAvailableCartridges(null, null, getConfigContext());
if (cartridges == null || cartridges.isEmpty()) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "No cartridges found")).build();
}
CartridgeBean[] cartridgeArray = cartridges.toArray(new CartridgeBean[cartridges.size()]);
return Response.ok().entity(cartridgeArray).build();
}
/**
* Gets a single cartridge by type
*
* @param cartridgeType Cartridge type
* @return 200 if specified cartridge exists, 404 if not
* @throws RestAPIException
*/
@GET
@Path("/cartridges/{cartridgeType}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/getCartridge")
public Response getCartridge(
@PathParam("cartridgeType") String cartridgeType) throws RestAPIException {
CartridgeBean cartridge;
try {
cartridge = StratosApiV41Utils.getCartridge(cartridgeType);
return Response.ok().entity(cartridge).build();
} catch (RestAPIException e) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Cartridge not found")).build();
}
}
/**
* Returns cartridges by category.
*
* @param filter Filter
* @param criteria Criteria
* @return 200 if cartridges are found for specified filter, 404 if none found
* @throws RestAPIException
*/
@GET
@Path("/cartridges/filter/{filter}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/getCartridgesByFilter")
public Response getCartridgesByFilter(
@DefaultValue("") @PathParam("filter") String filter, @QueryParam("criteria") String criteria)
throws RestAPIException {
List<CartridgeBean> cartridges = StratosApiV41Utils.
getCartridgesByFilter(filter, criteria, getConfigContext());
if (cartridges == null || cartridges.isEmpty()) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "No cartridges found")).build();
}
CartridgeBean[] cartridgeArray = cartridges.toArray(new CartridgeBean[cartridges.size()]);
return Response.ok().entity(cartridgeArray).build();
}
/**
* Returns a specific cartridge by category.
*
* @param filter Filter
* @param cartridgeType Cartridge Type
* @return 200 if a cartridge is found for specified filter, 404 if none found
* @throws RestAPIException
*/
@GET
@Path("/cartridges/{cartridgeType}/filter/{filter}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/getCartridgesByFilter")
public Response getCartridgeByFilter(
@PathParam("cartridgeType") String cartridgeType, @DefaultValue("") @PathParam("filter") String filter)
throws RestAPIException {
CartridgeBean cartridge;
cartridge = StratosApiV41Utils.getCartridgeByFilter(filter, cartridgeType, getConfigContext());
if (cartridge == null) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "No cartridges found for this filter")).build();
}
return Response.ok().entity(cartridge).build();
}
/**
* Deletes a cartridge definition.
*
* @param cartridgeType the cartridge type
* @return 200 if cartridge is successfully removed
* @throws RestAPIException the rest api exception
*/
@DELETE
@Path("/cartridges/{cartridgeType}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/removeCartridge")
public Response removeCartridge(
@PathParam("cartridgeType") String cartridgeType) throws RestAPIException {
StratosApiV41Utils.removeCartridge(cartridgeType);
return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Cartridge deleted successfully: [cartridge-type] %s", cartridgeType))).build();
}
// API methods for cartridge groups
/**
* Creates the cartridge group definition.
*
* @param serviceGroupDefinition the cartridge group definition
* @return 201 if group added successfully
* @throws RestAPIException the rest api exception
*/
@POST
@Path("/cartridgeGroups")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/addServiceGroup")
@SuperTenantService(true)
public Response addServiceGroup(
GroupBean serviceGroupDefinition) throws RestAPIException {
try {
StratosApiV41Utils.addServiceGroup(serviceGroupDefinition);
URI url = uriInfo.getAbsolutePathBuilder().path(serviceGroupDefinition.getName()).build();
return Response.created(url).entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Cartridge Group added successfully: [cartridge-group] %s",
serviceGroupDefinition.getName()))).build();
} catch (InvalidCartridgeGroupDefinitionException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, e.getMessage())).build();
} catch (RestAPIException e) {
if (e.getCause().getMessage().contains("already exists")) {
return Response.status(Response.Status.CONFLICT).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Cartridge group not found")).build();
} else if (e.getCause().getMessage().contains("Invalid Service Group")) {
return Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, e.getCause().getMessage())).build();
} else {
throw e;
}
}
}
/**
* Gets the cartridge group definition.
*
* @param groupDefinitionName the group definition name
* @return 200 if cartridge group found for group definition, 404 if none is found
* @throws RestAPIException the rest api exception
*/
@GET
@Path("/cartridgeGroups/{groupDefinitionName}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/getServiceGroupDefinition")
public Response getServiceGroupDefinition(
@PathParam("groupDefinitionName") String groupDefinitionName) throws RestAPIException {
GroupBean serviceGroupDefinition = StratosApiV41Utils.getServiceGroupDefinition(groupDefinitionName);
if (serviceGroupDefinition != null) {
return Response.ok().entity(serviceGroupDefinition).build();
} else {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Cartridge group not found")).build();
}
}
/**
* Gets all cartridge groups created.
*
* @return 200 if cartridge groups are found, 404 if none found
* @throws RestAPIException the rest api exception
*/
@GET
@Path("/cartridgeGroups")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/getServiceGroupDefinition")
public Response getServiceGroups()
throws RestAPIException {
GroupBean[] serviceGroups = StratosApiV41Utils.getServiceGroupDefinitions();
if (serviceGroups != null) {
return Response.ok().entity(serviceGroups).build();
} else {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Cartridge group not found")).build();
}
}
/**
* Delete cartridge group definition.
*
* @param groupDefinitionName the group definition name
* @return 200 if cartridge group is successfully removed
* @throws RestAPIException the rest api exception
*/
@DELETE
@Path("/cartridgeGroups/{groupDefinitionName}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/removeServiceGroup")
@SuperTenantService(true)
public Response removeServiceGroup(
@PathParam("groupDefinitionName") String groupDefinitionName) throws RestAPIException {
try {
StratosApiV41Utils.removeServiceGroup(groupDefinitionName);
} catch (AutoscalerServiceCartridgeGroupNotFoundExceptionException e) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Cartridge group not found")).build();
}
return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Cartridge Group deleted successfully: [cartridge-group] %s", groupDefinitionName)))
.build();
}
// API methods for network partitions
/**
* Add network partition
*
* @param networkPartitionBean Network Partition
* @return 201 if network partition successfully added, 409 if network partition already exists
* @throws RestAPIException
*/
@POST
@Path("/networkPartitions")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/addNetworkPartition")
public Response addNetworkPartition(
NetworkPartitionBean networkPartitionBean) throws RestAPIException {
String networkPartitionId = networkPartitionBean.getId();
try {
StratosApiV41Utils.addNetworkPartition(networkPartitionBean);
} catch (CloudControllerServiceNetworkPartitionAlreadyExistsExceptionException e) {
return Response.status(Response.Status.CONFLICT)
.entity(new ResponseMessageBean(ResponseMessageBean.ERROR, e.getMessage()))
.build();
}
URI url = uriInfo.getAbsolutePathBuilder().path(networkPartitionId).build();
return Response.created(url).entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Network partition added successfully: [network-partition] %s", networkPartitionId)))
.build();
}
/**
* Get network partitions
*
* @return 200 if network partitions are found
* @throws RestAPIException
*/
@GET
@Path("/networkPartitions")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/getNetworkPartitions")
public Response getNetworkPartitions()
throws RestAPIException {
NetworkPartitionBean[] networkPartitions = StratosApiV41Utils.getNetworkPartitions();
if (networkPartitions == null || networkPartitions.length == 0) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.SUCCESS, "No network partitions found")).build();
}
return Response.ok(networkPartitions).build();
}
/**
* Get network partition by network partition id
*
* @return 200 if specified network partition is found
* @throws RestAPIException
*/
@GET
@Path("/networkPartitions/{networkPartitionId}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/getNetworkPartitions")
public Response getNetworkPartition(
@PathParam("networkPartitionId") String networkPartitionId) throws RestAPIException {
NetworkPartitionBean networkPartition = StratosApiV41Utils.getNetworkPartition(networkPartitionId);
if (networkPartition == null) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Network partition is not found")).build();
}
return Response.ok(networkPartition).build();
}
/**
* Remove network partition by network partition id
*
* @return 200 if specified network partition is successfully deleted, 404 if specified network partition is not
* found
* @throws RestAPIException
*/
@DELETE
@Path("/networkPartitions/{networkPartitionId}")
@AuthorizationAction("/permission/protected/manage/removeNetworkPartition")
public Response removeNetworkPartition(
@PathParam("networkPartitionId") String networkPartitionId) throws RestAPIException {
try {
StratosApiV41Utils.removeNetworkPartition(networkPartitionId);
} catch (CloudControllerServiceNetworkPartitionNotExistsExceptionException e) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Network partition is not found")).build();
}
return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Network partition deleted successfully: [network-partition] %s",
networkPartitionId))).build();
}
// API methods for applications
/**
* Add application
*
* @param applicationDefinition Application Definition
* @return 201 if application is successfully added
* @throws RestAPIException
*/
@POST
@Path("/applications")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/addApplication")
public Response addApplication(ApplicationBean applicationDefinition) throws RestAPIException {
try {
StratosApiV41Utils.addApplication(applicationDefinition, getConfigContext(), getUsername(), getTenantDomain());
URI url = uriInfo.getAbsolutePathBuilder().path(applicationDefinition.getApplicationId()).build();
return Response.created(url).entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Application added successfully: [application] %s",
applicationDefinition.getApplicationId()))).build();
} catch (ApplicationAlreadyExistException e) {
return Response.status(Response.Status.CONFLICT).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Application already exists")).build();
} catch (RestAPIException e) {
throw e;
}
}
/**
* Add application
*
* @param applicationDefinition Application Definition
* @return 201 if application is successfully added
* @throws RestAPIException
*/
@PUT
@Path("/applications")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/addApplication")
public Response updateApplication(ApplicationBean applicationDefinition) throws RestAPIException {
StratosApiV41Utils.updateApplication(applicationDefinition, getConfigContext(), getUsername(), getTenantDomain());
URI url = uriInfo.getAbsolutePathBuilder().path(applicationDefinition.getApplicationId()).build();
return Response.created(url).entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Application updated successfully: [application] %s",
applicationDefinition.getApplicationId()))).build();
}
/**
* Return applications
*
* @return 200 if applications are found
* @throws RestAPIException
*/
@GET
@Path("/applications")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/getApplications")
public Response getApplications() throws RestAPIException {
List<ApplicationBean> applicationDefinitions = StratosApiV41Utils.getApplications();
if (applicationDefinitions == null || applicationDefinitions.isEmpty()) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "No applications found")).build();
}
ApplicationBean[] applicationDefinitionsArray = applicationDefinitions
.toArray(new ApplicationBean[applicationDefinitions.size()]);
return Response.ok(applicationDefinitionsArray).build();
}
/**
* Gets the application.
*
* @param applicationId the application id
* @return 200 if specified application is found, 404 if not
* @throws RestAPIException the rest api exception
*/
@GET
@Path("/applications/{applicationId}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/getApplications")
public Response getApplication(
@PathParam("applicationId") String applicationId) throws RestAPIException {
ApplicationBean applicationDefinition = StratosApiV41Utils.getApplication(applicationId);
if (applicationDefinition == null) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Application not found")).build();
}
return Response.ok(applicationDefinition).build();
}
/**
* Deploy application.
*
* @param applicationId Application Id
* @param applicationPolicyId the application policy id
* @return 202 after deployment process is started. Deployment is asynchronous
* @throws RestAPIException the rest api exception
*/
@POST
@Path("/applications/{applicationId}/deploy/{applicationPolicyId}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/deployApplication")
public Response deployApplication(
@PathParam("applicationId") String applicationId,
@PathParam("applicationPolicyId") String applicationPolicyId) throws RestAPIException {
try {
StratosApiV41Utils.deployApplication(applicationId, applicationPolicyId);
return Response.accepted().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Application deployed successfully: [application] %s", applicationId))).build();
} catch (ApplicationAlreadyDeployedException e) {
return Response.status(Response.Status.CONFLICT).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Application policy already deployed")).build();
} catch (RestAPIException e) {
throw e;
}
}
/**
* Adds an application policy
*
* @param applicationPolicy Application Policy
* @return 201 if the application policy is successfully added
* @throws RestAPIException
*/
@POST
@Path("/applicationPolicies")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/addApplicationPolicy")
public Response addApplicationPolicy(
ApplicationPolicyBean applicationPolicy) throws RestAPIException {
try {
StratosApiV41Utils.addApplicationPolicy(applicationPolicy);
URI url = uriInfo.getAbsolutePathBuilder().path(applicationPolicy.getId()).build();
return Response.created(url).entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Application policy added successfully: [application-policy] %s",
applicationPolicy.getId()))).build();
} catch (RestAPIException e) {
throw e;
} catch (AutoscalerServiceInvalidApplicationPolicyExceptionException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Invalid application policy")).build();
}
}
/**
* Retrieve specified application policy
*
* @param applicationPolicyId Application Policy Id
* @return 200 if application policy is found
* @throws RestAPIException
*/
@GET
@Path("/applicationPolicies/{applicationPolicyId}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/getApplicationPolicy")
public Response getApplicationPolicy(
@PathParam("applicationPolicyId") String applicationPolicyId) throws RestAPIException {
try {
ApplicationPolicyBean applicationPolicyBean = StratosApiV41Utils.getApplicationPolicy(applicationPolicyId);
if (applicationPolicyBean == null) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Application policy not found: [application-policy] " +
applicationPolicyId)).build();
}
return Response.ok(applicationPolicyBean).build();
} catch (ApplicationPolicyIdIsEmptyException e) {
return Response.status(Response.Status.BAD_REQUEST).build();
}
}
/**
* Retrieve all application policies
*
* @return 200
* @throws RestAPIException
*/
@GET
@Path("/applicationPolicies")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/getApplicationPolicies")
public Response getApplicationPolicies()
throws RestAPIException {
ApplicationPolicyBean[] applicationPolicies = StratosApiV41Utils.getApplicationPolicies();
if (applicationPolicies == null || applicationPolicies.length == 0) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "No application policies found")).build();
}
return Response.ok().entity(applicationPolicies).build();
}
/**
* Remove specified application policy
*
* @param applicationPolicyId Application Policy Id
* @return 200 if application policy is successfully removed
* @throws RestAPIException
*/
@DELETE
@Path("/applicationPolicies/{applicationPolicyId}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/removeApplicationPolicy")
public Response removeApplicationPolicy(
@PathParam("applicationPolicyId") String applicationPolicyId) throws RestAPIException {
try {
StratosApiV41Utils.removeApplicationPolicy(applicationPolicyId);
return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Application policy deleted successfully: [application-policy] %s",
applicationPolicyId))).build();
} catch (ApplicationPolicyIdIsEmptyException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Autoscaling policy id is empty"))
.build();
} catch (AutoscalerServiceInvalidPolicyExceptionException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Autoscaling policy is invalid"))
.build();
}
}
/**
* Update application policy
*
* @param applicationPolicy Application Policy
* @return 200 if application policies successfully updated
* @throws RestAPIException
*/
@PUT
@Path("/applicationPolicies")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/updateApplicationPolicy")
public Response updateApplicationPolicy(
ApplicationPolicyBean applicationPolicy) throws RestAPIException {
try {
StratosApiV41Utils.updateApplicationPolicy(applicationPolicy);
} catch (AutoscalerServiceInvalidApplicationPolicyExceptionException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Invalid application policy"))
.build();
} catch (AutoscalerServiceApplicatioinPolicyNotExistsExceptionException e) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, String.format("Application policy not found: [application-policy] %s",
applicationPolicy.getId()))).build();
}
return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Application policy updated successfully: [application-policy] %s",
applicationPolicy.getId()))).build();
}
/**
* Get network partition ids used in an application
*
* @return 200
* @throws RestAPIException
*/
@GET
@Path("/applications/{applicationId}/networkPartitions")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/getApplicationNetworkPartitions")
public Response getApplicationNetworkPartitions(
@PathParam("applicationId") String applicationId) throws RestAPIException {
ApplicationNetworkPartitionIdListBean appNetworkPartitionsBean = StratosApiV41Utils
.getApplicationNetworkPartitions(applicationId);
if (appNetworkPartitionsBean == null ||
(appNetworkPartitionsBean.getNetworkPartitionIds().size() == 1 &&
appNetworkPartitionsBean.getNetworkPartitionIds().get(0) == null)) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "No network partitions found in the application")).build();
}
return Response.ok(appNetworkPartitionsBean).build();
}
/**
* Signs up for an application.
*
* @param applicationId the application id
* @param applicationSignUpBean the application sign up bean
* @return 200 if application sign up was successfull
* @throws RestAPIException the rest api exception
*/
@POST
@Path("/applications/{applicationId}/signup")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/addApplicationSignUp")
public Response addApplicationSignUp(
@PathParam("applicationId") String applicationId, ApplicationSignUpBean applicationSignUpBean)
throws RestAPIException {
StratosApiV41Utils.addApplicationSignUp(applicationId, applicationSignUpBean);
URI url = uriInfo.getAbsolutePathBuilder().path(applicationId).build();
return Response.created(url).entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Successfully signed up for: [application] %s", applicationId))).build();
}
/**
* Gets the application sign up.
*
* @param applicationId the application id
* @return 200 if specified application signup is found, 404 if not
* @throws RestAPIException the rest api exception
*/
@GET
@Path("/applications/{applicationId}/signup")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/getApplicationSignUp")
public Response getApplicationSignUp(
@PathParam("applicationId") String applicationId) throws RestAPIException,
StratosManagerServiceApplicationSignUpExceptionException {
ApplicationSignUpBean applicationSignUpBean;
try {
applicationSignUpBean = StratosApiV41Utils.getApplicationSignUp(applicationId);
if (applicationSignUpBean == null) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "No application signups found for application: [application]" +
applicationId)).build();
}
return Response.ok(applicationSignUpBean).build();
} catch (ApplicationSignUpRestAPIException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Invalid request to get application signups")).build();
}
}
/**
* Removes the application sign up.
*
* @param applicationId the application id
* @return 200 if specified application sign up is removed
* @throws RestAPIException the rest api exception
*/
@DELETE
@Path("/applications/{applicationId}/signup")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/removeApplicationSignUp")
public Response removeApplicationSignUp(
@PathParam("applicationId") String applicationId) throws RestAPIException {
StratosApiV41Utils.removeApplicationSignUp(applicationId);
return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Application sign up removed successfully: [application] %s", applicationId))).build();
}
/**
* Adds the domain mappings for an application.
*
* @param applicationId the application id
* @param domainMappingsBean the domain mappings bean
* @return 200
* @throws RestAPIException the rest api exception
*/
@POST
@Path("/applications/{applicationId}/domainMappings")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/addDomainMappings")
public Response addDomainMappings(
@PathParam("applicationId") String applicationId, ApplicationDomainMappingsBean domainMappingsBean)
throws RestAPIException {
try {
StratosApiV41Utils.addApplicationDomainMappings(applicationId, domainMappingsBean);
} catch (StratosManagerServiceDomainMappingExceptionException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Incorrect request to add domain mapping for " +
"application")).build();
}
List<DomainMappingBean> mappings = domainMappingsBean.getDomainMappings();
List<String> domainMappingList = new ArrayList<String>();
for (DomainMappingBean domainMappingBean : mappings) {
domainMappingList.add(domainMappingBean.getDomainName());
}
URI url = uriInfo.getAbsolutePathBuilder().path(applicationId).build();
return Response.created(url).entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Domain mappings added successfully: [domain-mappings] %s", domainMappingList)))
.build();
}
/**
* Removes the domain mappings for an application.
*
* @param applicationId the application id
* @param domainMapppingsBean the domain mapppings bean
* @return 200
* @throws RestAPIException the rest api exception
*/
@DELETE
@Path("/applications/{applicationId}/domainMappings")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/removeDomainMappings")
public Response removeDomainMappings(
@PathParam("applicationId") String applicationId, ApplicationDomainMappingsBean domainMapppingsBean)
throws RestAPIException {
try {
StratosApiV41Utils.removeApplicationDomainMappings(applicationId, domainMapppingsBean);
} catch (StratosManagerServiceDomainMappingExceptionException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Incorrect request to delete domain mapping of " +
"application")).build();
}
List<DomainMappingBean> mappings = domainMapppingsBean.getDomainMappings();
List<String> domainMappingList = new ArrayList<String>();
for (DomainMappingBean domainMappingBean : mappings) {
domainMappingList.add(domainMappingBean.getDomainName());
}
return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Domain mappings deleted successfully: [domain-mappings] %s", domainMappingList))).build();
}
/**
* Gets the domain mappings for an application.
*
* @param applicationId the application id
* @return 200
* @throws RestAPIException the rest api exception
*/
@GET
@Path("/applications/{applicationId}/domainMappings")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/getDomainMappings")
public Response getDomainMappings(
@PathParam("applicationId") String applicationId) throws RestAPIException {
List<DomainMappingBean> domainMappingsBeanList = null;
try {
domainMappingsBeanList = StratosApiV41Utils.getApplicationDomainMappings(applicationId);
if (domainMappingsBeanList == null || domainMappingsBeanList.isEmpty()) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "No domain mappings found for the application: [application-id] " +
applicationId)).build();
}
} catch (StratosManagerServiceDomainMappingExceptionException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Incorrect request to get domain mappings of application: " +
"[application-id] " + applicationId))
.build();
}
DomainMappingBean[] domainMappingsBeans = domainMappingsBeanList
.toArray(new DomainMappingBean[domainMappingsBeanList.size()]);
return Response.ok(domainMappingsBeans).build();
}
/**
* Undeploy an application.
*
* @param applicationId the application id
* @return 202 if undeployment process started, 404 if specified application is not found, 409 if application
* status is not in DEPLOYED state
* @throws RestAPIException the rest api exception
*/
@POST
@Path("/applications/{applicationId}/undeploy")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/undeployApplication")
public Response undeployApplication(
@PathParam("applicationId") String applicationId, @QueryParam("force") @DefaultValue("false") boolean force)
throws RestAPIException {
ApplicationBean applicationDefinition = StratosApiV41Utils.getApplication(applicationId);
if (applicationDefinition == null) {
String msg = String.format("Application does not exist [application-id] %s", applicationId);
log.info(msg);
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, msg)).build();
}
if (!applicationDefinition.getStatus().equalsIgnoreCase(StratosApiV41Utils.APPLICATION_STATUS_DEPLOYED)) {
String message = String.format("Could not undeploy since application is not in DEPLOYED status " +
"[application-id] %s [current status] %S", applicationId, applicationDefinition.getStatus());
log.info(message);
return Response.status(Response.Status.CONFLICT).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, message)).build();
}
StratosApiV41Utils.undeployApplication(applicationId, force);
return Response.accepted().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Application undeployed successfully: [application-id] %s", applicationId))).build();
}
/**
* This API resource provides information about the application denoted by the given appId. Details includes,
* Application details, top level cluster details, details of the group and sub groups.
*
* @param applicationId Id of the application.
* @return Json representing the application details with 200 as HTTP status. HTTP 404 is returned when there is
* no application with given Id.
* @throws RestAPIException is thrown in case of failure occurs.
*/
@GET
@Path("/applications/{applicationId}/runtime")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/getApplicationRuntime")
public Response getApplicationRuntime(
@PathParam("applicationId") String applicationId) throws RestAPIException {
ApplicationInfoBean applicationRuntime = StratosApiV41Utils.getApplicationRuntime(applicationId);
if (applicationRuntime == null) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Application runtime not found")).build();
} else {
return Response.ok().entity(applicationRuntime).build();
}
}
/**
* Delete an application.
*
* @param applicationId the application id
* @return 200 if application is successfully removed, 404 if specified application is not found, 409 if
* application is not in CREATED state
* @throws RestAPIException the rest api exception
*/
@DELETE
@Path("/applications/{applicationId}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/removeApplication")
@SuperTenantService(true)
public Response removeApplication(
@PathParam("applicationId") String applicationId) throws RestAPIException {
ApplicationBean applicationDefinition = StratosApiV41Utils.getApplication(applicationId);
if (applicationDefinition == null) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Application not found")).build();
}
if (!applicationDefinition.getStatus().equalsIgnoreCase(StratosApiV41Utils.APPLICATION_STATUS_CREATED)) {
return Response.status(Response.Status.CONFLICT).entity(new ResponseMessageBean(ResponseMessageBean.ERROR,
String.format("Could not delete since application is not in CREATED state :" +
" [application] %s [current-status] %S", applicationId, applicationDefinition.getStatus()))).build();
}
StratosApiV41Utils.removeApplication(applicationId);
return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Application deleted successfully: [application] %s", applicationId))).build();
}
// API methods for autoscaling policies
/**
* Gets the autoscaling policies.
*
* @return 200
* @throws RestAPIException the rest api exception
*/
@GET
@Path("/autoscalingPolicies")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/getAutoscalingPolicies")
public Response getAutoscalingPolicies()
throws RestAPIException {
AutoscalePolicyBean[] autoScalePolicies = StratosApiV41Utils.getAutoScalePolicies();
if (autoScalePolicies == null || autoScalePolicies.length == 0) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "No autoscaling policies found")).build();
}
return Response.ok().entity(autoScalePolicies).build();
}
/**
* Gets the autoscaling policy.
*
* @param autoscalePolicyId the autoscale policy id
* @return 200 if specified autoscaling policy is found, 404 if not
* @throws RestAPIException the rest api exception
*/
@GET
@Path("/autoscalingPolicies/{autoscalePolicyId}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/getAutoscalingPolicies")
public Response getAutoscalingPolicy(
@PathParam("autoscalePolicyId") String autoscalePolicyId) throws RestAPIException {
AutoscalePolicyBean autoScalePolicy = StratosApiV41Utils.getAutoScalePolicy(autoscalePolicyId);
if (autoScalePolicy == null) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Autoscaling policy not found")).build();
}
return Response.ok().entity(autoScalePolicy).build();
}
/**
* Creates the autoscaling policy defintion.
*
* @param autoscalePolicy the autoscale policy
* @return 201 if autoscale policy is successfully added
* @throws RestAPIException the rest api exception
*/
@POST
@Path("/autoscalingPolicies")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/addAutoscalingPolicy")
public Response addAutoscalingPolicy(
AutoscalePolicyBean autoscalePolicy) throws RestAPIException {
try {
StratosApiV41Utils.addAutoscalingPolicy(autoscalePolicy);
URI url = uriInfo.getAbsolutePathBuilder().path(autoscalePolicy.getId()).build();
return Response.created(url).entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Autoscaling policy added successfully: [autoscale-policy] %s",
autoscalePolicy.getId()))).build();
} catch (AutoscalerServiceInvalidPolicyExceptionException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Provided Autoscaling policy is invalid")).build();
} catch (AutoscalerServiceAutoScalingPolicyAlreadyExistExceptionException e) {
return Response.status(Response.Status.CONFLICT).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Autoscaling policy already exists")).build();
} catch (RestAPIException e) {
throw e;
}
}
/**
* Update autoscaling policy.
*
* @param autoscalePolicy the autoscale policy
* @return 200 if autoscale policy is successfully updated
* @throws RestAPIException the rest api exception
*/
@PUT
@Path("/autoscalingPolicies")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/updateAutoscalingPolicy")
public Response updateAutoscalingPolicy(
AutoscalePolicyBean autoscalePolicy) throws RestAPIException {
try {
StratosApiV41Utils.updateAutoscalingPolicy(autoscalePolicy);
} catch (AutoscalerServiceInvalidPolicyExceptionException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Autoscaling policy is invalid")).build();
}
return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Autoscaling policy updated successfully: [autoscale-policy] %s",
autoscalePolicy.getId()))).build();
}
/**
* Updates a network partition
*
* @param networkPartition Network Partition
* @return 200 if network partition is successfully updated
* @throws RestAPIException
*/
@PUT
@Path("/networkPartitions")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/updateNetworkPartition")
public Response updateNetworkPartition(
NetworkPartitionBean networkPartition) throws RestAPIException {
try {
StratosApiV41Utils.updateNetworkPartition(networkPartition);
} catch (CloudControllerServiceNetworkPartitionNotExistsExceptionException e) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Network partition not found")).build();
}
return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Network Partition updated successfully: [network-partition] %s",
networkPartition.getId()))).build();
}
/**
* Remove autoscaling policy.
*
* @param autoscalingPolicyId the autoscale policy
* @return 200
* @throws RestAPIException the rest api exception
*/
@DELETE
@Path("/autoscalingPolicies/{autoscalingPolicyId}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/removeAutoscalingPolicy")
public Response removeAutoscalingPolicy(
@PathParam("autoscalingPolicyId") String autoscalingPolicyId) throws RestAPIException {
try {
StratosApiV41Utils.removeAutoscalingPolicy(autoscalingPolicyId);
} catch (AutoscalerServiceUnremovablePolicyExceptionException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Autoscaling policy is in use")).build();
} catch (AutoscalerServicePolicyDoesNotExistExceptionException e) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Autoscaling policy not found")).build();
}
return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Autoscaling policy deleted successfully: [autoscale-policy] %s",
autoscalingPolicyId))).build();
}
/**
* Get cluster for a given cluster id
*
* @param clusterId id of the cluster
* @return 200 if specified cluster is found, 404 if not
* @throws RestAPIException the rest api exception
*/
@GET
@Path("/cluster/{clusterId}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/cluster")
public Response getCluster(
@PathParam("clusterId") String clusterId) throws RestAPIException {
try {
ClusterBean clusterBean = StratosApiV41Utils.getClusterInfo(clusterId);
if (clusterBean == null) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Cluster not found")).build();
} else {
return Response.ok().entity(clusterBean).build();
}
} catch (ClusterIdIsEmptyException e) {
return Response.status(Response.Status.BAD_REQUEST).build();
}
}
// API methods for tenants
/**
* Adds the tenant.
*
* @param tenantInfoBean the tenant info bean
* @return 201 if the tenant is successfully added
* @throws RestAPIException the rest api exception
*/
@POST
@Path("/tenants")
@Consumes("application/json")
@Produces("application/json")
@AuthorizationAction("/permission/protected/manage/addTenant")
@SuperTenantService(true)
public Response addTenant(
org.apache.stratos.common.beans.TenantInfoBean tenantInfoBean) throws RestAPIException {
try {
StratosApiV41Utils.addTenant(tenantInfoBean);
} catch (InvalidEmailException e) {
Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Invalid email")).build();
} catch (InvalidDomainException e) {
Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Invalid domain")).build();
}
URI url = uriInfo.getAbsolutePathBuilder().path(tenantInfoBean.getTenantDomain()).build();
return Response.created(url).entity(
new ResponseMessageBean(ResponseMessageBean.SUCCESS, String.format(
"Tenant added successfully: [tenant] %s", tenantInfoBean.getTenantDomain()))).build();
}
/**
* Update tenant.
*
* @param tenantInfoBean the tenant info bean
* @return 200 if tenant is successfully updated, 404 if specified tenant not found
* @throws RestAPIException the rest api exception
*/
@PUT
@Path("/tenants")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/updateTenant")
@SuperTenantService(true)
public Response updateTenant(
org.apache.stratos.common.beans.TenantInfoBean tenantInfoBean) throws RestAPIException {
try {
StratosApiV41Utils.updateExistingTenant(tenantInfoBean);
} catch (TenantNotFoundException ex) {
Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Tenant not found")).build();
} catch (InvalidEmailException e) {
Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Invalid email")).build();
} catch (Exception e) {
String msg = "Error in updating tenant " + tenantInfoBean.getTenantDomain();
log.error(msg, e);
throw new RestAPIException(msg);
}
return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Tenant updated successfully: [tenant] %s", tenantInfoBean.getTenantDomain()))).build();
}
/**
* Gets the tenant by domain.
*
* @param tenantDomain the tenant domain
* @return 200 if tenant for specified tenant domain found
* @throws RestAPIException the rest api exception
*/
@GET
@Path("/tenants/{tenantDomain}")
@Consumes("application/json")
@Produces("application/json")
@AuthorizationAction("/permission/protected/manage/getTenantForDomain")
@SuperTenantService(true)
public Response getTenantForDomain(
@PathParam("tenantDomain") String tenantDomain) throws RestAPIException {
try {
TenantInfoBean tenantInfo = StratosApiV41Utils.getTenantByDomain(tenantDomain);
if (tenantInfo == null) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Tenant information not found")).build();
}
return Response.ok().entity(tenantInfo).build();
} catch (Exception e) {
String message = "Error in retreiving tenant";
log.error(message, e);
throw new RestAPIException(e);
}
}
/**
* Delete tenant.
*
* @param tenantDomain the tenant domain
* @return 406 - Use tenantDeactivate method
* @throws RestAPIException the rest api exception
*/
@DELETE
@Path("/tenants/{tenantDomain}")
@Consumes("application/json")
@Produces("application/json")
@AuthorizationAction("/permission/protected/manage/removeTenant")
@SuperTenantService(true)
public Response removeTenant(
@PathParam("tenantDomain") String tenantDomain) throws RestAPIException {
return Response.status(Response.Status.NOT_ACCEPTABLE)
.entity(new ResponseMessageBean(ResponseMessageBean.ERROR,
"Please use the tenant deactivate method")).build();
}
/**
* Gets the tenants.
*
* @return 200
* @throws RestAPIException the rest api exception
*/
@GET
@Path("/tenants")
@Produces("application/json")
@AuthorizationAction("/permission/protected/manage/getTenants")
@SuperTenantService(true)
public Response getTenants()
throws RestAPIException {
try {
List<org.apache.stratos.common.beans.TenantInfoBean> tenantList = StratosApiV41Utils.getAllTenants();
if (tenantList == null || tenantList.isEmpty()) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "No tenants found")).build();
}
return Response.ok().entity(tenantList.toArray(
new org.apache.stratos.common.beans.TenantInfoBean[tenantList.size()])).build();
} catch (Exception e) {
String msg = "Error in retrieving tenants";
log.error(msg, e);
throw new RestAPIException(msg);
}
}
/**
* Gets the partial search tenants.
*
* @param tenantDomain the tenant domain
* @return 200
* @throws RestAPIException the rest api exception
*/
@GET
@Path("/tenants/search/{tenantDomain}")
@Consumes("application/json")
@Produces("application/json")
@AuthorizationAction("/permission/protected/manage/getTenants")
@SuperTenantService(true)
public Response getPartialSearchTenants(
@PathParam("tenantDomain") String tenantDomain) throws RestAPIException {
try {
List<org.apache.stratos.common.beans.TenantInfoBean> tenantList = StratosApiV41Utils.searchPartialTenantsDomains(tenantDomain);
if (tenantList == null || tenantList.isEmpty()) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "No tenants found")).build();
}
return Response.ok().entity(tenantList.toArray(new org.apache.stratos.common.beans.TenantInfoBean[tenantList.size()])).build();
} catch (Exception e) {
String msg = "Error in getting information for tenant " + tenantDomain;
log.error(msg, e);
throw new RestAPIException(msg);
}
}
/**
* Activate tenant.
*
* @param tenantDomain the tenant domain
* @return 200 if tenant activated successfully
* @throws RestAPIException the rest api exception
*/
@PUT
@Path("/tenants/activate/{tenantDomain}")
@Consumes("application/json")
@Produces("application/json")
@AuthorizationAction("/permission/protected/manage/activateTenant")
@SuperTenantService(true)
public Response activateTenant(
@PathParam("tenantDomain") String tenantDomain) throws RestAPIException {
StratosApiV41Utils.activateTenant(tenantDomain);
return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Tenant activated successfully: [tenant] %s", tenantDomain))).build();
}
/**
* Deactivate tenant.
*
* @param tenantDomain the tenant domain
* @return 200 if tenant deactivated successfully
* @throws RestAPIException the rest api exception
*/
@PUT
@Path("/tenants/deactivate/{tenantDomain}")
@Consumes("application/json")
@Produces("application/json")
@AuthorizationAction("/permission/protected/manage/deactivateTenant")
@SuperTenantService(true)
public Response deactivateTenant(
@PathParam("tenantDomain") String tenantDomain) throws RestAPIException {
StratosApiV41Utils.deactivateTenant(tenantDomain);
return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Tenant deactivated successfully: [tenant] %s", tenantDomain))).build();
}
// API methods for repositories
/**
* Notify artifact update event for specified repository
*
* @param payload Git notification Payload
* @return 204
* @throws RestAPIException
*/
@POST
@Path("/repo/notify")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/notifyRepository")
public Response notifyRepository(
GitNotificationPayloadBean payload) throws RestAPIException {
if (log.isInfoEnabled()) {
log.info(String.format("Git update notification received."));
}
StratosApiV41Utils.notifyArtifactUpdatedEvent(payload);
return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Repository notification sent successfully"))).build();
}
// API methods for users
/**
* Adds the user.
*
* @param userInfoBean the user info bean
* @return 201 if the user is successfully created
* @throws RestAPIException the rest api exception
*/
@POST
@Path("/users")
@Consumes("application/json")
@Produces("application/json")
@AuthorizationAction("/permission/admin/manage/addUser")
public Response addUser(
UserInfoBean userInfoBean) throws RestAPIException {
StratosApiV41Utils.addUser(userInfoBean);
log.info("Successfully added an user with Username " + userInfoBean.getUserName());
URI url = uriInfo.getAbsolutePathBuilder().path(userInfoBean.getUserName()).build();
return Response.created(url).entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("User added successfully: [user] %s", userInfoBean.getUserName()))).build();
}
/**
* Delete user.
*
* @param userName the user name
* @return 200 if the user is successfully deleted
* @throws RestAPIException the rest api exception
*/
@DELETE
@Path("/users/{userName}")
@Consumes("application/json")
@Produces("application/json")
@AuthorizationAction("/permission/admin/manage/removeUser")
public Response removeUser(
@PathParam("userName") String userName) throws RestAPIException {
StratosApiV41Utils.removeUser(userName);
log.info("Successfully removed user: [username] " + userName);
return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("User deleted successfully: [user] %s", userName))).build();
}
/**
* Update user.
*
* @param userInfoBean the user info bean
* @return 200 if the user is successfully updated
* @throws RestAPIException the rest api exception
*/
@PUT
@Path("/users")
@Consumes("application/json")
@Produces("application/json")
@AuthorizationAction("/permission/admin/manage/updateUser")
public Response updateUser(
UserInfoBean userInfoBean) throws RestAPIException {
StratosApiV41Utils.updateUser(userInfoBean);
log.info("Successfully updated an user with Username " + userInfoBean.getUserName());
return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("User updated successfully: [user] %s", userInfoBean.getUserName()))).build();
}
/**
* Gets the users.
*
* @return 200
* @throws RestAPIException the rest api exception
*/
@GET
@Path("/users")
@Produces("application/json")
@AuthorizationAction("/permission/admin/manage/getUsers")
public Response getUsers()
throws RestAPIException {
List<UserInfoBean> userList = StratosApiV41Utils.getUsers();
return Response.ok().entity(userList.toArray(new UserInfoBean[userList.size()])).build();
}
// API methods for Kubernetes clusters
/**
* Deploy kubernetes host cluster.
*
* @param kubernetesCluster the kubernetes cluster
* @return 201 if the kubernetes cluster is successfully created
* @throws RestAPIException the rest api exception
*/
@POST
@Path("/kubernetesClusters")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/addKubernetesCluster")
public Response addKubernetesHostCluster(
KubernetesClusterBean kubernetesCluster) throws RestAPIException {
try {
StratosApiV41Utils.addKubernetesCluster(kubernetesCluster);
URI url = uriInfo.getAbsolutePathBuilder().path(kubernetesCluster.getClusterId()).build();
return Response.created(url).entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Kubernetes cluster added successfully: [kub-host-cluster] %s",
kubernetesCluster.getClusterId()))).build();
} catch (RestAPIException e) {
throw e;
} catch (CloudControllerServiceKubernetesClusterAlreadyExistsExceptionException e) {
return Response.status(Response.Status.CONFLICT).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Kubernetes cluster already exists")).build();
} catch (CloudControllerServiceInvalidKubernetesClusterExceptionException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Kubernetes cluster is invalid")).build();
}
}
/**
* Deploy kubernetes host.
*
* @param kubernetesClusterId the kubernetes cluster id
* @param kubernetesHost the kubernetes host
* @return 201 if the kubernetes host is successfully added
* @throws RestAPIException the rest api exception
*/
@POST
@Path("/kubernetesClusters/{kubernetesClusterId}/minion")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/addKubernetesHost")
public Response addKubernetesHost(
@PathParam("kubernetesClusterId") String kubernetesClusterId, KubernetesHostBean kubernetesHost)
throws RestAPIException {
StratosApiV41Utils.addKubernetesHost(kubernetesClusterId, kubernetesHost);
URI url = uriInfo.getAbsolutePathBuilder().path(kubernetesHost.getHostId()).build();
return Response.created(url).entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Kubernetes host added successfully: [kub-host] %s", kubernetesHost.getHostId()))).build();
}
/**
* Update kubernetes master.
*
* @param kubernetesMaster the kubernetes master
* @return 200 if the kubernetes master is updated successfully, 404 if the kubernetes master is not found
* @throws RestAPIException the rest api exception
*/
@PUT
@Path("/kubernetesClusters/{kubernetesClusterId}/master")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/updateKubernetesMaster")
public Response updateKubernetesMaster(
KubernetesMasterBean kubernetesMaster) throws RestAPIException {
try {
StratosApiV41Utils.updateKubernetesMaster(kubernetesMaster);
URI url = uriInfo.getAbsolutePathBuilder().path(kubernetesMaster.getHostId()).build();
return Response.ok(url).entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Kubernetes master updated successfully: [kub-master] %s",
kubernetesMaster.getHostId()))).build();
} catch (RestAPIException e) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Kubernetes cluster not found")).build();
}
}
@PUT
@Path("/kubernetes/update/host")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/updateKubernetesHost")
public Response updateKubernetesHost(
KubernetesHostBean kubernetesHost) throws RestAPIException {
try {
StratosApiV41Utils.updateKubernetesHost(kubernetesHost);
URI url = uriInfo.getAbsolutePathBuilder().path(kubernetesHost.getHostId()).build();
return Response.ok(url).entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Kubernetes Host updated successfully: [kub-host] %s",
kubernetesHost.getHostId()))).build();
} catch (RestAPIException e) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Kubernetes host not found")).build();
}
}
/**
* Gets the kubernetes host clusters.
*
* @return 200
* @throws RestAPIException the rest api exception
*/
@GET
@Path("/kubernetesClusters")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/getKubernetesHostClusters")
public Response getKubernetesHostClusters() throws RestAPIException {
KubernetesClusterBean[] availableKubernetesClusters = StratosApiV41Utils.getAvailableKubernetesClusters();
if (availableKubernetesClusters == null || availableKubernetesClusters.length == 0) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "No kubernetes clusters found")).build();
}
return Response.ok().entity(availableKubernetesClusters).build();
}
/**
* Gets the kubernetes host cluster.
*
* @param kubernetesClusterId the kubernetes cluster id
* @return 200 if specified kubernetes host cluster is found, 404 if not
* @throws RestAPIException the rest api exception
*/
@GET
@Path("/kubernetesClusters/{kubernetesClusterId}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/getKubernetesHostClusters")
public Response getKubernetesHostCluster(
@PathParam("kubernetesClusterId") String kubernetesClusterId) throws RestAPIException {
try {
return Response.ok().entity(StratosApiV41Utils.getKubernetesCluster(kubernetesClusterId)).build();
} catch (RestAPIException e) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Kubernetes cluster not found")).build();
}
}
/**
* Gets the kubernetes hosts of kubernetes cluster.
*
* @param kubernetesClusterId the kubernetes cluster id
* @return 200 if hosts are found in the specified kubernetes host cluster, 404 if not
* @throws RestAPIException the rest api exception
*/
@GET
@Path("/kubernetesClusters/{kubernetesClusterId}/hosts")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/getKubernetesHostClusters")
public Response getKubernetesHostsOfKubernetesCluster(
@PathParam("kubernetesClusterId") String kubernetesClusterId) throws RestAPIException {
try {
return Response.ok().entity(StratosApiV41Utils.getKubernetesHosts(kubernetesClusterId)).build();
} catch (RestAPIException e) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Kubernetes hosts not found")).build();
}
}
/**
* Gets the kubernetes master of kubernetes cluster.
*
* @param kubernetesClusterId the kubernetes cluster id
* @return 200 if master is found for specified kubernetes cluster, 404 if not
* @throws RestAPIException the rest api exception
*/
@GET
@Path("/kubernetesClusters/{kubernetesClusterId}/master")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/getKubernetesHostClusters")
public Response getKubernetesMasterOfKubernetesCluster(
@PathParam("kubernetesClusterId") String kubernetesClusterId) throws RestAPIException {
try {
return Response.ok().entity(StratosApiV41Utils.getKubernetesMaster(kubernetesClusterId)).build();
} catch (RestAPIException e) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Kubernetes cluster not found")).build();
}
}
/**
* Un deploy kubernetes host cluster.
*
* @param kubernetesClusterId the kubernetes cluster id
* @return 204 if Kubernetes cluster is successfully removed, 404 if the specified Kubernetes cluster is not found
* @throws RestAPIException the rest api exception
*/
@DELETE
@Path("/kubernetesClusters/{kubernetesClusterId}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/removeKubernetesHostCluster")
public Response removeKubernetesHostCluster(
@PathParam("kubernetesClusterId") String kubernetesClusterId) throws RestAPIException {
try {
StratosApiV41Utils.removeKubernetesCluster(kubernetesClusterId);
} catch (CloudControllerServiceNonExistingKubernetesClusterExceptionException e) {
return Response.status(Response.Status.NOT_FOUND)
.entity(new ResponseMessageBean(ResponseMessageBean.ERROR,
String.format("Kubernetes cluster not found: [kub-cluster] %s",
kubernetesClusterId))).build();
}
return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Kubernetes Cluster removed successfully: [kub-cluster] %s", kubernetesClusterId)))
.build();
}
/**
* Undeploy kubernetes host of kubernetes cluster.
*
* @param kubernetesHostId the kubernetes host id
* @return 200 if hosts are successfully removed from the specified Kubernetes cluster, 404 if specified Kubernetes
* cluster is not found.
* @throws RestAPIException the rest api exception
*/
@DELETE
@Path("/kubernetesClusters/{kubernetesClusterId}/hosts/{hostId}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/removeKubernetesHostCluster")
public Response removeKubernetesHostOfKubernetesCluster(
@PathParam("hostId") String kubernetesHostId) throws RestAPIException {
try {
StratosApiV41Utils.removeKubernetesHost(kubernetesHostId);
} catch (RestAPIException e) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Kubernetes cluster not found")).build();
}
return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Kubernetes Host removed successfully: [kub-host] %s", kubernetesHostId)))
.build();
}
}
| components/org.apache.stratos.rest.endpoint/src/main/java/org/apache/stratos/rest/endpoint/api/StratosApiV41.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.stratos.rest.endpoint.api;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.stratos.autoscaler.stub.*;
import org.apache.stratos.cloud.controller.stub.*;
import org.apache.stratos.common.beans.*;
import org.apache.stratos.common.beans.application.ApplicationBean;
import org.apache.stratos.common.beans.application.ApplicationNetworkPartitionIdListBean;
import org.apache.stratos.common.beans.application.GroupBean;
import org.apache.stratos.common.beans.application.domain.mapping.ApplicationDomainMappingsBean;
import org.apache.stratos.common.beans.application.domain.mapping.DomainMappingBean;
import org.apache.stratos.common.beans.application.signup.ApplicationSignUpBean;
import org.apache.stratos.common.beans.artifact.repository.GitNotificationPayloadBean;
import org.apache.stratos.common.beans.cartridge.CartridgeBean;
import org.apache.stratos.common.beans.kubernetes.KubernetesClusterBean;
import org.apache.stratos.common.beans.kubernetes.KubernetesHostBean;
import org.apache.stratos.common.beans.kubernetes.KubernetesMasterBean;
import org.apache.stratos.common.beans.partition.NetworkPartitionBean;
import org.apache.stratos.common.beans.policy.autoscale.AutoscalePolicyBean;
import org.apache.stratos.common.beans.policy.deployment.ApplicationPolicyBean;
import org.apache.stratos.common.beans.policy.deployment.DeploymentPolicyBean;
import org.apache.stratos.common.beans.topology.ApplicationInfoBean;
import org.apache.stratos.common.beans.topology.ClusterBean;
import org.apache.stratos.common.exception.InvalidEmailException;
import org.apache.stratos.manager.service.stub.StratosManagerServiceApplicationSignUpExceptionException;
import org.apache.stratos.manager.service.stub.StratosManagerServiceDomainMappingExceptionException;
import org.apache.stratos.rest.endpoint.Utils;
import org.apache.stratos.rest.endpoint.annotation.AuthorizationAction;
import org.apache.stratos.rest.endpoint.annotation.SuperTenantService;
import org.apache.stratos.rest.endpoint.exception.*;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
/**
* Stratos API v4.1 for Stratos 4.1.0 release.
*/
@Path("/")
public class StratosApiV41 extends AbstractApi {
private static final Log log = LogFactory.getLog(StratosApiV41.class);
@Context
HttpServletRequest httpServletRequest;
@Context
UriInfo uriInfo;
/**
* This method is used by clients such as the CLI to verify the Stratos manager URL.
*
* @return the response
* @throws RestAPIException the rest api exception
*/
@GET
@Path("/init")
@AuthorizationAction("/permission/admin/restlogin")
public Response initialize()
throws RestAPIException {
ResponseMessageBean response = new ResponseMessageBean(ResponseMessageBean.SUCCESS,
"Successfully authenticated");
return Response.ok(response).build();
}
/**
* This method gets called by the client who are interested in using session mechanism to authenticate
* themselves in subsequent calls. This method call get authenticated by the basic authenticator.
* Once the authenticated call received, the method creates a session and returns the session id.
*
* @return The session id related with the session
*/
@GET
@Path("/session")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/restlogin")
public Response getSession() {
HttpSession httpSession = httpServletRequest.getSession(true);//create session if not found
PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
httpSession.setAttribute("userName", carbonContext.getUsername());
httpSession.setAttribute("tenantDomain", carbonContext.getTenantDomain());
httpSession.setAttribute("tenantId", carbonContext.getTenantId());
String sessionId = httpSession.getId();
return Response.ok().header("WWW-Authenticate", "Basic").type(MediaType.APPLICATION_JSON).
entity(Utils.buildAuthenticationSuccessMessage(sessionId)).build();
}
/**
* Creates the cartridge definition.
*
* @param cartridgeDefinitionBean the cartridge definition bean
* @return 201 if cartridge is successfully created, 409 if cartridge already exists.
* @throws RestAPIException the rest api exception
*/
@POST
@Path("/cartridges")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/addCartridge")
public Response addCartridge(
CartridgeBean cartridgeDefinitionBean) throws RestAPIException {
String cartridgeType = cartridgeDefinitionBean.getType();
CartridgeBean cartridgeBean = StratosApiV41Utils.getCartridgeForValidate(cartridgeType);
if (cartridgeBean != null) {
String msg = String.format("Cartridge already exists: [cartridge-type] %s", cartridgeType);
log.warn(msg);
return Response.status(Response.Status.CONFLICT)
.entity(new ResponseMessageBean(ResponseMessageBean.ERROR, msg)).build();
}
StratosApiV41Utils.addCartridge(cartridgeDefinitionBean);
URI url = uriInfo.getAbsolutePathBuilder().path(cartridgeType).build();
return Response.created(url).entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Cartridge added successfully: [cartridge-type] %s", cartridgeType))).build();
}
/**
* Creates the Deployment Policy Definition.
*
* @param deploymentPolicyDefinitionBean the deployment policy bean
* @return 201 if deployment policy is successfully added
* @throws RestAPIException the rest api exception
*/
@POST
@Path("/deploymentPolicies")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/addDeploymentPolicy")
public Response addDeploymentPolicy(
DeploymentPolicyBean deploymentPolicyDefinitionBean) throws RestAPIException {
String deploymentPolicyID = deploymentPolicyDefinitionBean.getId();
try {
// TODO :: Deployment policy validation
StratosApiV41Utils.addDeploymentPolicy(deploymentPolicyDefinitionBean);
} catch (AutoscalerServiceInvalidDeploymentPolicyExceptionException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Deployment policy is not valid")).build();
} catch (AutoscalerServiceDeploymentPolicyAlreadyExistsExceptionException e) {
return Response.status(Response.Status.CONFLICT).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Deployment policy already exists")).build();
}
URI url = uriInfo.getAbsolutePathBuilder().path(deploymentPolicyID).build();
return Response.created(url).entity(new ResponseMessageBean(ResponseMessageBean.ERROR,
String.format("Deployment policy added successfully: " + "[deployment-policy-id] %s",
deploymentPolicyID))).build();
}
/**
* Get deployment policy by deployment policy id
*
* @return 200 if deployment policy is found, 404 if not
* @throws RestAPIException
*/
@GET
@Path("/deploymentPolicies/{deploymentPolicyId}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/getDeploymentPolicy")
public Response getDeploymentPolicy(
@PathParam("deploymentPolicyId") String deploymentPolicyId) throws RestAPIException {
DeploymentPolicyBean deploymentPolicyBean = StratosApiV41Utils.getDeployementPolicy(deploymentPolicyId);
if (deploymentPolicyBean == null) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Deployment policy not found")).build();
}
return Response.ok(deploymentPolicyBean).build();
}
/**
* Get deployment policies
*
* @return 200 with the list of deployment policies
* @throws RestAPIException
*/
@GET
@Path("/deploymentPolicies")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/getDeploymentPolicy")
public Response getDeploymentPolicies()
throws RestAPIException {
DeploymentPolicyBean[] deploymentPolicies = StratosApiV41Utils.getDeployementPolicies();
if (deploymentPolicies == null || deploymentPolicies.length == 0) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "No deployment policies found")).build();
}
return Response.ok(deploymentPolicies).build();
}
/**
* Updates the Deployment Policy Definition.
*
* @param deploymentPolicyDefinitionBean the deployment policy bean
* @return 200 if deployment policy is successfully updated
* @throws RestAPIException the rest api exception
*/
@PUT
@Path("/deploymentPolicies")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/updateDeploymentPolicy")
public Response updateDeploymentPolicy(
DeploymentPolicyBean deploymentPolicyDefinitionBean) throws RestAPIException {
String deploymentPolicyID = deploymentPolicyDefinitionBean.getId();
// TODO :: Deployment policy validation
try {
StratosApiV41Utils.updateDeploymentPolicy(deploymentPolicyDefinitionBean);
} catch (AutoscalerServiceInvalidPolicyExceptionException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Deployment policy is invalid")).build();
} catch (AutoscalerServiceInvalidDeploymentPolicyExceptionException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Deployment policy is invalid")).build();
} catch (AutoscalerServiceDeploymentPolicyNotExistsExceptionException e) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Deployment policy not found")).build();
}
URI url = uriInfo.getAbsolutePathBuilder().path(deploymentPolicyID).build();
return Response.ok(url).entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Deployment policy updated successfully: " + "[deployment-policy-id] %s",
deploymentPolicyID))).build();
}
/**
* Updates the Deployment Policy Definition.
*
* @param deploymentPolicyID the deployment policy id
* @return 200 if deployment policy is successfully removed
* @throws RestAPIException the rest api exception
*/
@DELETE
@Path("/deploymentPolicies/{depolymentPolicyID}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/removeDeploymentPolicy")
public Response removeDeploymentPolicy(
@PathParam("depolymentPolicyID") String deploymentPolicyID) throws RestAPIException {
try {
StratosApiV41Utils.removeDeploymentPolicy(deploymentPolicyID);
} catch (AutoscalerServiceDeploymentPolicyNotExistsExceptionException e) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Autoscaling policy not found")).build();
}
URI url = uriInfo.getAbsolutePathBuilder().path(deploymentPolicyID).build();
return Response.ok(url).entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Deployment policy removed successfully: " + "[deployment-policy-id] %s",
deploymentPolicyID))).build();
}
/**
* Updates the cartridge definition.
*
* @param cartridgeDefinitionBean the cartridge definition bean
* @return 201 if cartridge successfully updated
* @throws RestAPIException the rest api exception
*/
@PUT
@Path("/cartridges")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/updateCartridge")
public Response updateCartridge(
CartridgeBean cartridgeDefinitionBean) throws RestAPIException {
StratosApiV41Utils.updateCartridge(cartridgeDefinitionBean);
URI url = uriInfo.getAbsolutePathBuilder().path(cartridgeDefinitionBean.getType()).build();
return Response.ok(url)
.entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS, "Cartridge updated successfully"))
.build();
}
/**
* Gets all available cartridges.
*
* @return 200 if cartridges exists, 404 if no cartridges found
* @throws RestAPIException the rest api exception
*/
@GET
@Path("/cartridges")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/getCartridge")
public Response getCartridges()
throws RestAPIException {
//We pass null to searching string and multi-tenant parameter since we do not need to do any filtering
List<CartridgeBean> cartridges = StratosApiV41Utils.getAvailableCartridges(null, null, getConfigContext());
if (cartridges == null || cartridges.isEmpty()) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "No cartridges found")).build();
}
CartridgeBean[] cartridgeArray = cartridges.toArray(new CartridgeBean[cartridges.size()]);
return Response.ok().entity(cartridgeArray).build();
}
/**
* Gets a single cartridge by type
*
* @param cartridgeType Cartridge type
* @return 200 if specified cartridge exists, 404 if not
* @throws RestAPIException
*/
@GET
@Path("/cartridges/{cartridgeType}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/getCartridge")
public Response getCartridge(
@PathParam("cartridgeType") String cartridgeType) throws RestAPIException {
CartridgeBean cartridge;
try {
cartridge = StratosApiV41Utils.getCartridge(cartridgeType);
return Response.ok().entity(cartridge).build();
} catch (RestAPIException e) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Cartridge not found")).build();
}
}
/**
* Returns cartridges by category.
*
* @param filter Filter
* @param criteria Criteria
* @return 200 if cartridges are found for specified filter, 404 if none found
* @throws RestAPIException
*/
@GET
@Path("/cartridges/filter/{filter}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/getCartridgesByFilter")
public Response getCartridgesByFilter(
@DefaultValue("") @PathParam("filter") String filter, @QueryParam("criteria") String criteria)
throws RestAPIException {
List<CartridgeBean> cartridges = StratosApiV41Utils.
getCartridgesByFilter(filter, criteria, getConfigContext());
if (cartridges == null || cartridges.isEmpty()) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "No cartridges found")).build();
}
CartridgeBean[] cartridgeArray = cartridges.toArray(new CartridgeBean[cartridges.size()]);
return Response.ok().entity(cartridgeArray).build();
}
/**
* Returns a specific cartridge by category.
*
* @param filter Filter
* @param cartridgeType Cartridge Type
* @return 200 if a cartridge is found for specified filter, 404 if none found
* @throws RestAPIException
*/
@GET
@Path("/cartridges/{cartridgeType}/filter/{filter}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/getCartridgesByFilter")
public Response getCartridgeByFilter(
@PathParam("cartridgeType") String cartridgeType, @DefaultValue("") @PathParam("filter") String filter)
throws RestAPIException {
CartridgeBean cartridge;
cartridge = StratosApiV41Utils.getCartridgeByFilter(filter, cartridgeType, getConfigContext());
if (cartridge == null) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "No cartridges found for this filter")).build();
}
return Response.ok().entity(cartridge).build();
}
/**
* Deletes a cartridge definition.
*
* @param cartridgeType the cartridge type
* @return 200 if cartridge is successfully removed
* @throws RestAPIException the rest api exception
*/
@DELETE
@Path("/cartridges/{cartridgeType}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/removeCartridge")
public Response removeCartridge(
@PathParam("cartridgeType") String cartridgeType) throws RestAPIException {
StratosApiV41Utils.removeCartridge(cartridgeType);
return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Cartridge deleted successfully: [cartridge-type] %s", cartridgeType))).build();
}
// API methods for cartridge groups
/**
* Creates the cartridge group definition.
*
* @param serviceGroupDefinition the cartridge group definition
* @return 201 if group added successfully
* @throws RestAPIException the rest api exception
*/
@POST
@Path("/cartridgeGroups")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/addServiceGroup")
@SuperTenantService(true)
public Response addServiceGroup(
GroupBean serviceGroupDefinition) throws RestAPIException {
try {
StratosApiV41Utils.addServiceGroup(serviceGroupDefinition);
URI url = uriInfo.getAbsolutePathBuilder().path(serviceGroupDefinition.getName()).build();
return Response.created(url).entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Cartridge Group added successfully: [cartridge-group] %s",
serviceGroupDefinition.getName()))).build();
} catch (InvalidCartridgeGroupDefinitionException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, e.getMessage())).build();
} catch (RestAPIException e) {
if (e.getCause().getMessage().contains("already exists")) {
return Response.status(Response.Status.CONFLICT).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Cartridge group not found")).build();
} else if (e.getCause().getMessage().contains("Invalid Service Group")) {
return Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, e.getCause().getMessage())).build();
} else {
throw e;
}
}
}
/**
* Gets the cartridge group definition.
*
* @param groupDefinitionName the group definition name
* @return 200 if cartridge group found for group definition, 404 if none is found
* @throws RestAPIException the rest api exception
*/
@GET
@Path("/cartridgeGroups/{groupDefinitionName}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/getServiceGroupDefinition")
public Response getServiceGroupDefinition(
@PathParam("groupDefinitionName") String groupDefinitionName) throws RestAPIException {
GroupBean serviceGroupDefinition = StratosApiV41Utils.getServiceGroupDefinition(groupDefinitionName);
if (serviceGroupDefinition != null) {
return Response.ok().entity(serviceGroupDefinition).build();
} else {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Cartridge group not found")).build();
}
}
/**
* Gets all cartridge groups created.
*
* @return 200 if cartridge groups are found, 404 if none found
* @throws RestAPIException the rest api exception
*/
@GET
@Path("/cartridgeGroups")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/getServiceGroupDefinition")
public Response getServiceGroups()
throws RestAPIException {
GroupBean[] serviceGroups = StratosApiV41Utils.getServiceGroupDefinitions();
if (serviceGroups != null) {
return Response.ok().entity(serviceGroups).build();
} else {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Cartridge group not found")).build();
}
}
/**
* Delete cartridge group definition.
*
* @param groupDefinitionName the group definition name
* @return 200 if cartridge group is successfully removed
* @throws RestAPIException the rest api exception
*/
@DELETE
@Path("/cartridgeGroups/{groupDefinitionName}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/removeServiceGroup")
@SuperTenantService(true)
public Response removeServiceGroup(
@PathParam("groupDefinitionName") String groupDefinitionName) throws RestAPIException {
try {
StratosApiV41Utils.removeServiceGroup(groupDefinitionName);
} catch (AutoscalerServiceCartridgeGroupNotFoundExceptionException e) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Cartridge group not found")).build();
}
return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Cartridge Group deleted successfully: [cartridge-group] %s", groupDefinitionName)))
.build();
}
// API methods for network partitions
/**
* Add network partition
*
* @param networkPartitionBean Network Partition
* @return 201 if network partition successfully added, 409 if network partition already exists
* @throws RestAPIException
*/
@POST
@Path("/networkPartitions")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/addNetworkPartition")
public Response addNetworkPartition(
NetworkPartitionBean networkPartitionBean) throws RestAPIException {
String networkPartitionId = networkPartitionBean.getId();
try {
StratosApiV41Utils.addNetworkPartition(networkPartitionBean);
} catch (CloudControllerServiceNetworkPartitionAlreadyExistsExceptionException e) {
return Response.status(Response.Status.CONFLICT)
.entity(new ResponseMessageBean(ResponseMessageBean.ERROR, e.getMessage()))
.build();
}
URI url = uriInfo.getAbsolutePathBuilder().path(networkPartitionId).build();
return Response.created(url).entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Network partition added successfully: [network-partition] %s", networkPartitionId)))
.build();
}
/**
* Get network partitions
*
* @return 200 if network partitions are found
* @throws RestAPIException
*/
@GET
@Path("/networkPartitions")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/getNetworkPartitions")
public Response getNetworkPartitions()
throws RestAPIException {
NetworkPartitionBean[] networkPartitions = StratosApiV41Utils.getNetworkPartitions();
if (networkPartitions == null || networkPartitions.length == 0) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "No network partitions found")).build();
}
return Response.ok(networkPartitions).build();
}
/**
* Get network partition by network partition id
*
* @return 200 if specified network partition is found
* @throws RestAPIException
*/
@GET
@Path("/networkPartitions/{networkPartitionId}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/getNetworkPartitions")
public Response getNetworkPartition(
@PathParam("networkPartitionId") String networkPartitionId) throws RestAPIException {
NetworkPartitionBean networkPartition = StratosApiV41Utils.getNetworkPartition(networkPartitionId);
if (networkPartition == null) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Network partition is not found")).build();
}
return Response.ok(networkPartition).build();
}
/**
* Remove network partition by network partition id
*
* @return 200 if specified network partition is successfully deleted, 404 if specified network partition is not
* found
* @throws RestAPIException
*/
@DELETE
@Path("/networkPartitions/{networkPartitionId}")
@AuthorizationAction("/permission/protected/manage/removeNetworkPartition")
public Response removeNetworkPartition(
@PathParam("networkPartitionId") String networkPartitionId) throws RestAPIException {
try {
StratosApiV41Utils.removeNetworkPartition(networkPartitionId);
} catch (CloudControllerServiceNetworkPartitionNotExistsExceptionException e) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Network partition is not found")).build();
}
return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Network partition deleted successfully: [network-partition] %s",
networkPartitionId))).build();
}
// API methods for applications
/**
* Add application
*
* @param applicationDefinition Application Definition
* @return 201 if application is successfully added
* @throws RestAPIException
*/
@POST
@Path("/applications")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/addApplication")
public Response addApplication(ApplicationBean applicationDefinition) throws RestAPIException {
try {
StratosApiV41Utils.addApplication(applicationDefinition, getConfigContext(), getUsername(), getTenantDomain());
URI url = uriInfo.getAbsolutePathBuilder().path(applicationDefinition.getApplicationId()).build();
return Response.created(url).entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Application added successfully: [application] %s",
applicationDefinition.getApplicationId()))).build();
} catch (ApplicationAlreadyExistException e) {
return Response.status(Response.Status.CONFLICT).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Application already exists")).build();
} catch (RestAPIException e) {
throw e;
}
}
/**
* Add application
*
* @param applicationDefinition Application Definition
* @return 201 if application is successfully added
* @throws RestAPIException
*/
@PUT
@Path("/applications")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/addApplication")
public Response updateApplication(ApplicationBean applicationDefinition) throws RestAPIException {
StratosApiV41Utils.updateApplication(applicationDefinition, getConfigContext(), getUsername(), getTenantDomain());
URI url = uriInfo.getAbsolutePathBuilder().path(applicationDefinition.getApplicationId()).build();
return Response.created(url).entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Application updated successfully: [application] %s",
applicationDefinition.getApplicationId()))).build();
}
/**
* Return applications
*
* @return 200 if applications are found
* @throws RestAPIException
*/
@GET
@Path("/applications")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/getApplications")
public Response getApplications() throws RestAPIException {
List<ApplicationBean> applicationDefinitions = StratosApiV41Utils.getApplications();
if (applicationDefinitions == null || applicationDefinitions.isEmpty()) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "No applications found")).build();
}
ApplicationBean[] applicationDefinitionsArray = applicationDefinitions
.toArray(new ApplicationBean[applicationDefinitions.size()]);
return Response.ok(applicationDefinitionsArray).build();
}
/**
* Gets the application.
*
* @param applicationId the application id
* @return 200 if specified application is found, 404 if not
* @throws RestAPIException the rest api exception
*/
@GET
@Path("/applications/{applicationId}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/getApplications")
public Response getApplication(
@PathParam("applicationId") String applicationId) throws RestAPIException {
ApplicationBean applicationDefinition = StratosApiV41Utils.getApplication(applicationId);
if (applicationDefinition == null) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Application not found")).build();
}
return Response.ok(applicationDefinition).build();
}
/**
* Deploy application.
*
* @param applicationId Application Id
* @param applicationPolicyId the application policy id
* @return 202 after deployment process is started. Deployment is asynchronous
* @throws RestAPIException the rest api exception
*/
@POST
@Path("/applications/{applicationId}/deploy/{applicationPolicyId}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/deployApplication")
public Response deployApplication(
@PathParam("applicationId") String applicationId,
@PathParam("applicationPolicyId") String applicationPolicyId) throws RestAPIException {
try {
StratosApiV41Utils.deployApplication(applicationId, applicationPolicyId);
return Response.accepted().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Application deployed successfully: [application] %s", applicationId))).build();
} catch (ApplicationAlreadyDeployedException e) {
return Response.status(Response.Status.CONFLICT).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Application policy already deployed")).build();
} catch (RestAPIException e) {
throw e;
}
}
/**
* Adds an application policy
*
* @param applicationPolicy Application Policy
* @return 201 if the application policy is successfully added
* @throws RestAPIException
*/
@POST
@Path("/applicationPolicies")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/addApplicationPolicy")
public Response addApplicationPolicy(
ApplicationPolicyBean applicationPolicy) throws RestAPIException {
try {
StratosApiV41Utils.addApplicationPolicy(applicationPolicy);
URI url = uriInfo.getAbsolutePathBuilder().path(applicationPolicy.getId()).build();
return Response.created(url).entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Application policy added successfully: [application-policy] %s",
applicationPolicy.getId()))).build();
} catch (RestAPIException e) {
throw e;
} catch (AutoscalerServiceInvalidApplicationPolicyExceptionException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Invalid application policy")).build();
}
}
/**
* Retrieve specified application policy
*
* @param applicationPolicyId Application Policy Id
* @return 200 if application policy is found
* @throws RestAPIException
*/
@GET
@Path("/applicationPolicies/{applicationPolicyId}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/getApplicationPolicy")
public Response getApplicationPolicy(
@PathParam("applicationPolicyId") String applicationPolicyId) throws RestAPIException {
try {
ApplicationPolicyBean applicationPolicyBean = StratosApiV41Utils.getApplicationPolicy(applicationPolicyId);
if (applicationPolicyBean == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
return Response.ok(applicationPolicyBean).build();
} catch (ApplicationPolicyIdIsEmptyException e) {
return Response.status(Response.Status.BAD_REQUEST).build();
}
}
/**
* Retrieve all application policies
*
* @return 200
* @throws RestAPIException
*/
@GET
@Path("/applicationPolicies")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/getApplicationPolicies")
public Response getApplicationPolicies()
throws RestAPIException {
ApplicationPolicyBean[] applicationPolicies = StratosApiV41Utils.getApplicationPolicies();
if (applicationPolicies == null || applicationPolicies.length == 0) {
return Response.status(Response.Status.NOT_FOUND).build();
}
return Response.ok().entity(applicationPolicies).build();
}
/**
* Remove specified application policy
*
* @param applicationPolicyId Application Policy Id
* @return 200 if application policy is successfully removed
* @throws RestAPIException
*/
@DELETE
@Path("/applicationPolicies/{applicationPolicyId}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/removeApplicationPolicy")
public Response removeApplicationPolicy(
@PathParam("applicationPolicyId") String applicationPolicyId) throws RestAPIException {
try {
StratosApiV41Utils.removeApplicationPolicy(applicationPolicyId);
return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Application policy deleted successfully: [application-policy] %s",
applicationPolicyId))).build();
} catch (ApplicationPolicyIdIsEmptyException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Autoscaling policy id is empty"))
.build();
} catch (AutoscalerServiceInvalidPolicyExceptionException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Autoscaling policy is invalid"))
.build();
}
}
/**
* Update application policy
*
* @param applicationPolicy Application Policy
* @return 200 if application policies successfully updated
* @throws RestAPIException
*/
@PUT
@Path("/applicationPolicies")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/updateApplicationPolicy")
public Response updateApplicationPolicy(
ApplicationPolicyBean applicationPolicy) throws RestAPIException {
try {
StratosApiV41Utils.updateApplicationPolicy(applicationPolicy);
} catch (AutoscalerServiceInvalidApplicationPolicyExceptionException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Invalid application policy"))
.build();
} catch (AutoscalerServiceApplicatioinPolicyNotExistsExceptionException e) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Application policy does not exist"))
.build();
}
return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Application policy updated successfully: [application-policy] %s",
applicationPolicy.getId()))).build();
}
/**
* Get network partition ids used in an application
*
* @return 200
* @throws RestAPIException
*/
@GET
@Path("/applications/{applicationId}/networkPartitions")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/getApplicationNetworkPartitions")
public Response getApplicationNetworkPartitions(
@PathParam("applicationId") String applicationId) throws RestAPIException {
ApplicationNetworkPartitionIdListBean appNetworkPartitionsBean = StratosApiV41Utils
.getApplicationNetworkPartitions(applicationId);
if (appNetworkPartitionsBean == null ||
(appNetworkPartitionsBean.getNetworkPartitionIds().size() == 1 &&
appNetworkPartitionsBean.getNetworkPartitionIds().get(0) == null)) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "No network partitions used in the application"))
.build();
}
return Response.ok(appNetworkPartitionsBean).build();
}
/**
* Signs up for an application.
*
* @param applicationId the application id
* @param applicationSignUpBean the application sign up bean
* @return 200 if application sign up was successfull
* @throws RestAPIException the rest api exception
*/
@POST
@Path("/applications/{applicationId}/signup")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/addApplicationSignUp")
public Response addApplicationSignUp(
@PathParam("applicationId") String applicationId, ApplicationSignUpBean applicationSignUpBean)
throws RestAPIException {
StratosApiV41Utils.addApplicationSignUp(applicationId, applicationSignUpBean);
URI url = uriInfo.getAbsolutePathBuilder().path(applicationId).build();
return Response.created(url).entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Successfully signed up for: [application] %s", applicationId))).build();
}
/**
* Gets the application sign up.
*
* @param applicationId the application id
* @return 200 if specified application signup is found, 404 if not
* @throws RestAPIException the rest api exception
*/
@GET
@Path("/applications/{applicationId}/signup")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/getApplicationSignUp")
public Response getApplicationSignUp(
@PathParam("applicationId") String applicationId) throws RestAPIException,
StratosManagerServiceApplicationSignUpExceptionException {
ApplicationSignUpBean applicationSignUpBean;
try {
applicationSignUpBean = StratosApiV41Utils.getApplicationSignUp(applicationId);
if (applicationSignUpBean == null) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "No Application signups found for application"))
.build();
}
return Response.ok(applicationSignUpBean).build();
} catch (ApplicationSignUpRestAPIException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Incorrect request to get application sign ups"))
.build();
}
}
/**
* Removes the application sign up.
*
* @param applicationId the application id
* @return 200 if specified application sign up is removed
* @throws RestAPIException the rest api exception
*/
@DELETE
@Path("/applications/{applicationId}/signup")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/removeApplicationSignUp")
public Response removeApplicationSignUp(
@PathParam("applicationId") String applicationId) throws RestAPIException {
StratosApiV41Utils.removeApplicationSignUp(applicationId);
return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Application sign up removed successfully: [application] %s", applicationId))).build();
}
/**
* Adds the domain mappings for an application.
*
* @param applicationId the application id
* @param domainMappingsBean the domain mappings bean
* @return 200
* @throws RestAPIException the rest api exception
*/
@POST
@Path("/applications/{applicationId}/domainMappings")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/addDomainMappings")
public Response addDomainMappings(
@PathParam("applicationId") String applicationId, ApplicationDomainMappingsBean domainMappingsBean)
throws RestAPIException {
try {
StratosApiV41Utils.addApplicationDomainMappings(applicationId, domainMappingsBean);
} catch (StratosManagerServiceDomainMappingExceptionException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Incorrect request to add domain mapping for " +
"application")).build();
}
List<DomainMappingBean> mappings = domainMappingsBean.getDomainMappings();
List<String> domainMappingList = new ArrayList<String>();
for (DomainMappingBean domainMappingBean : mappings) {
domainMappingList.add(domainMappingBean.getDomainName());
}
URI url = uriInfo.getAbsolutePathBuilder().path(applicationId).build();
return Response.created(url).entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Domain mappings added successfully: [domain-mappings] %s", domainMappingList)))
.build();
}
/**
* Removes the domain mappings for an application.
*
* @param applicationId the application id
* @param domainMapppingsBean the domain mapppings bean
* @return 200
* @throws RestAPIException the rest api exception
*/
@DELETE
@Path("/applications/{applicationId}/domainMappings")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/removeDomainMappings")
public Response removeDomainMappings(
@PathParam("applicationId") String applicationId, ApplicationDomainMappingsBean domainMapppingsBean)
throws RestAPIException {
try {
StratosApiV41Utils.removeApplicationDomainMappings(applicationId, domainMapppingsBean);
} catch (StratosManagerServiceDomainMappingExceptionException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Incorrect request to delete domain mapping of " +
"application")).build();
}
List<DomainMappingBean> mappings = domainMapppingsBean.getDomainMappings();
List<String> domainMappingList = new ArrayList<String>();
for (DomainMappingBean domainMappingBean : mappings) {
domainMappingList.add(domainMappingBean.getDomainName());
}
return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Domain mappings deleted successfully: [domain-mappings] %s", domainMappingList)))
.build();
}
/**
* Gets the domain mappings for an application.
*
* @param applicationId the application id
* @return 200
* @throws RestAPIException the rest api exception
*/
@GET
@Path("/applications/{applicationId}/domainMappings")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/getDomainMappings")
public Response getDomainMappings(
@PathParam("applicationId") String applicationId) throws RestAPIException {
List<DomainMappingBean> domainMappingsBeanList = null;
try {
domainMappingsBeanList = StratosApiV41Utils.getApplicationDomainMappings(applicationId);
if (domainMappingsBeanList == null || domainMappingsBeanList.isEmpty()) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.SUCCESS, "No domain mappings found for the application: [application-id] " +
applicationId)).build();
}
} catch (StratosManagerServiceDomainMappingExceptionException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Incorrect request to get domain mappings of application: " +
"[application-id] " + applicationId))
.build();
}
DomainMappingBean[] domainMappingsBeans = domainMappingsBeanList
.toArray(new DomainMappingBean[domainMappingsBeanList.size()]);
return Response.ok(domainMappingsBeans).build();
}
/**
* Undeploy an application.
*
* @param applicationId the application id
* @return 202 if undeployment process started, 404 if specified application is not found, 409 if application
* status is not in DEPLOYED state
* @throws RestAPIException the rest api exception
*/
@POST
@Path("/applications/{applicationId}/undeploy")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/undeployApplication")
public Response undeployApplication(
@PathParam("applicationId") String applicationId, @QueryParam("force") @DefaultValue("false") boolean force)
throws RestAPIException {
ApplicationBean applicationDefinition = StratosApiV41Utils.getApplication(applicationId);
if (applicationDefinition == null) {
String msg = String.format("Application does not exist [application-id] %s", applicationId);
log.info(msg);
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, msg)).build();
}
if (!applicationDefinition.getStatus().equalsIgnoreCase(StratosApiV41Utils.APPLICATION_STATUS_DEPLOYED)) {
String message = String.format("Could not undeploy since application is not in DEPLOYED status " +
"[application-id] %s [current status] %S", applicationId, applicationDefinition.getStatus());
log.info(message);
return Response.status(Response.Status.CONFLICT).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, message)).build();
}
StratosApiV41Utils.undeployApplication(applicationId, force);
return Response.accepted().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Application undeployed successfully: [application-id] %s", applicationId))).build();
}
/**
* This API resource provides information about the application denoted by the given appId. Details includes,
* Application details, top level cluster details, details of the group and sub groups.
*
* @param applicationId Id of the application.
* @return Json representing the application details with 200 as HTTP status. HTTP 404 is returned when there is
* no application with given Id.
* @throws RestAPIException is thrown in case of failure occurs.
*/
@GET
@Path("/applications/{applicationId}/runtime")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/getApplicationRuntime")
public Response getApplicationRuntime(
@PathParam("applicationId") String applicationId) throws RestAPIException {
ApplicationInfoBean applicationRuntime = StratosApiV41Utils.getApplicationRuntime(applicationId);
if (applicationRuntime == null) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Application runtime not found")).build();
} else {
return Response.ok().entity(applicationRuntime).build();
}
}
/**
* Delete an application.
*
* @param applicationId the application id
* @return 200 if application is successfully removed, 404 if specified application is not found, 409 if
* application is not in CREATED state
* @throws RestAPIException the rest api exception
*/
@DELETE
@Path("/applications/{applicationId}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/removeApplication")
@SuperTenantService(true)
public Response removeApplication(
@PathParam("applicationId") String applicationId) throws RestAPIException {
ApplicationBean applicationDefinition = StratosApiV41Utils.getApplication(applicationId);
if (applicationDefinition == null) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Application not found")).build();
}
if (!applicationDefinition.getStatus().equalsIgnoreCase(StratosApiV41Utils.APPLICATION_STATUS_CREATED)) {
return Response.status(Response.Status.CONFLICT).entity(new ResponseMessageBean(ResponseMessageBean.ERROR,
String.format("Could not delete since application is not in CREATED state :" +
" [application] %s [current-status] %S", applicationId, applicationDefinition.getStatus()))).build();
}
StratosApiV41Utils.removeApplication(applicationId);
return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Application deleted successfully: [application] %s", applicationId))).build();
}
// API methods for autoscaling policies
/**
* Gets the autoscaling policies.
*
* @return 200
* @throws RestAPIException the rest api exception
*/
@GET
@Path("/autoscalingPolicies")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/getAutoscalingPolicies")
public Response getAutoscalingPolicies()
throws RestAPIException {
AutoscalePolicyBean[] autoScalePolicies = StratosApiV41Utils.getAutoScalePolicies();
if (autoScalePolicies == null || autoScalePolicies.length == 0) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.SUCCESS, "No autoscaling policies found")).build();
}
return Response.ok().entity(autoScalePolicies).build();
}
/**
* Gets the autoscaling policy.
*
* @param autoscalePolicyId the autoscale policy id
* @return 200 if specified autoscaling policy is found, 404 if not
* @throws RestAPIException the rest api exception
*/
@GET
@Path("/autoscalingPolicies/{autoscalePolicyId}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/getAutoscalingPolicies")
public Response getAutoscalingPolicy(
@PathParam("autoscalePolicyId") String autoscalePolicyId) throws RestAPIException {
AutoscalePolicyBean autoScalePolicy = StratosApiV41Utils.getAutoScalePolicy(autoscalePolicyId);
if (autoScalePolicy == null) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.SUCCESS, "Autoscaling policy not found")).build();
}
return Response.ok().entity(autoScalePolicy).build();
}
/**
* Creates the autoscaling policy defintion.
*
* @param autoscalePolicy the autoscale policy
* @return 201 if autoscale policy is successfully added
* @throws RestAPIException the rest api exception
*/
@POST
@Path("/autoscalingPolicies")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/addAutoscalingPolicy")
public Response addAutoscalingPolicy(
AutoscalePolicyBean autoscalePolicy) throws RestAPIException {
try {
StratosApiV41Utils.addAutoscalingPolicy(autoscalePolicy);
URI url = uriInfo.getAbsolutePathBuilder().path(autoscalePolicy.getId()).build();
return Response.created(url).entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Autoscaling policy added successfully: [autoscale-policy] %s",
autoscalePolicy.getId()))).build();
} catch (AutoscalerServiceInvalidPolicyExceptionException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Provided Autoscaling policy is invalid")).build();
} catch (AutoscalerServiceAutoScalingPolicyAlreadyExistExceptionException e) {
return Response.status(Response.Status.CONFLICT).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Autoscaling policy already exists")).build();
} catch (RestAPIException e) {
throw e;
}
}
/**
* Update autoscaling policy.
*
* @param autoscalePolicy the autoscale policy
* @return 200 if autoscale policy is successfully updated
* @throws RestAPIException the rest api exception
*/
@PUT
@Path("/autoscalingPolicies")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/updateAutoscalingPolicy")
public Response updateAutoscalingPolicy(
AutoscalePolicyBean autoscalePolicy) throws RestAPIException {
try {
StratosApiV41Utils.updateAutoscalingPolicy(autoscalePolicy);
} catch (AutoscalerServiceInvalidPolicyExceptionException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Autoscaling policy is invalid")).build();
}
return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Autoscaling policy updated successfully: [autoscale-policy] %s",
autoscalePolicy.getId()))).build();
}
/**
* Updates a network partition
*
* @param networkPartition Network Partition
* @return 200 if network partition is successfully updated
* @throws RestAPIException
*/
@PUT
@Path("/networkPartitions")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/updateNetworkPartition")
public Response updateNetworkPartition(
NetworkPartitionBean networkPartition) throws RestAPIException {
try {
StratosApiV41Utils.updateNetworkPartition(networkPartition);
} catch (CloudControllerServiceNetworkPartitionNotExistsExceptionException e) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Network partition not found")).build();
}
return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Network Partition updated successfully: [network-partition] %s",
networkPartition.getId()))).build();
}
/**
* Remove autoscaling policy.
*
* @param autoscalingPolicyId the autoscale policy
* @return 200
* @throws RestAPIException the rest api exception
*/
@DELETE
@Path("/autoscalingPolicies/{autoscalingPolicyId}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/removeAutoscalingPolicy")
public Response removeAutoscalingPolicy(
@PathParam("autoscalingPolicyId") String autoscalingPolicyId) throws RestAPIException {
try {
StratosApiV41Utils.removeAutoscalingPolicy(autoscalingPolicyId);
} catch (AutoscalerServiceUnremovablePolicyExceptionException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Autoscaling policy is in use")).build();
} catch (AutoscalerServicePolicyDoesNotExistExceptionException e) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Autoscaling policy not found")).build();
}
return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Autoscaling policy deleted successfully: [autoscale-policy] %s",
autoscalingPolicyId))).build();
}
/**
* Get cluster for a given cluster id
*
* @param clusterId id of the cluster
* @return 200 if specified cluster is found, 404 if not
* @throws RestAPIException the rest api exception
*/
@GET
@Path("/cluster/{clusterId}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/cluster")
public Response getCluster(
@PathParam("clusterId") String clusterId) throws RestAPIException {
try {
ClusterBean clusterBean = StratosApiV41Utils.getClusterInfo(clusterId);
if (clusterBean == null) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.SUCCESS, "Cluster not found")).build();
} else {
return Response.ok().entity(clusterBean).build();
}
} catch (ClusterIdIsEmptyException e) {
return Response.status(Response.Status.BAD_REQUEST).build();
}
}
// API methods for tenants
/**
* Adds the tenant.
*
* @param tenantInfoBean the tenant info bean
* @return 201 if the tenant is successfully added
* @throws RestAPIException the rest api exception
*/
@POST
@Path("/tenants")
@Consumes("application/json")
@Produces("application/json")
@AuthorizationAction("/permission/protected/manage/addTenant")
@SuperTenantService(true)
public Response addTenant(
org.apache.stratos.common.beans.TenantInfoBean tenantInfoBean) throws RestAPIException {
try {
StratosApiV41Utils.addTenant(tenantInfoBean);
} catch (InvalidEmailException e) {
Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Invalid email")).build();
} catch (InvalidDomainException e) {
Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Invalid domain")).build();
}
URI url = uriInfo.getAbsolutePathBuilder().path(tenantInfoBean.getTenantDomain()).build();
return Response.created(url).entity(
new ResponseMessageBean(ResponseMessageBean.SUCCESS, String.format(
"Tenant added successfully: [tenant] %s", tenantInfoBean.getTenantDomain()))).build();
}
/**
* Update tenant.
*
* @param tenantInfoBean the tenant info bean
* @return 200 if tenant is successfully updated, 404 if specified tenant not found
* @throws RestAPIException the rest api exception
*/
@PUT
@Path("/tenants")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/updateTenant")
@SuperTenantService(true)
public Response updateTenant(
org.apache.stratos.common.beans.TenantInfoBean tenantInfoBean) throws RestAPIException {
try {
StratosApiV41Utils.updateExistingTenant(tenantInfoBean);
} catch (TenantNotFoundException ex) {
Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Tenant not found")).build();
} catch (InvalidEmailException e) {
Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Invalid email")).build();
} catch (Exception e) {
String msg = "Error in updating tenant " + tenantInfoBean.getTenantDomain();
log.error(msg, e);
throw new RestAPIException(msg);
}
return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Tenant updated successfully: [tenant] %s", tenantInfoBean.getTenantDomain()))).build();
}
/**
* Gets the tenant by domain.
*
* @param tenantDomain the tenant domain
* @return 200 if tenant for specified tenant domain found
* @throws RestAPIException the rest api exception
*/
@GET
@Path("/tenants/{tenantDomain}")
@Consumes("application/json")
@Produces("application/json")
@AuthorizationAction("/permission/protected/manage/getTenantForDomain")
@SuperTenantService(true)
public Response getTenantForDomain(
@PathParam("tenantDomain") String tenantDomain) throws RestAPIException {
try {
TenantInfoBean tenantInfo = StratosApiV41Utils.getTenantByDomain(tenantDomain);
if (tenantInfo == null) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.SUCCESS, "Tenant information not found")).build();
}
return Response.ok().entity(tenantInfo).build();
} catch (Exception e) {
return Response.status(Response.Status.NOT_FOUND).build();
}
}
/**
* Delete tenant.
*
* @param tenantDomain the tenant domain
* @return 406 - Use tenantDeactivate method
* @throws RestAPIException the rest api exception
*/
@DELETE
@Path("/tenants/{tenantDomain}")
@Consumes("application/json")
@Produces("application/json")
@AuthorizationAction("/permission/protected/manage/removeTenant")
@SuperTenantService(true)
public Response removeTenant(
@PathParam("tenantDomain") String tenantDomain) throws RestAPIException {
return Response.status(Response.Status.NOT_ACCEPTABLE)
.entity(new ResponseMessageBean(ResponseMessageBean.ERROR,
"Please use the tenant deactivate method")).build();
}
/**
* Gets the tenants.
*
* @return 200
* @throws RestAPIException the rest api exception
*/
@GET
@Path("/tenants")
@Produces("application/json")
@AuthorizationAction("/permission/protected/manage/getTenants")
@SuperTenantService(true)
public Response getTenants()
throws RestAPIException {
try {
List<org.apache.stratos.common.beans.TenantInfoBean> tenantList = StratosApiV41Utils.getAllTenants();
if (tenantList == null || tenantList.isEmpty()) {
return Response.status(Response.Status.NOT_FOUND).build();
}
return Response.ok().entity(tenantList.toArray(
new org.apache.stratos.common.beans.TenantInfoBean[tenantList.size()])).build();
} catch (Exception e) {
String msg = "Error in retrieving tenants";
log.error(msg, e);
throw new RestAPIException(msg);
}
}
/**
* Gets the partial search tenants.
*
* @param tenantDomain the tenant domain
* @return 200
* @throws RestAPIException the rest api exception
*/
@GET
@Path("/tenants/search/{tenantDomain}")
@Consumes("application/json")
@Produces("application/json")
@AuthorizationAction("/permission/protected/manage/getTenants")
@SuperTenantService(true)
public Response getPartialSearchTenants(
@PathParam("tenantDomain") String tenantDomain) throws RestAPIException {
try {
List<org.apache.stratos.common.beans.TenantInfoBean> tenantList = StratosApiV41Utils.searchPartialTenantsDomains(tenantDomain);
if (tenantList == null || tenantList.isEmpty()) {
return Response.status(Response.Status.NOT_FOUND).build();
}
return Response.ok().entity(tenantList.toArray(new org.apache.stratos.common.beans.TenantInfoBean[tenantList.size()])).build();
} catch (Exception e) {
String msg = "Error in getting information for tenant " + tenantDomain;
log.error(msg, e);
throw new RestAPIException(msg);
}
}
/**
* Activate tenant.
*
* @param tenantDomain the tenant domain
* @return 200 if tenant activated successfully
* @throws RestAPIException the rest api exception
*/
@PUT
@Path("/tenants/activate/{tenantDomain}")
@Consumes("application/json")
@Produces("application/json")
@AuthorizationAction("/permission/protected/manage/activateTenant")
@SuperTenantService(true)
public Response activateTenant(
@PathParam("tenantDomain") String tenantDomain) throws RestAPIException {
StratosApiV41Utils.activateTenant(tenantDomain);
return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Tenant activated successfully: [tenant] %s", tenantDomain))).build();
}
/**
* Deactivate tenant.
*
* @param tenantDomain the tenant domain
* @return 200 if tenant deactivated successfully
* @throws RestAPIException the rest api exception
*/
@PUT
@Path("/tenants/deactivate/{tenantDomain}")
@Consumes("application/json")
@Produces("application/json")
@AuthorizationAction("/permission/protected/manage/deactivateTenant")
@SuperTenantService(true)
public Response deactivateTenant(
@PathParam("tenantDomain") String tenantDomain) throws RestAPIException {
StratosApiV41Utils.deactivateTenant(tenantDomain);
return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Tenant deactivated successfully: [tenant] %s", tenantDomain))).build();
}
// API methods for repositories
/**
* Notify artifact update event for specified repository
*
* @param payload Git notification Payload
* @return 204
* @throws RestAPIException
*/
@POST
@Path("/repo/notify")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/notifyRepository")
public Response notifyRepository(
GitNotificationPayloadBean payload) throws RestAPIException {
if (log.isInfoEnabled()) {
log.info(String.format("Git update notification received."));
}
StratosApiV41Utils.notifyArtifactUpdatedEvent(payload);
return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Repository notification sent successfully"))).build();
}
// API methods for users
/**
* Adds the user.
*
* @param userInfoBean the user info bean
* @return 201 if the user is successfully created
* @throws RestAPIException the rest api exception
*/
@POST
@Path("/users")
@Consumes("application/json")
@Produces("application/json")
@AuthorizationAction("/permission/admin/manage/addUser")
public Response addUser(
UserInfoBean userInfoBean) throws RestAPIException {
StratosApiV41Utils.addUser(userInfoBean);
log.info("Successfully added an user with Username " + userInfoBean.getUserName());
URI url = uriInfo.getAbsolutePathBuilder().path(userInfoBean.getUserName()).build();
return Response.created(url).entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("User added successfully: [user] %s", userInfoBean.getUserName()))).build();
}
/**
* Delete user.
*
* @param userName the user name
* @return 200 if the user is successfully deleted
* @throws RestAPIException the rest api exception
*/
@DELETE
@Path("/users/{userName}")
@Consumes("application/json")
@Produces("application/json")
@AuthorizationAction("/permission/admin/manage/removeUser")
public Response removeUser(
@PathParam("userName") String userName) throws RestAPIException {
StratosApiV41Utils.removeUser(userName);
log.info("Successfully removed user: [username] " + userName);
return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("User deleted successfully: [user] %s", userName))).build();
}
/**
* Update user.
*
* @param userInfoBean the user info bean
* @return 200 if the user is successfully updated
* @throws RestAPIException the rest api exception
*/
@PUT
@Path("/users")
@Consumes("application/json")
@Produces("application/json")
@AuthorizationAction("/permission/admin/manage/updateUser")
public Response updateUser(
UserInfoBean userInfoBean) throws RestAPIException {
StratosApiV41Utils.updateUser(userInfoBean);
log.info("Successfully updated an user with Username " + userInfoBean.getUserName());
return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("User updated successfully: [user] %s", userInfoBean.getUserName()))).build();
}
/**
* Gets the users.
*
* @return 200
* @throws RestAPIException the rest api exception
*/
@GET
@Path("/users")
@Produces("application/json")
@AuthorizationAction("/permission/admin/manage/getUsers")
public Response getUsers()
throws RestAPIException {
List<UserInfoBean> userList = StratosApiV41Utils.getUsers();
return Response.ok().entity(userList.toArray(new UserInfoBean[userList.size()])).build();
}
// API methods for Kubernetes clusters
/**
* Deploy kubernetes host cluster.
*
* @param kubernetesCluster the kubernetes cluster
* @return 201 if the kubernetes cluster is successfully created
* @throws RestAPIException the rest api exception
*/
@POST
@Path("/kubernetesClusters")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/addKubernetesCluster")
public Response addKubernetesHostCluster(
KubernetesClusterBean kubernetesCluster) throws RestAPIException {
try {
StratosApiV41Utils.addKubernetesCluster(kubernetesCluster);
URI url = uriInfo.getAbsolutePathBuilder().path(kubernetesCluster.getClusterId()).build();
return Response.created(url).entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Kubernetes cluster added successfully: [kub-host-cluster] %s",
kubernetesCluster.getClusterId()))).build();
} catch (RestAPIException e) {
throw e;
} catch (CloudControllerServiceKubernetesClusterAlreadyExistsExceptionException e) {
return Response.status(Response.Status.CONFLICT).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Kubernetes cluster already exists")).build();
} catch (CloudControllerServiceInvalidKubernetesClusterExceptionException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Kubernetes cluster is invalid")).build();
}
}
/**
* Deploy kubernetes host.
*
* @param kubernetesClusterId the kubernetes cluster id
* @param kubernetesHost the kubernetes host
* @return 201 if the kubernetes host is successfully added
* @throws RestAPIException the rest api exception
*/
@POST
@Path("/kubernetesClusters/{kubernetesClusterId}/minion")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/addKubernetesHost")
public Response addKubernetesHost(
@PathParam("kubernetesClusterId") String kubernetesClusterId, KubernetesHostBean kubernetesHost)
throws RestAPIException {
StratosApiV41Utils.addKubernetesHost(kubernetesClusterId, kubernetesHost);
URI url = uriInfo.getAbsolutePathBuilder().path(kubernetesHost.getHostId()).build();
return Response.created(url).entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Kubernetes host added successfully: [kub-host] %s", kubernetesHost.getHostId()))).build();
}
/**
* Update kubernetes master.
*
* @param kubernetesMaster the kubernetes master
* @return 200 if the kubernetes master is updated successfully, 404 if the kubernetes master is not found
* @throws RestAPIException the rest api exception
*/
@PUT
@Path("/kubernetesClusters/{kubernetesClusterId}/master")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/updateKubernetesMaster")
public Response updateKubernetesMaster(
KubernetesMasterBean kubernetesMaster) throws RestAPIException {
try {
StratosApiV41Utils.updateKubernetesMaster(kubernetesMaster);
URI url = uriInfo.getAbsolutePathBuilder().path(kubernetesMaster.getHostId()).build();
return Response.ok(url).entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Kubernetes master updated successfully: [kub-master] %s",
kubernetesMaster.getHostId()))).build();
} catch (RestAPIException e) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Kubernetes cluster not found")).build();
}
}
@PUT
@Path("/kubernetes/update/host")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/updateKubernetesHost")
public Response updateKubernetesHost(
KubernetesHostBean kubernetesHost) throws RestAPIException {
try {
StratosApiV41Utils.updateKubernetesHost(kubernetesHost);
URI url = uriInfo.getAbsolutePathBuilder().path(kubernetesHost.getHostId()).build();
return Response.ok(url).entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Kubernetes Host updated successfully: [kub-host] %s",
kubernetesHost.getHostId()))).build();
} catch (RestAPIException e) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Kubernetes host not found")).build();
}
}
/**
* Gets the kubernetes host clusters.
*
* @return 200
* @throws RestAPIException the rest api exception
*/
@GET
@Path("/kubernetesClusters")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/getKubernetesHostClusters")
public Response getKubernetesHostClusters() throws RestAPIException {
KubernetesClusterBean[] availableKubernetesClusters = StratosApiV41Utils.getAvailableKubernetesClusters();
if (availableKubernetesClusters == null || availableKubernetesClusters.length == 0) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.SUCCESS, "Kubernetes clusters not found")).build();
}
return Response.ok().entity(availableKubernetesClusters).build();
}
/**
* Gets the kubernetes host cluster.
*
* @param kubernetesClusterId the kubernetes cluster id
* @return 200 if specified kubernetes host cluster is found, 404 if not
* @throws RestAPIException the rest api exception
*/
@GET
@Path("/kubernetesClusters/{kubernetesClusterId}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/getKubernetesHostClusters")
public Response getKubernetesHostCluster(
@PathParam("kubernetesClusterId") String kubernetesClusterId) throws RestAPIException {
try {
return Response.ok().entity(StratosApiV41Utils.getKubernetesCluster(kubernetesClusterId)).build();
} catch (RestAPIException e) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Kubernetes cluster not found")).build();
}
}
/**
* Gets the kubernetes hosts of kubernetes cluster.
*
* @param kubernetesClusterId the kubernetes cluster id
* @return 200 if hosts are found in the specified kubernetes host cluster, 404 if not
* @throws RestAPIException the rest api exception
*/
@GET
@Path("/kubernetesClusters/{kubernetesClusterId}/hosts")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/getKubernetesHostClusters")
public Response getKubernetesHostsOfKubernetesCluster(
@PathParam("kubernetesClusterId") String kubernetesClusterId) throws RestAPIException {
try {
return Response.ok().entity(StratosApiV41Utils.getKubernetesHosts(kubernetesClusterId)).build();
} catch (RestAPIException e) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Kubernetes hosts not found")).build();
}
}
/**
* Gets the kubernetes master of kubernetes cluster.
*
* @param kubernetesClusterId the kubernetes cluster id
* @return 200 if master is found for specified kubernetes cluster, 404 if not
* @throws RestAPIException the rest api exception
*/
@GET
@Path("/kubernetesClusters/{kubernetesClusterId}/master")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/getKubernetesHostClusters")
public Response getKubernetesMasterOfKubernetesCluster(
@PathParam("kubernetesClusterId") String kubernetesClusterId) throws RestAPIException {
try {
return Response.ok().entity(StratosApiV41Utils.getKubernetesMaster(kubernetesClusterId)).build();
} catch (RestAPIException e) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Kubernetes cluster not found")).build();
}
}
/**
* Un deploy kubernetes host cluster.
*
* @param kubernetesClusterId the kubernetes cluster id
* @return 204 if Kubernetes cluster is successfully removed, 404 if the specified Kubernetes cluster is not found
* @throws RestAPIException the rest api exception
*/
@DELETE
@Path("/kubernetesClusters/{kubernetesClusterId}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/removeKubernetesHostCluster")
public Response removeKubernetesHostCluster(
@PathParam("kubernetesClusterId") String kubernetesClusterId) throws RestAPIException {
try {
StratosApiV41Utils.removeKubernetesCluster(kubernetesClusterId);
} catch (CloudControllerServiceNonExistingKubernetesClusterExceptionException e) {
return Response.status(Response.Status.NOT_FOUND)
.entity(new ResponseMessageBean(ResponseMessageBean.ERROR,
String.format("Could not find specified Kubernetes cluster: [kub-cluster] %s",
kubernetesClusterId))).build();
}
return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Kubernetes Cluster removed successfully: [kub-cluster] %s", kubernetesClusterId)))
.build();
}
/**
* Undeploy kubernetes host of kubernetes cluster.
*
* @param kubernetesHostId the kubernetes host id
* @return 200 if hosts are successfully removed from the specified Kubernetes cluster, 404 if specified Kubernetes
* cluster is not found.
* @throws RestAPIException the rest api exception
*/
@DELETE
@Path("/kubernetesClusters/{kubernetesClusterId}/hosts/{hostId}")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/admin/manage/removeKubernetesHostCluster")
public Response removeKubernetesHostOfKubernetesCluster(
@PathParam("hostId") String kubernetesHostId) throws RestAPIException {
try {
StratosApiV41Utils.removeKubernetesHost(kubernetesHostId);
} catch (RestAPIException e) {
return Response.status(Response.Status.NOT_FOUND).entity(new ResponseMessageBean(
ResponseMessageBean.ERROR, "Kubernetes cluster not found")).build();
}
return Response.ok().entity(new ResponseMessageBean(ResponseMessageBean.SUCCESS,
String.format("Kubernetes Host removed successfully: [kub-host] %s", kubernetesHostId)))
.build();
}
}
| Fixing response message statuses of HTTP NOT_FOUND scenarios
| components/org.apache.stratos.rest.endpoint/src/main/java/org/apache/stratos/rest/endpoint/api/StratosApiV41.java | Fixing response message statuses of HTTP NOT_FOUND scenarios |
|
Java | apache-2.0 | 6a8a9a0d0c40ebebeabd953aeb6742d820d49598 | 0 | cherryhill/collectionspace-application | /* Copyright 2010 University of Cambridge
* Licensed under the Educational Community License (ECL), Version 2.0. You may not use this file except in
* compliance with this License.
*
* You may obtain a copy of the ECL 2.0 License at https://source.collectionspace.org/collection-space/LICENSE.txt
*/
package org.collectionspace.chain.csp.persistence.services.relation;
import static org.junit.Assert.*;
import org.collectionspace.chain.csp.persistence.TestBase;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.AfterClass;
import org.junit.Test;
import org.mortbay.jetty.testing.HttpTester;
import org.mortbay.jetty.testing.ServletTester;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestRelationsThroughWebapp {
private static final Logger log = LoggerFactory
.getLogger(TestRelationsThroughWebapp.class);
private static TestBase tester = new TestBase();
private JSONObject createMini(String type, String id) throws JSONException {
JSONObject out = new JSONObject();
out.put("csid", id);
out.put("recordtype", type);
return out;
}
private JSONObject createRelation(String src_type, String src, String type,
String dst_type, String dst, boolean one_way) throws JSONException {
JSONObject out = new JSONObject();
out.put("source", createMini(src_type, src));
out.put("target", createMini(dst_type, dst));
out.put("type", type);
out.put("one-way", one_way);
return out;
}
@Test
public void testRelationsCreate() throws Exception {
// First create atester. couple of cataloging
ServletTester jetty = tester.setupJetty();
HttpTester out = tester.POSTData("/cataloging/",
tester.makeSimpleRequest(tester.getResourceString("obj3.json")), jetty);
String id1 = out.getHeader("Location");
out =tester.POSTData("/cataloging/",
tester.makeSimpleRequest(tester.getResourceString("obj3.json")), jetty);
String id2 = out.getHeader("Location");
out = tester.POSTData("/cataloging/",
tester.makeSimpleRequest(tester.getResourceString("obj3.json")), jetty);
String id3 = out.getHeader("Location");
String[] path1 = id1.split("/");
String[] path2 = id2.split("/");
String[] path3 = id3.split("/");
// Now create a pair of relations in: 3<->1, 3->2: a. 1->3, b. 3->1, c.
// 3->2
out = tester.POSTData("/relationships", createRelation(path3[1], path3[2],
"affects", path1[1], path1[2], false), jetty);
log.info(out.getContent());
String relid1 = out.getHeader("Location");
String csid1 = new JSONObject(out.getContent()).getString("csid");
out = tester.POSTData("/relationships", createRelation(path3[1], path3[2],
"affects", path2[1], path2[2], true), jetty);
log.info(out.getContent());
String relid2 = out.getHeader("Location");
String csid2 = new JSONObject(out.getContent()).getString("csid");
// Check 1 has relation to 3
out = tester.GETData(id1, jetty);
JSONObject data1 = new JSONObject(out.getContent());
// that the destination is 3
log.info(out.getContent());
JSONArray rel1 = data1.getJSONObject("relations").getJSONArray(
"cataloging");
assertNotNull(rel1);
assertEquals(1, rel1.length());
JSONObject mini1 = rel1.getJSONObject(0);
assertEquals("cataloging", mini1.getString("recordtype"));
assertEquals(mini1.getString("csid"), path3[2]);
String rida = mini1.getString("relid");
// pull the relation itself, and check it
out = tester.GETData("/relationships/" + rida, jetty);
JSONObject rd1 = new JSONObject(out.getContent());
assertEquals("affects", rd1.getString("type"));
assertEquals(rida, rd1.getString("csid"));
JSONObject src1 = rd1.getJSONObject("source");
assertEquals("cataloging", src1.getString("recordtype"));
assertEquals(path1[2], src1.get("csid"));
JSONObject dst1 = rd1.getJSONObject("target");
assertEquals("cataloging", dst1.getString("recordtype"));
assertEquals(path3[2], dst1.get("csid"));
// Check that 2 has no relations at all
out = tester.GETData(id2, jetty);
JSONObject data2 = new JSONObject(out.getContent());
// that the destination is 3
JSONObject rel2 = data2.getJSONObject("relations");
assertNotNull(rel2);
assertEquals(0, rel2.length());
// Check that 3 has relations to 1 and 2
out = tester.GETData(id3, jetty);
JSONObject data3 = new JSONObject(out.getContent());
// untangle them
JSONArray rel3 = data3.getJSONObject("relations").getJSONArray(
"cataloging");
assertNotNull(rel3);
assertEquals(2, rel3.length());
int i0 = 0, i1 = 1;
String rel_a = rel3.getJSONObject(i0).getString("csid");
String rel_b = rel3.getJSONObject(i1).getString("csid");
if (rel_a.equals(path2[2]) && rel_b.equals(path1[2])) {
i0 = 1;
i1 = 0;
}
JSONObject rel31 = rel3.getJSONObject(i0);
JSONObject rel32 = rel3.getJSONObject(i1);
// check desintations
assertEquals("cataloging", rel31.getString("recordtype"));
assertEquals(rel31.getString("csid"), path1[2]);
String rid31 = rel31.getString("relid");
assertEquals("cataloging", rel32.getString("recordtype"));
assertEquals(rel32.getString("csid"), path2[2]);
String rid32 = rel32.getString("relid");
// check actual records
// 3 -> 1
out = tester.GETData("/relationships/" + rid31, jetty);
JSONObject rd31 = new JSONObject(out.getContent());
assertEquals("affects", rd31.getString("type"));
assertEquals(rid31, rd31.getString("csid"));
JSONObject src31 = rd31.getJSONObject("source");
assertEquals("cataloging", src31.getString("recordtype"));
assertEquals(path3[2], src31.get("csid"));
JSONObject dst31 = rd31.getJSONObject("target");
assertEquals("cataloging", dst31.getString("recordtype"));
assertEquals(path1[2], dst31.get("csid"));
// 3 -> 2
out = tester.GETData("/relationships/" + rid32, jetty);
JSONObject rd32 = new JSONObject(out.getContent());
assertEquals("affects", rd32.getString("type"));
assertEquals(rid32, rd32.getString("csid"));
JSONObject src32 = rd32.getJSONObject("source");
assertEquals("cataloging", src32.getString("recordtype"));
assertEquals(path3[2], src32.get("csid"));
JSONObject dst32 = rd32.getJSONObject("target");
assertEquals("cataloging", dst32.getString("recordtype"));
assertEquals(path2[2], dst32.get("csid"));
/* clean up */
tester.DELETEData("/relationships/" + csid1, jetty);
tester.DELETEData("/relationships/" + csid2, jetty);
tester.DELETEData(id1, jetty);
tester.DELETEData(id2, jetty);
tester.DELETEData(id3, jetty);
tester.stopJetty(jetty);
}
@Test
public void testLoginTest() throws Exception {
// initially set up with logged in user
ServletTester jetty = tester.setupJetty();
HttpTester out = tester.GETData("/loginstatus", jetty);
JSONObject data3 = new JSONObject(out.getContent());
Boolean rel3 = data3.getBoolean("login");
assertTrue(rel3);
// logout the user
out = tester.GETData("/logout", jetty, 303);
// should get false
out = tester.GETData("/loginstatus", jetty);
JSONObject data2 = new JSONObject(out.getContent());
Boolean rel2 = data2.getBoolean("login");
assertFalse(rel2);
tester.stopJetty(jetty);
}
// XXX factor out creation
@Test
public void testRelationsMissingOneWay() throws Exception {
// First create a couple of cataloging
ServletTester jetty = tester.setupJetty();
HttpTester out = tester.POSTData("/cataloging/",
tester.makeSimpleRequest(tester.getResourceString("obj3.json")), jetty);
String id1 = out.getHeader("Location");
out = tester.POSTData("/cataloging/",
tester.makeSimpleRequest(tester.getResourceString("obj3.json")), jetty);
String id2 = out.getHeader("Location");
out = tester.POSTData("/cataloging/",
tester.makeSimpleRequest(tester.getResourceString("obj3.json")), jetty);
String id3 = out.getHeader("Location");
String[] path1 = id1.split("/");
String[] path3 = id3.split("/");
JSONObject data = createRelation(path3[1], path3[2], "affects",
path1[1], path1[2], false);
data.remove("one-way");
out = tester.POSTData("/relationships", data, jetty);
// Get csid
JSONObject datacs = new JSONObject(out.getContent());
String csid1 = datacs.getString("csid");
// Just heck they have length 1 (other stuff will be tested by main
// test)
out = tester.GETData(id3, jetty);
JSONObject data3 = new JSONObject(out.getContent());
JSONArray rel3 = data3.getJSONObject("relations").getJSONArray(
"cataloging");
assertNotNull(rel3);
assertEquals(1, rel3.length());
out = tester.GETData(id1, jetty);
JSONObject data1 = new JSONObject(out.getContent());
JSONArray rel1 = data1.getJSONObject("relations").getJSONArray(
"cataloging");
assertNotNull(rel1);
assertEquals(1, rel1.length());
// clean up after
tester.DELETEData("/relationships/" + csid1, jetty);
tester.DELETEData(id1, jetty);
tester.DELETEData(id2, jetty);
tester.DELETEData(id3, jetty);
tester.stopJetty(jetty);
}
@Test
public void testMultipleCreate() throws Exception {
// Create test cataloging
ServletTester jetty = tester.setupJetty();
HttpTester out = tester.POSTData("/cataloging/",
tester.makeSimpleRequest(tester.getResourceString("obj3.json")), jetty);
String id1 = out.getHeader("Location");
out = tester.POSTData("/cataloging/",
tester.makeSimpleRequest(tester.getResourceString("obj3.json")), jetty);
String id2 = out.getHeader("Location");
out = tester.POSTData("/cataloging/",
tester.makeSimpleRequest(tester.getResourceString("obj3.json")), jetty);
String id3 = out.getHeader("Location");
String[] path1 = id1.split("/");
String[] path2 = id2.split("/");
String[] path3 = id3.split("/");
// Do the rleation
JSONObject data1 = createRelation(path3[1], path3[2], "affects",
path1[1], path1[2], false);
JSONObject data2 = createRelation(path3[1], path3[2], "affects",
path2[1], path2[2], false);
JSONArray datas = new JSONArray();
datas.put(data1);
datas.put(data2);
JSONObject data = new JSONObject();
data.put("items", datas);
out = tester.POSTData("/relationships", data, jetty);
// Check it
out = tester.GETData(id3, jetty);
JSONObject data3 = new JSONObject(out.getContent());
JSONArray rel3 = data3.getJSONObject("relations").getJSONArray(
"cataloging");
assertNotNull(rel3);
assertEquals(2, rel3.length());
tester.DELETEData(id1, jetty);
tester.DELETEData(id2, jetty);
tester.DELETEData(id3, jetty);
tester.stopJetty(jetty);
}
// XXX update of two-way relations
// XXX update of one-wayness
@Test
public void testUpdate() throws Exception {
// Create test cataloging
ServletTester jetty = tester.setupJetty();
HttpTester out = tester.POSTData("/cataloging/",
tester.makeSimpleRequest(tester.getResourceString("obj3.json")), jetty);
String id1 = out.getHeader("Location");
out = tester.POSTData("/cataloging/",
tester.makeSimpleRequest(tester.getResourceString("obj3.json")), jetty);
String id2 = out.getHeader("Location");
out = tester.POSTData("/cataloging/",
tester.makeSimpleRequest(tester.getResourceString("obj3.json")), jetty);
String id3 = out.getHeader("Location");
String[] path1 = id1.split("/");
String[] path2 = id2.split("/");
String[] path3 = id3.split("/");
// Create a relation 3 -> 1
out = tester.POSTData("/relationships", createRelation(path3[1], path3[2],
"affects", path1[1], path1[2], true), jetty);
// Get csid
JSONObject data = new JSONObject(out.getContent());
log.info(out.getContent());
String csid1 = data.getString("csid");
assertNotNull(csid1);
// Update it to 2 -> 1
out = tester.PUTData("/relationships/" + csid1, createRelation(path2[1],
path2[2], "affects", path1[1], path1[2], true), jetty);
log.info(out.getContent());
// Check it
out = tester.GETData(id1, jetty);
JSONObject data1 = new JSONObject(out.getContent());
JSONObject rel1 = data1.getJSONObject("relations");
out = tester.GETData(id2, jetty);
JSONObject data2 = new JSONObject(out.getContent());
log.info(out.getContent());
JSONArray rel2 = data2.getJSONObject("relations").getJSONArray(
"cataloging");
out = tester.GETData(id3, jetty);
JSONObject data3 = new JSONObject(out.getContent());
JSONObject rel3 = data3.getJSONObject("relations");
// clean up after
tester.DELETEData("/relationships/" + csid1, jetty);
tester.DELETEData(id1, jetty);
tester.DELETEData(id2, jetty);
tester.DELETEData(id3, jetty);
//test
assertNotNull(rel1);
assertEquals(0, rel1.length());
assertNotNull(rel2);
assertEquals(1, rel2.length());
assertNotNull(rel3);
assertEquals(0, rel3.length());
tester.stopJetty(jetty);
}
@Test
public void testOneWayWorksInUpdate() throws Exception {
ServletTester jetty = tester.setupJetty();
HttpTester out = tester.POSTData("/intake/",
tester.makeSimpleRequest(tester.getResourceString("2007.4-a.json")), jetty);
String id1 = out.getHeader("Location");
out = tester.POSTData("/cataloging/",
tester.makeSimpleRequest(tester.getResourceString("obj3.json")), jetty);
String id2 = out.getHeader("Location");
out = tester.POSTData("/acquisition/",
tester.makeSimpleRequest(tester.getResourceString("2005.017.json")), jetty);
String id3 = out.getHeader("Location");
String[] path1 = id1.split("/");
String[] path2 = id2.split("/");
String[] path3 = id3.split("/");
// Create a relation 3 <-> 1
out = tester.POSTData("/relationships", createRelation(path3[1], path3[2],
"affects", path1[1], path1[2], false), jetty);
// Get csid
JSONObject data = new JSONObject(out.getContent());
String csid1 = data.getString("csid");
assertNotNull(csid1);
// Update to 2 <-> 1 keeping one-way false
out = tester.PUTData("/relationships/" + csid1, createRelation(path2[1],
path2[2], "affects", path1[1], path1[2], false), jetty);
// Check it
out = tester.GETData(id1, jetty);
JSONObject data1 = new JSONObject(out.getContent());
JSONArray rel1 = data1.getJSONObject("relations").getJSONArray(
"cataloging");
assertNotNull(rel1);
assertEquals(1, rel1.length());
out = tester.GETData(id2, jetty);
JSONObject data2 = new JSONObject(out.getContent());
JSONArray rel2 = data2.getJSONObject("relations")
.getJSONArray("intake");
assertNotNull(rel2);
assertEquals(1, rel2.length());
out = tester.GETData(id3, jetty);
JSONObject data3 = new JSONObject(out.getContent());
JSONObject rel3 = data3.getJSONObject("relations");
assertNotNull(rel3);
assertEquals(0, rel3.length());
// Update to 1 -> 3, making one-way true
String csid2 = rel1.getJSONObject(0).getString("relid");
out = tester.PUTData("/relationships/" + csid2, createRelation(path1[1],
path1[2], "affects", path3[1], path3[2], true), jetty);
// Check it
out = tester.GETData(id1, jetty);
data1 = new JSONObject(out.getContent());
rel1 = data1.getJSONObject("relations").getJSONArray("acquisition");
assertNotNull(rel1);
assertEquals(1, rel1.length());
out = tester.GETData(id2, jetty);
data2 = new JSONObject(out.getContent());
JSONObject rel2a = data2.getJSONObject("relations");
assertNotNull(rel2a);
assertEquals(0, rel2a.length());
out = tester.GETData(id3, jetty);
data3 = new JSONObject(out.getContent());
rel3 = data3.getJSONObject("relations");
assertNotNull(rel3);
assertEquals(0, rel3.length());
// Update to 3 -> 1, keeping one way true
out = tester.PUTData("/relationships/" + csid2, createRelation(path3[1],
path3[2], "affects", path1[1], path1[2], true), jetty);
// Check it
out = tester.GETData(id1, jetty);
data1 = new JSONObject(out.getContent());
JSONObject rel1a = data1.getJSONObject("relations");
assertNotNull(rel1a);
assertEquals(0, rel1a.length());
out = tester.GETData(id2, jetty);
data2 = new JSONObject(out.getContent());
rel2a = data2.getJSONObject("relations");
assertNotNull(rel2a);
assertEquals(0, rel2a.length());
out = tester.GETData(id3, jetty);
data3 = new JSONObject(out.getContent());
JSONArray rel3a = data3.getJSONObject("relations").getJSONArray(
"intake");
assertNotNull(rel3a);
assertEquals(1, rel3a.length());
// Update to 1 <-> 2, making one way false
out = tester.PUTData("/relationships/" + csid2, createRelation(path1[1],
path1[2], "affects", path2[1], path2[2], false), jetty);
// Check it
out = tester.GETData(id1, jetty);
data1 = new JSONObject(out.getContent());
rel1 = data1.getJSONObject("relations").getJSONArray("cataloging");
assertNotNull(rel1);
assertEquals(1, rel1.length());
out = tester.GETData(id2, jetty);
data2 = new JSONObject(out.getContent());
rel2 = data2.getJSONObject("relations").getJSONArray("intake");
assertNotNull(rel2);
assertEquals(1, rel2.length());
out = tester.GETData(id3, jetty);
data3 = new JSONObject(out.getContent());
rel3 = data3.getJSONObject("relations");
assertNotNull(rel3);
assertEquals(0, rel3.length());
// clean up after
tester.DELETEData(id1, jetty);
tester.DELETEData(id2, jetty);
tester.DELETEData(id3, jetty);
tester.stopJetty(jetty);
}
@Test
public void testRelationshipType() throws Exception {
// Create test cataloging
ServletTester jetty = tester.setupJetty();
HttpTester out = tester.POSTData("/cataloging/",
tester.makeSimpleRequest(tester.getResourceString("obj3.json")), jetty);
String id1 = out.getHeader("Location");
out = tester.POSTData("/intake/",
tester.makeSimpleRequest(tester.getResourceString("2007.4-a.json")), jetty);
String id2 = out.getHeader("Location");
String[] path1 = id1.split("/");
String[] path2 = id2.split("/");
// Relate them
out = tester.POSTData("/relationships/", createRelation(path2[1], path2[2],
"affects", path1[1], path1[2], false), jetty);
String csid = new JSONObject(out.getContent()).getString("csid");
// Check types
out = tester.GETData(id1, jetty);
JSONObject data1 = new JSONObject(out.getContent());
JSONArray rels1 = data1.getJSONObject("relations").getJSONArray(
"intake");
assertNotNull(rels1);
assertEquals(1, rels1.length());
JSONObject rel1 = rels1.getJSONObject(0);
assertEquals(rel1.getString("recordtype"), "intake");
out = tester.GETData(id2, jetty);
JSONObject data2 = new JSONObject(out.getContent());
JSONArray rels2 = data2.getJSONObject("relations").getJSONArray(
"cataloging");
assertNotNull(rels2);
assertEquals(1, rels2.length());
JSONObject rel2 = rels2.getJSONObject(0);
assertEquals(rel2.getString("recordtype"), "cataloging");
// clean up after
tester.DELETEData("/relationships/" + csid, jetty);
tester.DELETEData(id1, jetty);
tester.DELETEData(id2, jetty);
tester.stopJetty(jetty);
}
/* this is not testing anything - make it test something
@Test
public void testHierarchical() throws Exception{
// Check list is empty;
ServletTester jetty = tester.setupJetty();
String st = "/relationships/hierarchical/search?source=person/a93233e6-ca44-477d-97a0&type=hasBroader";
HttpTester out = tester.GETData(st, jetty);
log.info(out.getContent());
tester.stopJetty(jetty);
}
*/
@Test
public void testSearchList() throws Exception {
// Check list is empty
ServletTester jetty = tester.setupJetty();
HttpTester out = tester.GETData("/relationships/", jetty);
JSONArray items = new JSONObject(out.getContent())
.getJSONArray("items");
Integer offset = items.length();
// assertEquals(0,items.length());
// Create some cataloging
out = tester.POSTData("/intake/",
tester.makeSimpleRequest(tester.getResourceString("2007.4-a.json")), jetty);
String id1 = out.getHeader("Location");
out = tester.POSTData("/cataloging/",
tester.makeSimpleRequest(tester.getResourceString("obj3.json")), jetty);
String id2 = out.getHeader("Location");
out = tester.POSTData("/acquisition/",
tester.makeSimpleRequest(tester.getResourceString("2005.017.json")), jetty);
String id3 = out.getHeader("Location");
String[] path1 = id1.split("/");
String[] path2 = id2.split("/");
String[] path3 = id3.split("/");
// Add a relation rel1: 2 -> 1
out = tester.POSTData("/relationships/", createRelation(path2[1], path2[2],
"affects", path1[1], path1[2], true), jetty);
String csid1 = new JSONObject(out.getContent()).getString("csid");
out = tester.GETData("/relationships/" + csid1, jetty);
JSONObject rel1 = new JSONObject(out.getContent());
assertEquals(path2[2], rel1.getJSONObject("source").getString("csid"));
assertEquals(path1[2], rel1.getJSONObject("target").getString("csid"));
// Add some more relations: rel2: 2 -> 3 ; rel 3: 3 -> 1 (new type)
out = tester.POSTData("/relationships/", createRelation(path2[1], path2[2],
"affects", path3[1], path3[2], true), jetty);
String csid2 = new JSONObject(out.getContent()).getString("csid");
out = tester.POSTData("/relationships/", createRelation(path3[1], path3[2],
"broader", path1[1], path1[2], true), jetty);
String csid3 = new JSONObject(out.getContent()).getString("csid");
// Total length should be 3 XXX pagination & offset
// out = GETData("/relationships",jetty);
// items=new JSONObject(out.getContent()).getJSONArray("items");
// assertEquals(3,items.length());
// Should be two starting at 2
out = tester.GETData("/relationships/search?source=" + path2[1] + "/"
+ path2[2], jetty);
items = new JSONObject(out.getContent()).getJSONArray("items");
assertEquals(2, items.length());
// Should be one staring at 3, none at 1
out = tester.GETData("/relationships/search?source=" + path3[1] + "/"
+ path3[2], jetty);
items = new JSONObject(out.getContent()).getJSONArray("items");
assertEquals(1, items.length());
out = tester.GETData("/relationships/search?source=" + path1[1] + "/"
+ path1[2], jetty);
items = new JSONObject(out.getContent()).getJSONArray("items");
assertEquals(0, items.length());
// Targets: two at 1, none at 2, one at 3
out = tester.GETData("/relationships/search?target=" + path1[1] + "/"
+ path1[2], jetty);
items = new JSONObject(out.getContent()).getJSONArray("items");
assertEquals(2, items.length());
out = tester.GETData("/relationships/search?target=" + path2[1] + "/"
+ path2[2], jetty);
items = new JSONObject(out.getContent()).getJSONArray("items");
assertEquals(0, items.length());
out = tester.GETData("/relationships/search?target=" + path3[1] + "/"
+ path3[2], jetty);
items = new JSONObject(out.getContent()).getJSONArray("items");
assertEquals(1, items.length());
// out=GETData("/relationships/search?type=broader",null);
// items=new JSONObject(out.getContent()).getJSONArray("items");
// assertEquals(1,items.length());
// Combination: target = 1, type = affects; just one
out = tester.GETData("/relationships/search?type=affects&target=" + path1[1]
+ "/" + path1[2], jetty);
items = new JSONObject(out.getContent()).getJSONArray("items");
assertEquals(1, items.length());
// Combination: source = 2, target = 3; just one
out = tester.GETData("/relationships/search?source=" + path2[1] + "/"
+ path2[2] + "&target=" + path3[1] + "/" + path3[2], jetty);
items = new JSONObject(out.getContent()).getJSONArray("items");
assertEquals(1, items.length());
// clean up after
tester.DELETEData("/relationships/" + csid1, jetty);
tester.DELETEData("/relationships/" + csid2, jetty);
tester.DELETEData("/relationships/" + csid3, jetty);
tester.DELETEData(id1, jetty);
tester.DELETEData(id2, jetty);
tester.DELETEData(id3, jetty);
tester.stopJetty(jetty);
}
@Test
public void testDelete() throws Exception {
// Check size of initial is empty
ServletTester jetty = tester.setupJetty();
HttpTester out = tester.GETData("/relationships/", jetty);
JSONArray itemsall = new JSONObject(out.getContent())
.getJSONArray("items");
Integer offset = itemsall.length();
// Create some cataloging
out = tester.POSTData("/intake/",
tester.makeSimpleRequest(tester.getResourceString("2007.4-a.json")), jetty);
String id1 = out.getHeader("Location");
out = tester.POSTData("/cataloging/",
tester.makeSimpleRequest(tester.getResourceString("obj3.json")), jetty);
String id2 = out.getHeader("Location");
out = tester.POSTData("/acquisition/",
tester.makeSimpleRequest(tester.getResourceString("2005.017.json")), jetty);
String id3 = out.getHeader("Location");
String[] path1 = id1.split("/");
String[] path2 = id2.split("/");
String[] path3 = id3.split("/");
// Create three relationships, one two way
out = tester.POSTData("/relationships/", createRelation(path2[1], path2[2],
"affects", path1[1], path1[2], true), jetty);
String csid2 = new JSONObject(out.getContent()).getString("csid");
out = tester.POSTData("/relationships/", createRelation(path3[1], path3[2],
"affects", path1[1], path1[2], false), jetty);
String csid = new JSONObject(out.getContent()).getString("csid");
out = tester.POSTData("/relationships/", createRelation(path3[1], path3[2],
"affects", path2[1], path2[2], false), jetty);
String csid3 = new JSONObject(out.getContent()).getString("csid");
//delete first relationship
tester.DELETEData("/relationships/" + csid2, jetty);
//delete second relationship
String path = "/relationships/0?source="+id3+"&target="+id1+"&type=affects";
tester.DELETEData(path, jetty);
//delete third relationship
JSONObject delrel = new JSONObject();
JSONObject source = new JSONObject();
JSONObject target = new JSONObject();
source.put("csid", path3[2]);
source.put("recordtype", path3[1]);
target.put("csid", path2[2]);
target.put("recordtype", path2[1]);
delrel.put("source", source);
delrel.put("target", target);
delrel.put("type", "affects");
delrel.put("one-way", "false");
tester.DELETEData("/relationships/0", jetty, delrel.toString());
tester.DELETEData(id1, jetty);
tester.DELETEData(id2, jetty);
tester.DELETEData(id3, jetty);
tester.stopJetty(jetty);
}
// XXX DELETE RELATIONS WHEN RECORD IS DELETED: NOT FOR 0.5
}
| tomcat-main/src/test/java/org/collectionspace/chain/csp/persistence/services/relation/TestRelationsThroughWebapp.java | /* Copyright 2010 University of Cambridge
* Licensed under the Educational Community License (ECL), Version 2.0. You may not use this file except in
* compliance with this License.
*
* You may obtain a copy of the ECL 2.0 License at https://source.collectionspace.org/collection-space/LICENSE.txt
*/
package org.collectionspace.chain.csp.persistence.services.relation;
import static org.junit.Assert.*;
import org.collectionspace.chain.csp.persistence.TestBase;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.AfterClass;
import org.junit.Test;
import org.mortbay.jetty.testing.HttpTester;
import org.mortbay.jetty.testing.ServletTester;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestRelationsThroughWebapp {
private static final Logger log = LoggerFactory
.getLogger(TestRelationsThroughWebapp.class);
private static TestBase tester = new TestBase();
private JSONObject createMini(String type, String id) throws JSONException {
JSONObject out = new JSONObject();
out.put("csid", id);
out.put("recordtype", type);
return out;
}
private JSONObject createRelation(String src_type, String src, String type,
String dst_type, String dst, boolean one_way) throws JSONException {
JSONObject out = new JSONObject();
out.put("source", createMini(src_type, src));
out.put("target", createMini(dst_type, dst));
out.put("type", type);
out.put("one-way", one_way);
return out;
}
@Test
public void testRelationsCreate() throws Exception {
// First create atester. couple of cataloging
ServletTester jetty = tester.setupJetty();
HttpTester out = tester.POSTData("/cataloging/",
tester.makeSimpleRequest(tester.getResourceString("obj3.json")), jetty);
String id1 = out.getHeader("Location");
out =tester.POSTData("/cataloging/",
tester.makeSimpleRequest(tester.getResourceString("obj3.json")), jetty);
String id2 = out.getHeader("Location");
out = tester.POSTData("/cataloging/",
tester.makeSimpleRequest(tester.getResourceString("obj3.json")), jetty);
String id3 = out.getHeader("Location");
String[] path1 = id1.split("/");
String[] path2 = id2.split("/");
String[] path3 = id3.split("/");
// Now create a pair of relations in: 3<->1, 3->2: a. 1->3, b. 3->1, c.
// 3->2
out = tester.POSTData("/relationships", createRelation(path3[1], path3[2],
"affects", path1[1], path1[2], false), jetty);
log.info(out.getContent());
String relid1 = out.getHeader("Location");
String csid1 = new JSONObject(out.getContent()).getString("csid");
out = tester.POSTData("/relationships", createRelation(path3[1], path3[2],
"affects", path2[1], path2[2], true), jetty);
log.info(out.getContent());
String relid2 = out.getHeader("Location");
String csid2 = new JSONObject(out.getContent()).getString("csid");
// Check 1 has relation to 3
out = tester.GETData(id1, jetty);
JSONObject data1 = new JSONObject(out.getContent());
// that the destination is 3
log.info(out.getContent());
JSONArray rel1 = data1.getJSONObject("relations").getJSONArray(
"cataloging");
assertNotNull(rel1);
assertEquals(1, rel1.length());
JSONObject mini1 = rel1.getJSONObject(0);
assertEquals("cataloging", mini1.getString("recordtype"));
assertEquals(mini1.getString("csid"), path3[2]);
String rida = mini1.getString("relid");
// pull the relation itself, and check it
out = tester.GETData("/relationships/" + rida, jetty);
JSONObject rd1 = new JSONObject(out.getContent());
assertEquals("affects", rd1.getString("type"));
assertEquals(rida, rd1.getString("csid"));
JSONObject src1 = rd1.getJSONObject("source");
assertEquals("cataloging", src1.getString("recordtype"));
assertEquals(path1[2], src1.get("csid"));
JSONObject dst1 = rd1.getJSONObject("target");
assertEquals("cataloging", dst1.getString("recordtype"));
assertEquals(path3[2], dst1.get("csid"));
// Check that 2 has no relations at all
out = tester.GETData(id2, jetty);
JSONObject data2 = new JSONObject(out.getContent());
// that the destination is 3
JSONObject rel2 = data2.getJSONObject("relations");
assertNotNull(rel2);
assertEquals(0, rel2.length());
// Check that 3 has relations to 1 and 2
out = tester.GETData(id3, jetty);
JSONObject data3 = new JSONObject(out.getContent());
// untangle them
JSONArray rel3 = data3.getJSONObject("relations").getJSONArray(
"cataloging");
assertNotNull(rel3);
assertEquals(2, rel3.length());
int i0 = 0, i1 = 1;
String rel_a = rel3.getJSONObject(i0).getString("csid");
String rel_b = rel3.getJSONObject(i1).getString("csid");
if (rel_a.equals(path2[2]) && rel_b.equals(path1[2])) {
i0 = 1;
i1 = 0;
}
JSONObject rel31 = rel3.getJSONObject(i0);
JSONObject rel32 = rel3.getJSONObject(i1);
// check desintations
assertEquals("cataloging", rel31.getString("recordtype"));
assertEquals(rel31.getString("csid"), path1[2]);
String rid31 = rel31.getString("relid");
assertEquals("cataloging", rel32.getString("recordtype"));
assertEquals(rel32.getString("csid"), path2[2]);
String rid32 = rel32.getString("relid");
// check actual records
// 3 -> 1
out = tester.GETData("/relationships/" + rid31, jetty);
JSONObject rd31 = new JSONObject(out.getContent());
assertEquals("affects", rd31.getString("type"));
assertEquals(rid31, rd31.getString("csid"));
JSONObject src31 = rd31.getJSONObject("source");
assertEquals("cataloging", src31.getString("recordtype"));
assertEquals(path3[2], src31.get("csid"));
JSONObject dst31 = rd31.getJSONObject("target");
assertEquals("cataloging", dst31.getString("recordtype"));
assertEquals(path1[2], dst31.get("csid"));
// 3 -> 2
out = tester.GETData("/relationships/" + rid32, jetty);
JSONObject rd32 = new JSONObject(out.getContent());
assertEquals("affects", rd32.getString("type"));
assertEquals(rid32, rd32.getString("csid"));
JSONObject src32 = rd32.getJSONObject("source");
assertEquals("cataloging", src32.getString("recordtype"));
assertEquals(path3[2], src32.get("csid"));
JSONObject dst32 = rd32.getJSONObject("target");
assertEquals("cataloging", dst32.getString("recordtype"));
assertEquals(path2[2], dst32.get("csid"));
/* clean up */
tester.DELETEData("/relationships/" + csid1, jetty);
tester.DELETEData("/relationships/" + csid2, jetty);
tester.DELETEData(id1, jetty);
tester.DELETEData(id2, jetty);
tester.DELETEData(id3, jetty);
tester.stopJetty(jetty);
}
@Test
public void testLoginTest() throws Exception {
// initially set up with logged in user
ServletTester jetty = tester.setupJetty();
HttpTester out = tester.GETData("/loginstatus", jetty);
JSONObject data3 = new JSONObject(out.getContent());
Boolean rel3 = data3.getBoolean("login");
assertTrue(rel3);
// logout the user
out = tester.GETData("/logout", jetty, 303);
// should get false
out = tester.GETData("/loginstatus", jetty);
JSONObject data2 = new JSONObject(out.getContent());
Boolean rel2 = data2.getBoolean("login");
assertFalse(rel2);
tester.stopJetty(jetty);
}
// XXX factor out creation
@Test
public void testRelationsMissingOneWay() throws Exception {
// First create a couple of cataloging
ServletTester jetty = tester.setupJetty();
HttpTester out = tester.POSTData("/cataloging/",
tester.makeSimpleRequest(tester.getResourceString("obj3.json")), jetty);
String id1 = out.getHeader("Location");
out = tester.POSTData("/cataloging/",
tester.makeSimpleRequest(tester.getResourceString("obj3.json")), jetty);
String id2 = out.getHeader("Location");
out = tester.POSTData("/cataloging/",
tester.makeSimpleRequest(tester.getResourceString("obj3.json")), jetty);
String id3 = out.getHeader("Location");
String[] path1 = id1.split("/");
String[] path3 = id3.split("/");
JSONObject data = createRelation(path3[1], path3[2], "affects",
path1[1], path1[2], false);
data.remove("one-way");
out = tester.POSTData("/relationships", data, jetty);
// Get csid
JSONObject datacs = new JSONObject(out.getContent());
String csid1 = datacs.getString("csid");
// Just heck they have length 1 (other stuff will be tested by main
// test)
out = tester.GETData(id3, jetty);
JSONObject data3 = new JSONObject(out.getContent());
JSONArray rel3 = data3.getJSONObject("relations").getJSONArray(
"cataloging");
assertNotNull(rel3);
assertEquals(1, rel3.length());
out = tester.GETData(id1, jetty);
JSONObject data1 = new JSONObject(out.getContent());
JSONArray rel1 = data1.getJSONObject("relations").getJSONArray(
"cataloging");
assertNotNull(rel1);
assertEquals(1, rel1.length());
// clean up after
tester.DELETEData("/relationships/" + csid1, jetty);
tester.DELETEData(id1, jetty);
tester.DELETEData(id2, jetty);
tester.DELETEData(id3, jetty);
tester.stopJetty(jetty);
}
@Test
public void testMultipleCreate() throws Exception {
// Create test cataloging
ServletTester jetty = tester.setupJetty();
HttpTester out = tester.POSTData("/cataloging/",
tester.makeSimpleRequest(tester.getResourceString("obj3.json")), jetty);
String id1 = out.getHeader("Location");
out = tester.POSTData("/cataloging/",
tester.makeSimpleRequest(tester.getResourceString("obj3.json")), jetty);
String id2 = out.getHeader("Location");
out = tester.POSTData("/cataloging/",
tester.makeSimpleRequest(tester.getResourceString("obj3.json")), jetty);
String id3 = out.getHeader("Location");
String[] path1 = id1.split("/");
String[] path2 = id2.split("/");
String[] path3 = id3.split("/");
// Do the rleation
JSONObject data1 = createRelation(path3[1], path3[2], "affects",
path1[1], path1[2], false);
JSONObject data2 = createRelation(path3[1], path3[2], "affects",
path2[1], path2[2], false);
JSONArray datas = new JSONArray();
datas.put(data1);
datas.put(data2);
JSONObject data = new JSONObject();
data.put("items", datas);
out = tester.POSTData("/relationships", data, jetty);
// Check it
out = tester.GETData(id3, jetty);
JSONObject data3 = new JSONObject(out.getContent());
JSONArray rel3 = data3.getJSONObject("relations").getJSONArray(
"cataloging");
assertNotNull(rel3);
assertEquals(2, rel3.length());
tester.DELETEData(id1, jetty);
tester.DELETEData(id2, jetty);
tester.DELETEData(id3, jetty);
tester.stopJetty(jetty);
}
// XXX update of two-way relations
// XXX update of one-wayness
@Test
public void testUpdate() throws Exception {
// Create test cataloging
ServletTester jetty = tester.setupJetty();
HttpTester out = tester.POSTData("/cataloging/",
tester.makeSimpleRequest(tester.getResourceString("obj3.json")), jetty);
String id1 = out.getHeader("Location");
out = tester.POSTData("/cataloging/",
tester.makeSimpleRequest(tester.getResourceString("obj3.json")), jetty);
String id2 = out.getHeader("Location");
out = tester.POSTData("/cataloging/",
tester.makeSimpleRequest(tester.getResourceString("obj3.json")), jetty);
String id3 = out.getHeader("Location");
String[] path1 = id1.split("/");
String[] path2 = id2.split("/");
String[] path3 = id3.split("/");
// Create a relation 3 -> 1
out = tester.POSTData("/relationships", createRelation(path3[1], path3[2],
"affects", path1[1], path1[2], true), jetty);
// Get csid
JSONObject data = new JSONObject(out.getContent());
log.info(out.getContent());
String csid1 = data.getString("csid");
assertNotNull(csid1);
// Update it to 2 -> 1
out = tester.PUTData("/relationships/" + csid1, createRelation(path2[1],
path2[2], "affects", path1[1], path1[2], true), jetty);
log.info(out.getContent());
// Check it
out = tester.GETData(id1, jetty);
JSONObject data1 = new JSONObject(out.getContent());
JSONObject rel1 = data1.getJSONObject("relations");
out = tester.GETData(id2, jetty);
JSONObject data2 = new JSONObject(out.getContent());
log.info(out.getContent());
JSONArray rel2 = data2.getJSONObject("relations").getJSONArray(
"cataloging");
out = tester.GETData(id3, jetty);
JSONObject data3 = new JSONObject(out.getContent());
JSONObject rel3 = data3.getJSONObject("relations");
// clean up after
tester.DELETEData("/relationships/" + csid1, jetty);
tester.DELETEData(id1, jetty);
tester.DELETEData(id2, jetty);
tester.DELETEData(id3, jetty);
//test
assertNotNull(rel1);
assertEquals(0, rel1.length());
assertNotNull(rel2);
assertEquals(1, rel2.length());
assertNotNull(rel3);
assertEquals(0, rel3.length());
tester.stopJetty(jetty);
}
@Test
public void testOneWayWorksInUpdate() throws Exception {
ServletTester jetty = tester.setupJetty();
HttpTester out = tester.POSTData("/intake/",
tester.makeSimpleRequest(tester.getResourceString("2007.4-a.json")), jetty);
String id1 = out.getHeader("Location");
out = tester.POSTData("/cataloging/",
tester.makeSimpleRequest(tester.getResourceString("obj3.json")), jetty);
String id2 = out.getHeader("Location");
out = tester.POSTData("/acquisition/",
tester.makeSimpleRequest(tester.getResourceString("2005.017.json")), jetty);
String id3 = out.getHeader("Location");
String[] path1 = id1.split("/");
String[] path2 = id2.split("/");
String[] path3 = id3.split("/");
// Create a relation 3 <-> 1
out = tester.POSTData("/relationships", createRelation(path3[1], path3[2],
"affects", path1[1], path1[2], false), jetty);
// Get csid
JSONObject data = new JSONObject(out.getContent());
String csid1 = data.getString("csid");
assertNotNull(csid1);
// Update to 2 <-> 1 keeping one-way false
out = tester.PUTData("/relationships/" + csid1, createRelation(path2[1],
path2[2], "affects", path1[1], path1[2], false), jetty);
// Check it
out = tester.GETData(id1, jetty);
JSONObject data1 = new JSONObject(out.getContent());
JSONArray rel1 = data1.getJSONObject("relations").getJSONArray(
"cataloging");
assertNotNull(rel1);
assertEquals(1, rel1.length());
out = tester.GETData(id2, jetty);
JSONObject data2 = new JSONObject(out.getContent());
JSONArray rel2 = data2.getJSONObject("relations")
.getJSONArray("intake");
assertNotNull(rel2);
assertEquals(1, rel2.length());
out = tester.GETData(id3, jetty);
JSONObject data3 = new JSONObject(out.getContent());
JSONObject rel3 = data3.getJSONObject("relations");
assertNotNull(rel3);
assertEquals(0, rel3.length());
// Update to 1 -> 3, making one-way true
String csid2 = rel1.getJSONObject(0).getString("relid");
out = tester.PUTData("/relationships/" + csid2, createRelation(path1[1],
path1[2], "affects", path3[1], path3[2], true), jetty);
// Check it
out = tester.GETData(id1, jetty);
data1 = new JSONObject(out.getContent());
rel1 = data1.getJSONObject("relations").getJSONArray("acquisition");
assertNotNull(rel1);
assertEquals(1, rel1.length());
out = tester.GETData(id2, jetty);
data2 = new JSONObject(out.getContent());
JSONObject rel2a = data2.getJSONObject("relations");
assertNotNull(rel2a);
assertEquals(0, rel2a.length());
out = tester.GETData(id3, jetty);
data3 = new JSONObject(out.getContent());
rel3 = data3.getJSONObject("relations");
assertNotNull(rel3);
assertEquals(0, rel3.length());
// Update to 3 -> 1, keeping one way true
out = tester.PUTData("/relationships/" + csid2, createRelation(path3[1],
path3[2], "affects", path1[1], path1[2], true), jetty);
// Check it
out = tester.GETData(id1, jetty);
data1 = new JSONObject(out.getContent());
JSONObject rel1a = data1.getJSONObject("relations");
assertNotNull(rel1a);
assertEquals(0, rel1a.length());
out = tester.GETData(id2, jetty);
data2 = new JSONObject(out.getContent());
rel2a = data2.getJSONObject("relations");
assertNotNull(rel2a);
assertEquals(0, rel2a.length());
out = tester.GETData(id3, jetty);
data3 = new JSONObject(out.getContent());
JSONArray rel3a = data3.getJSONObject("relations").getJSONArray(
"intake");
assertNotNull(rel3a);
assertEquals(1, rel3a.length());
// Update to 1 <-> 2, making one way false
out = tester.PUTData("/relationships/" + csid2, createRelation(path1[1],
path1[2], "affects", path2[1], path2[2], false), jetty);
// Check it
out = tester.GETData(id1, jetty);
data1 = new JSONObject(out.getContent());
rel1 = data1.getJSONObject("relations").getJSONArray("cataloging");
assertNotNull(rel1);
assertEquals(1, rel1.length());
out = tester.GETData(id2, jetty);
data2 = new JSONObject(out.getContent());
rel2 = data2.getJSONObject("relations").getJSONArray("intake");
assertNotNull(rel2);
assertEquals(1, rel2.length());
out = tester.GETData(id3, jetty);
data3 = new JSONObject(out.getContent());
rel3 = data3.getJSONObject("relations");
assertNotNull(rel3);
assertEquals(0, rel3.length());
// clean up after
tester.DELETEData(id1, jetty);
tester.DELETEData(id2, jetty);
tester.DELETEData(id3, jetty);
tester.stopJetty(jetty);
}
@Test
public void testRelationshipType() throws Exception {
// Create test cataloging
ServletTester jetty = tester.setupJetty();
HttpTester out = tester.POSTData("/cataloging/",
tester.makeSimpleRequest(tester.getResourceString("obj3.json")), jetty);
String id1 = out.getHeader("Location");
out = tester.POSTData("/intake/",
tester.makeSimpleRequest(tester.getResourceString("2007.4-a.json")), jetty);
String id2 = out.getHeader("Location");
String[] path1 = id1.split("/");
String[] path2 = id2.split("/");
// Relate them
out = tester.POSTData("/relationships/", createRelation(path2[1], path2[2],
"affects", path1[1], path1[2], false), jetty);
String csid = new JSONObject(out.getContent()).getString("csid");
// Check types
out = tester.GETData(id1, jetty);
JSONObject data1 = new JSONObject(out.getContent());
JSONArray rels1 = data1.getJSONObject("relations").getJSONArray(
"intake");
assertNotNull(rels1);
assertEquals(1, rels1.length());
JSONObject rel1 = rels1.getJSONObject(0);
assertEquals(rel1.getString("recordtype"), "intake");
out = tester.GETData(id2, jetty);
JSONObject data2 = new JSONObject(out.getContent());
JSONArray rels2 = data2.getJSONObject("relations").getJSONArray(
"cataloging");
assertNotNull(rels2);
assertEquals(1, rels2.length());
JSONObject rel2 = rels2.getJSONObject(0);
assertEquals(rel2.getString("recordtype"), "cataloging");
// clean up after
tester.DELETEData("/relationships/" + csid, jetty);
tester.DELETEData(id1, jetty);
tester.DELETEData(id2, jetty);
tester.stopJetty(jetty);
}
@Test
public void testHierarchical() throws Exception{
// Check list is empty;
ServletTester jetty = tester.setupJetty();
String st = "/relationships/hierarchical/search?source=person/a93233e6-ca44-477d-97a0&type=hasBroader";
HttpTester out = tester.GETData(st, jetty);
log.info(out.getContent());
tester.stopJetty(jetty);
}
@Test
public void testSearchList() throws Exception {
// Check list is empty
ServletTester jetty = tester.setupJetty();
HttpTester out = tester.GETData("/relationships/", jetty);
JSONArray items = new JSONObject(out.getContent())
.getJSONArray("items");
Integer offset = items.length();
// assertEquals(0,items.length());
// Create some cataloging
out = tester.POSTData("/intake/",
tester.makeSimpleRequest(tester.getResourceString("2007.4-a.json")), jetty);
String id1 = out.getHeader("Location");
out = tester.POSTData("/cataloging/",
tester.makeSimpleRequest(tester.getResourceString("obj3.json")), jetty);
String id2 = out.getHeader("Location");
out = tester.POSTData("/acquisition/",
tester.makeSimpleRequest(tester.getResourceString("2005.017.json")), jetty);
String id3 = out.getHeader("Location");
String[] path1 = id1.split("/");
String[] path2 = id2.split("/");
String[] path3 = id3.split("/");
// Add a relation rel1: 2 -> 1
out = tester.POSTData("/relationships/", createRelation(path2[1], path2[2],
"affects", path1[1], path1[2], true), jetty);
String csid1 = new JSONObject(out.getContent()).getString("csid");
out = tester.GETData("/relationships/" + csid1, jetty);
JSONObject rel1 = new JSONObject(out.getContent());
assertEquals(path2[2], rel1.getJSONObject("source").getString("csid"));
assertEquals(path1[2], rel1.getJSONObject("target").getString("csid"));
// Add some more relations: rel2: 2 -> 3 ; rel 3: 3 -> 1 (new type)
out = tester.POSTData("/relationships/", createRelation(path2[1], path2[2],
"affects", path3[1], path3[2], true), jetty);
String csid2 = new JSONObject(out.getContent()).getString("csid");
out = tester.POSTData("/relationships/", createRelation(path3[1], path3[2],
"broader", path1[1], path1[2], true), jetty);
String csid3 = new JSONObject(out.getContent()).getString("csid");
// Total length should be 3 XXX pagination & offset
// out = GETData("/relationships",jetty);
// items=new JSONObject(out.getContent()).getJSONArray("items");
// assertEquals(3,items.length());
// Should be two starting at 2
out = tester.GETData("/relationships/search?source=" + path2[1] + "/"
+ path2[2], jetty);
items = new JSONObject(out.getContent()).getJSONArray("items");
assertEquals(2, items.length());
// Should be one staring at 3, none at 1
out = tester.GETData("/relationships/search?source=" + path3[1] + "/"
+ path3[2], jetty);
items = new JSONObject(out.getContent()).getJSONArray("items");
assertEquals(1, items.length());
out = tester.GETData("/relationships/search?source=" + path1[1] + "/"
+ path1[2], jetty);
items = new JSONObject(out.getContent()).getJSONArray("items");
assertEquals(0, items.length());
// Targets: two at 1, none at 2, one at 3
out = tester.GETData("/relationships/search?target=" + path1[1] + "/"
+ path1[2], jetty);
items = new JSONObject(out.getContent()).getJSONArray("items");
assertEquals(2, items.length());
out = tester.GETData("/relationships/search?target=" + path2[1] + "/"
+ path2[2], jetty);
items = new JSONObject(out.getContent()).getJSONArray("items");
assertEquals(0, items.length());
out = tester.GETData("/relationships/search?target=" + path3[1] + "/"
+ path3[2], jetty);
items = new JSONObject(out.getContent()).getJSONArray("items");
assertEquals(1, items.length());
// out=GETData("/relationships/search?type=broader",null);
// items=new JSONObject(out.getContent()).getJSONArray("items");
// assertEquals(1,items.length());
// Combination: target = 1, type = affects; just one
out = tester.GETData("/relationships/search?type=affects&target=" + path1[1]
+ "/" + path1[2], jetty);
items = new JSONObject(out.getContent()).getJSONArray("items");
assertEquals(1, items.length());
// Combination: source = 2, target = 3; just one
out = tester.GETData("/relationships/search?source=" + path2[1] + "/"
+ path2[2] + "&target=" + path3[1] + "/" + path3[2], jetty);
items = new JSONObject(out.getContent()).getJSONArray("items");
assertEquals(1, items.length());
// clean up after
tester.DELETEData("/relationships/" + csid1, jetty);
tester.DELETEData("/relationships/" + csid2, jetty);
tester.DELETEData("/relationships/" + csid3, jetty);
tester.DELETEData(id1, jetty);
tester.DELETEData(id2, jetty);
tester.DELETEData(id3, jetty);
tester.stopJetty(jetty);
}
@Test
public void testDelete() throws Exception {
// Check size of initial is empty
ServletTester jetty = tester.setupJetty();
HttpTester out = tester.GETData("/relationships/", jetty);
JSONArray itemsall = new JSONObject(out.getContent())
.getJSONArray("items");
Integer offset = itemsall.length();
// Create some cataloging
out = tester.POSTData("/intake/",
tester.makeSimpleRequest(tester.getResourceString("2007.4-a.json")), jetty);
String id1 = out.getHeader("Location");
out = tester.POSTData("/cataloging/",
tester.makeSimpleRequest(tester.getResourceString("obj3.json")), jetty);
String id2 = out.getHeader("Location");
out = tester.POSTData("/acquisition/",
tester.makeSimpleRequest(tester.getResourceString("2005.017.json")), jetty);
String id3 = out.getHeader("Location");
String[] path1 = id1.split("/");
String[] path2 = id2.split("/");
String[] path3 = id3.split("/");
// Create three relationships, one two way
out = tester.POSTData("/relationships/", createRelation(path2[1], path2[2],
"affects", path1[1], path1[2], true), jetty);
String csid2 = new JSONObject(out.getContent()).getString("csid");
out = tester.POSTData("/relationships/", createRelation(path3[1], path3[2],
"affects", path1[1], path1[2], false), jetty);
String csid = new JSONObject(out.getContent()).getString("csid");
out = tester.POSTData("/relationships/", createRelation(path3[1], path3[2],
"affects", path2[1], path2[2], false), jetty);
String csid3 = new JSONObject(out.getContent()).getString("csid");
//delete first relationship
tester.DELETEData("/relationships/" + csid2, jetty);
//delete second relationship
String path = "/relationships/0?source="+id3+"&target="+id1+"&type=affects";
tester.DELETEData(path, jetty);
//delete third relationship
JSONObject delrel = new JSONObject();
JSONObject source = new JSONObject();
JSONObject target = new JSONObject();
source.put("csid", path3[2]);
source.put("recordtype", path3[1]);
target.put("csid", path2[2]);
target.put("recordtype", path2[1]);
delrel.put("source", source);
delrel.put("target", target);
delrel.put("type", "affects");
delrel.put("one-way", "false");
tester.DELETEData("/relationships/0", jetty, delrel.toString());
tester.DELETEData(id1, jetty);
tester.DELETEData(id2, jetty);
tester.DELETEData(id3, jetty);
tester.stopJetty(jetty);
}
// XXX DELETE RELATIONS WHEN RECORD IS DELETED: NOT FOR 0.5
}
| nojira - remove redundant test
| tomcat-main/src/test/java/org/collectionspace/chain/csp/persistence/services/relation/TestRelationsThroughWebapp.java | nojira - remove redundant test |
|
Java | apache-2.0 | f748459b1c14d19cc811fbf3c525154fba44949b | 0 | ricepanda/rice-git2,ricepanda/rice-git3,ricepanda/rice-git3,ricepanda/rice-git3,ricepanda/rice-git3,kuali/rice-playground,ricepanda/rice-git2,ricepanda/rice-git2,kuali/rice-playground,ricepanda/rice-git2,kuali/rice-playground,kuali/rice-playground | /**
* Copyright 2005-2013 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.rice.krad.demo.uif.library.elements;
import org.junit.Test;
import org.kuali.rice.testtools.selenium.WebDriverLegacyITBase;
/**
* @author Kuali Rice Team ([email protected])
*/
public class DemoElementsHeaderAft extends WebDriverLegacyITBase {
/**
* /kr-krad/kradsampleapp?viewId=Demo-Header-View&methodToCall=start
*/
public static final String BOOKMARK_URL = "/kr-krad/kradsampleapp?viewId=Demo-HeaderView";
@Override
protected String getBookmarkUrl() {
return BOOKMARK_URL;
}
@Override
protected void navigate() throws Exception {
waitAndClickById("Demo-LibraryLink", "");
waitAndClickByLinkText("Elements");
waitAndClickByLinkText("Header");
}
protected void testLibraryElementsHeaderBaseHeader() throws Exception {
assertElementPresentByXpath("//div[@data-header_for='Demo-Header-Example1']/h3/span");
}
protected void testLibraryElementsHeader1() throws Exception {
waitAndClickByLinkText("Header 1");
assertElementPresentByXpath("//h1/span");
}
protected void testLibraryElementsHeader2() throws Exception {
waitAndClickByLinkText("Header 2");
assertElementPresentByXpath("//div[@id='Demo-Header-Example3']/div[@class='uif-verticalBoxLayout clearfix']/div/div/h2/span");
}
protected void testLibraryElementsHeader3() throws Exception {
waitAndClickByLinkText("Header 3");
assertElementPresentByXpath("//div[@id='Demo-Header-Example4']/div[@class='uif-verticalBoxLayout clearfix']/div/div/h3/span");
}
protected void testLibraryElementsHeader4() throws Exception {
waitAndClickByLinkText("Header 4");
assertElementPresentByXpath("//div[@id='Demo-Header-Example5']/div[@class='uif-verticalBoxLayout clearfix']/div/div/h4/span");
}
protected void testLibraryElementsHeader5() throws Exception {
waitAndClickByLinkText("Header 5");
assertElementPresentByXpath("//div[@id='Demo-Header-Example6']/div[@class='uif-verticalBoxLayout clearfix']/div/div/h5/span");
}
protected void testLibraryElementsHeader6() throws Exception {
waitAndClickByLinkText("Header 6");
assertElementPresentByXpath("//div[@id='Demo-Header-Example7']/div[@class='uif-verticalBoxLayout clearfix']/div/div/h6/span");
}
protected void testLibraryElementsHeaderEditableHeader() throws Exception {
waitAndClickByLinkText("EditablePage Header");
assertElementPresentByXpath("//div[@id='Demo-Header-Example12']/div[@class='uif-verticalBoxLayout clearfix']/div/div/h2/span");
assertElementPresentByXpath("//div[@id='Demo-Header-Example12']/div[@class='uif-verticalBoxLayout clearfix']/div/div[@class='uif-verticalBoxGroup uif-header-lowerGroup']/div[@class='uif-verticalBoxLayout clearfix']/div[1]/div/button[@class='btn btn-default btn-sm uif-expandDisclosuresButton uif-boxLayoutHorizontalItem']");
assertElementPresentByXpath("//div[@id='Demo-Header-Example12']/div[@class='uif-verticalBoxLayout clearfix']/div/div[@class='uif-verticalBoxGroup uif-header-lowerGroup']/div[@class='uif-verticalBoxLayout clearfix']/div[1]/div/button[@class='btn btn-default btn-sm uif-collapseDisclosuresButton uif-boxLayoutHorizontalItem']");
assertElementPresentByXpath("//div[@id='Demo-Header-Example12']/div[@class='uif-verticalBoxLayout clearfix']/div/div[@class='uif-verticalBoxGroup uif-header-lowerGroup']/div[@class='uif-verticalBoxLayout clearfix']/div[2]/div/span[@class='uif-requiredInstructionsMessage uif-boxLayoutHorizontalItem']");
}
protected void testLibraryElementsHeaderDisclosureHeader() throws Exception {
waitAndClickByLinkText("Disclosure Header");
assertElementPresentByXpath("//div[@id='Demo-Header-Example13']/div[@class='uif-verticalBoxLayout clearfix']/div/div/h2/span");
}
protected void testLibraryElementsHeaderImageCaptionHeader() throws Exception {
waitAndClickByLinkText("ImageCaption Header");
assertElementPresentByXpath("//div[@id='Demo-Header-Example14']/div[@class='uif-verticalBoxLayout clearfix']/div/div/h4/span");
}
protected void testLibraryElementsHeaderGroupsHeader() throws Exception {
waitAndClickByLinkText("Header Groups");
assertElementPresentByXpath("//div[@id='Demo-Header-Example15']/div[@class='uif-verticalBoxLayout clearfix']/div/div/div[1]/div[@class='uif-horizontalBoxLayout clearfix']/span");
assertElementPresentByXpath("//div[@id='Demo-Header-Example15']/div[@class='uif-verticalBoxLayout clearfix']/div/div/div[2]/h3");
assertElementPresentByXpath("//div[@id='Demo-Header-Example15']/div[@class='uif-verticalBoxLayout clearfix']/div/div/div[3]/div[@class='uif-horizontalBoxLayout clearfix']/span");
}
private void testAllHeaders() throws Exception {
testLibraryElementsHeaderBaseHeader();
testLibraryElementsHeader1();
testLibraryElementsHeader2();
testLibraryElementsHeader3();
testLibraryElementsHeader4();
testLibraryElementsHeader5();
testLibraryElementsHeader6();
testLibraryElementsHeaderEditableHeader();
testLibraryElementsHeaderDisclosureHeader();
testLibraryElementsHeaderImageCaptionHeader();
testLibraryElementsHeaderGroupsHeader();
passed();
}
@Test
public void testElementsHeaderNav() throws Exception {
testAllHeaders();
passed();
}
@Test
public void testElementsHeaderBookmark() throws Exception {
testAllHeaders();
passed();
}
}
| rice-framework/krad-sampleapp/web/src/it/java/org/kuali/rice/krad/demo/uif/library/elements/DemoElementsHeaderAft.java | /**
* Copyright 2005-2013 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.rice.krad.demo.uif.library.elements;
import org.junit.Test;
import org.kuali.rice.testtools.selenium.WebDriverLegacyITBase;
/**
* @author Kuali Rice Team ([email protected])
*/
public class DemoElementsHeaderAft extends WebDriverLegacyITBase {
/**
* /kr-krad/kradsampleapp?viewId=Demo-Header-View&methodToCall=start
*/
public static final String BOOKMARK_URL = "/kr-krad/kradsampleapp?viewId=Demo-Header-View&methodToCall=start";
@Override
protected String getBookmarkUrl() {
return BOOKMARK_URL;
}
@Override
protected void navigate() throws Exception {
waitAndClickById("Demo-LibraryLink", "");
waitAndClickByLinkText("Elements");
waitAndClickByLinkText("Header");
}
protected void testLibraryElementsHeaderBaseHeader() throws Exception {
assertElementPresentByXpath("//div[@data-header_for='Demo-Header-Example1']/h3/span");
}
protected void testLibraryElementsHeader1() throws Exception {
waitAndClickByLinkText("Header 1");
assertElementPresentByXpath("//h1/span");
}
protected void testLibraryElementsHeader2() throws Exception {
waitAndClickByLinkText("Header 2");
assertElementPresentByXpath("//div[@id='Demo-Header-Example3']/div[@class='uif-verticalBoxLayout clearfix']/div/div/h2/span");
}
protected void testLibraryElementsHeader3() throws Exception {
waitAndClickByLinkText("Header 3");
assertElementPresentByXpath("//div[@id='Demo-Header-Example4']/div[@class='uif-verticalBoxLayout clearfix']/div/div/h3/span");
}
protected void testLibraryElementsHeader4() throws Exception {
waitAndClickByLinkText("Header 4");
assertElementPresentByXpath("//div[@id='Demo-Header-Example5']/div[@class='uif-verticalBoxLayout clearfix']/div/div/h4/span");
}
protected void testLibraryElementsHeader5() throws Exception {
waitAndClickByLinkText("Header 5");
assertElementPresentByXpath("//div[@id='Demo-Header-Example6']/div[@class='uif-verticalBoxLayout clearfix']/div/div/h5/span");
}
protected void testLibraryElementsHeader6() throws Exception {
waitAndClickByLinkText("Header 6");
assertElementPresentByXpath("//div[@id='Demo-Header-Example7']/div[@class='uif-verticalBoxLayout clearfix']/div/div/h6/span");
}
protected void testLibraryElementsHeaderEditableHeader() throws Exception {
waitAndClickByLinkText("EditablePage Header");
assertElementPresentByXpath("//div[@id='Demo-Header-Example12']/div[@class='uif-verticalBoxLayout clearfix']/div/div/h2/span");
assertElementPresentByXpath("//div[@id='Demo-Header-Example12']/div[@class='uif-verticalBoxLayout clearfix']/div/div[@class='uif-verticalBoxGroup uif-header-lowerGroup']/div[@class='uif-verticalBoxLayout clearfix']/div[1]/div/button[@class='btn btn-default btn-sm uif-expandDisclosuresButton uif-boxLayoutHorizontalItem']");
assertElementPresentByXpath("//div[@id='Demo-Header-Example12']/div[@class='uif-verticalBoxLayout clearfix']/div/div[@class='uif-verticalBoxGroup uif-header-lowerGroup']/div[@class='uif-verticalBoxLayout clearfix']/div[1]/div/button[@class='btn btn-default btn-sm uif-collapseDisclosuresButton uif-boxLayoutHorizontalItem']");
assertElementPresentByXpath("//div[@id='Demo-Header-Example12']/div[@class='uif-verticalBoxLayout clearfix']/div/div[@class='uif-verticalBoxGroup uif-header-lowerGroup']/div[@class='uif-verticalBoxLayout clearfix']/div[2]/div/span[@class='uif-requiredInstructionsMessage uif-boxLayoutHorizontalItem']");
}
protected void testLibraryElementsHeaderImageCaptionHeader() throws Exception {
waitAndClickByLinkText("ImageCaption Header");
assertElementPresentByXpath("//div[@id='Demo-Header-Example14']/div[@class='uif-verticalBoxLayout clearfix']/div/div/h4/span");
}
protected void testLibraryElementsHeaderGroupsHeader() throws Exception {
waitAndClickByLinkText("Header Groups");
assertElementPresentByXpath("//div[@id='Demo-Header-Example15']/div[@class='uif-verticalBoxLayout clearfix']/div/div/div[1]/div[@class='uif-horizontalBoxLayout clearfix']/span");
assertElementPresentByXpath("//div[@id='Demo-Header-Example15']/div[@class='uif-verticalBoxLayout clearfix']/div/div/div[2]/h3");
assertElementPresentByXpath("//div[@id='Demo-Header-Example15']/div[@class='uif-verticalBoxLayout clearfix']/div/div/div[3]/div[@class='uif-horizontalBoxLayout clearfix']/span");
}
private void testAllHeaders() throws Exception {
testLibraryElementsHeaderBaseHeader();
testLibraryElementsHeader1();
testLibraryElementsHeader2();
testLibraryElementsHeader3();
testLibraryElementsHeader4();
testLibraryElementsHeader5();
testLibraryElementsHeader6();
testLibraryElementsHeaderEditableHeader();
testLibraryElementsHeaderImageCaptionHeader();
testLibraryElementsHeaderGroupsHeader();
passed();
}
@Test
public void testElementsHeaderNav() throws Exception {
testAllHeaders();
passed();
}
}
| KULRICE-11233 : Fill AFT Per-Screen Item Gap: KRAD Library: Header - Added code.
git-svn-id: 2a5d2b5a02908a0c4ba7967b726d8c4198d1b9ed@43254 7a7aa7f6-c479-11dc-97e2-85a2497f191d
| rice-framework/krad-sampleapp/web/src/it/java/org/kuali/rice/krad/demo/uif/library/elements/DemoElementsHeaderAft.java | KULRICE-11233 : Fill AFT Per-Screen Item Gap: KRAD Library: Header - Added code. |
|
Java | apache-2.0 | 6f655aed3b83899163740c98bac8d4919d65cde3 | 0 | apurtell/hadoop,littlezhou/hadoop,lukmajercak/hadoop,dierobotsdie/hadoop,GeLiXin/hadoop,apurtell/hadoop,apache/hadoop,GeLiXin/hadoop,apache/hadoop,xiao-chen/hadoop,littlezhou/hadoop,apache/hadoop,lukmajercak/hadoop,lukmajercak/hadoop,apache/hadoop,littlezhou/hadoop,xiao-chen/hadoop,plusplusjiajia/hadoop,JingchengDu/hadoop,nandakumar131/hadoop,mapr/hadoop-common,GeLiXin/hadoop,xiao-chen/hadoop,GeLiXin/hadoop,nandakumar131/hadoop,szegedim/hadoop,GeLiXin/hadoop,nandakumar131/hadoop,dierobotsdie/hadoop,steveloughran/hadoop,steveloughran/hadoop,mapr/hadoop-common,plusplusjiajia/hadoop,lukmajercak/hadoop,wwjiang007/hadoop,littlezhou/hadoop,dierobotsdie/hadoop,apache/hadoop,steveloughran/hadoop,ucare-uchicago/hadoop,wwjiang007/hadoop,szegedim/hadoop,xiao-chen/hadoop,dierobotsdie/hadoop,lukmajercak/hadoop,littlezhou/hadoop,steveloughran/hadoop,mapr/hadoop-common,ucare-uchicago/hadoop,steveloughran/hadoop,xiao-chen/hadoop,JingchengDu/hadoop,JingchengDu/hadoop,ucare-uchicago/hadoop,ucare-uchicago/hadoop,apurtell/hadoop,apache/hadoop,JingchengDu/hadoop,plusplusjiajia/hadoop,dierobotsdie/hadoop,apurtell/hadoop,dierobotsdie/hadoop,apurtell/hadoop,GeLiXin/hadoop,JingchengDu/hadoop,apurtell/hadoop,plusplusjiajia/hadoop,plusplusjiajia/hadoop,xiao-chen/hadoop,apache/hadoop,dierobotsdie/hadoop,nandakumar131/hadoop,apurtell/hadoop,JingchengDu/hadoop,mapr/hadoop-common,wwjiang007/hadoop,wwjiang007/hadoop,ucare-uchicago/hadoop,nandakumar131/hadoop,ucare-uchicago/hadoop,littlezhou/hadoop,nandakumar131/hadoop,wwjiang007/hadoop,nandakumar131/hadoop,plusplusjiajia/hadoop,szegedim/hadoop,ucare-uchicago/hadoop,wwjiang007/hadoop,GeLiXin/hadoop,xiao-chen/hadoop,lukmajercak/hadoop,littlezhou/hadoop,plusplusjiajia/hadoop,mapr/hadoop-common,JingchengDu/hadoop,steveloughran/hadoop,szegedim/hadoop,wwjiang007/hadoop,lukmajercak/hadoop,steveloughran/hadoop,szegedim/hadoop,szegedim/hadoop,szegedim/hadoop,mapr/hadoop-common,mapr/hadoop-common | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.server.protocol;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.util.Time;
/**
* This class is helper class to generate a live usage report by calculating
* the delta between current DataNode usage metrics and the usage metrics
* captured at the time of the last report.
*/
@InterfaceAudience.Private
@InterfaceStability.Unstable
public final class DataNodeUsageReportUtil {
private long bytesWritten;
private long bytesRead;
private long writeTime;
private long readTime;
private long blocksWritten;
private long blocksRead;
private DataNodeUsageReport lastReport;
public DataNodeUsageReport getUsageReport(long bWritten, long
bRead, long wTime, long rTime, long wBlockOp, long
rBlockOp, long timeSinceLastReport) {
if (timeSinceLastReport == 0) {
if (lastReport == null) {
lastReport = DataNodeUsageReport.EMPTY_REPORT;
}
return lastReport;
}
DataNodeUsageReport.Builder builder = new DataNodeUsageReport.Builder();
DataNodeUsageReport report = builder.setBytesWrittenPerSec(
getBytesWrittenPerSec(bWritten, timeSinceLastReport))
.setBytesReadPerSec(getBytesReadPerSec(bRead, timeSinceLastReport))
.setWriteTime(getWriteTime(wTime))
.setReadTime(getReadTime(rTime)).setBlocksWrittenPerSec(
getWriteBlockOpPerSec(wBlockOp, timeSinceLastReport))
.setBlocksReadPerSec(
getReadBlockOpPerSec(rBlockOp, timeSinceLastReport))
.setTimestamp(Time.monotonicNow()).build();
// Save raw metrics
this.bytesRead = bRead;
this.bytesWritten = bWritten;
this.blocksWritten = wBlockOp;
this.blocksRead = rBlockOp;
this.readTime = rTime;
this.writeTime = wTime;
lastReport = report;
return report;
}
private long getBytesReadPerSec(long bRead, long
timeInSec) {
return (bRead - this.bytesRead) / timeInSec;
}
private long getBytesWrittenPerSec(long
bWritten, long timeInSec) {
return (bWritten - this.bytesWritten) / timeInSec;
}
private long getWriteBlockOpPerSec(
long totalWriteBlocks, long timeInSec) {
return (totalWriteBlocks - this.blocksWritten) / timeInSec;
}
private long getReadBlockOpPerSec(long totalReadBlockOp,
long timeInSec) {
return (totalReadBlockOp - this.blocksRead) / timeInSec;
}
private long getReadTime(long totalReadTime) {
return totalReadTime - this.readTime;
}
private long getWriteTime(long totalWriteTime) {
return totalWriteTime - this.writeTime;
}
}
| hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/server/protocol/DataNodeUsageReportUtil.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.server.protocol;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.util.Time;
/**
* This class is helper class to generate a live usage report by calculating
* the delta between current DataNode usage metrics and the usage metrics
* captured at the time of the last report.
*/
@InterfaceAudience.Private
@InterfaceStability.Unstable
public final class DataNodeUsageReportUtil {
private long bytesWritten;
private long bytesRead;
private long writeTime;
private long readTime;
private long blocksWritten;
private long blocksRead;
private DataNodeUsageReport lastReport;
public DataNodeUsageReport getUsageReport(long bWritten, long
bRead, long wTime, long rTime, long wBlockOp, long
rBlockOp, long timeSinceLastReport) {
if (timeSinceLastReport == 0) {
if (lastReport == null) {
lastReport = DataNodeUsageReport.EMPTY_REPORT;
}
return lastReport;
}
DataNodeUsageReport.Builder builder = new DataNodeUsageReport.Builder();
DataNodeUsageReport report = builder.setBytesWrittenPerSec(
getBytesWrittenPerSec(bWritten, timeSinceLastReport))
.setBytesReadPerSec(getBytesReadPerSec(bRead, timeSinceLastReport))
.setWriteTime(getWriteTime(wTime))
.setReadTime(getReadTime(rTime)).setBlocksWrittenPerSec(
getWriteBlockOpPerSec(wBlockOp, timeSinceLastReport))
.setBlocksReadPerSec(
getReadBlockOpPerSec(rBlockOp, timeSinceLastReport))
.setTimestamp(Time.monotonicNow()).build();
// Save raw metrics
this.bytesRead = bRead;
this.bytesWritten = bWritten;
this.blocksWritten = wBlockOp;
this.blocksRead = rBlockOp;
this.readTime = rTime;
this.writeTime = wTime;
lastReport = report;
return report;
}
private long getBytesReadPerSec(long bRead, long
timeInSec) {
return (bRead - this.bytesRead) / timeInSec;
}
private long getBytesWrittenPerSec(long
bWritten, long timeInSec) {
return (bWritten - this.bytesWritten) / timeInSec;
}
private long getWriteBlockOpPerSec(
long totalWriteBlocks, long timeInSec) {
return (totalWriteBlocks - this.blocksWritten) / timeInSec;
}
private long getReadBlockOpPerSec(long totalReadBlockOp,
long timeInSec) {
return (totalReadBlockOp - this.blocksRead) / timeInSec;
}
private long getReadTime(long totalReadTime) {
return totalReadTime - this.readTime;
}
private long getWriteTime(long totalWriteTime) {
return totalWriteTime - this.writeTime;
}
}
| HADOOP-15404. Remove multibyte characters in DataNodeUsageReportUtil
Signed-off-by: Akira Ajisaka <[email protected]>
| hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/server/protocol/DataNodeUsageReportUtil.java | HADOOP-15404. Remove multibyte characters in DataNodeUsageReportUtil |
|
Java | bsd-2-clause | ba5529956746748687d4bc128aabdb09de813648 | 0 | scifio/scifio | //
// SwingUtil.java
//
/*
VisBio application for visualization of multidimensional
biological image data. Copyright (C) 2002-2005 Curtis Rueden.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.visbio.util;
import java.awt.*;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.CharArrayWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.util.Enumeration;
import java.util.Vector;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import visad.util.*;
/** SwingUtil contains useful Swing functions. */
public abstract class SwingUtil {
/** Constructs a JButton with an icon from the given file id. */
public static JButton makeButton(Object owner, String id,
String altText, int wpad, int hpad)
{
URL url = owner.getClass().getResource(id);
ImageIcon icon = null;
if (url != null) icon = new ImageIcon(url);
JButton button;
if (icon == null) button = new JButton(altText);
else {
button = new JButton(icon);
button.setPreferredSize(new Dimension(
icon.getIconWidth() + wpad, icon.getIconHeight() + hpad));
}
return button;
}
/** Constructs a JToggleButton with an icon from the given file id. */
public static JToggleButton makeToggleButton(Object owner,
String id, String altText, int wpad, int hpad)
{
URL url = owner.getClass().getResource(id);
ImageIcon icon = null;
if (url != null) icon = new ImageIcon(url);
JToggleButton button;
if (icon == null) button = new JToggleButton(altText);
else {
button = new JToggleButton(icon);
button.setPreferredSize(new Dimension(
icon.getIconWidth() + wpad, icon.getIconHeight() + hpad));
}
return button;
}
/** Fully expands the given JTree from the specified node. */
public static void expandTree(JTree tree, DefaultMutableTreeNode node) {
if (node.isLeaf()) return;
tree.expandPath(new TreePath(node.getPath()));
Enumeration e = node.children();
while (e.hasMoreElements()) {
expandTree(tree, (DefaultMutableTreeNode) e.nextElement());
}
}
/**
* Toggles the cursor for the given component and all child components
* between the wait cursor and the normal one.
*/
public static void setWaitCursor(Component c, boolean wait) {
setCursor(c, wait ? Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR) : null);
}
/**
* Sets the cursor for the given component and
* all child components to the given cursor.
*/
public static void setCursor(Component c, Cursor cursor) {
c.setCursor(cursor);
if (c instanceof Container) {
Container contain = (Container) c;
Component[] sub = contain.getComponents();
for (int i=0; i<sub.length; i++) setCursor(sub[i], cursor);
}
}
/** Gets the containing window for the given component. */
public static Window getWindow(Component c) {
while (c != null) {
if (c instanceof Window) return (Window) c;
c = c.getParent();
}
return null;
}
/**
* Enlarges a window to its preferred width
* and/or height if it is too small.
*/
public static void repack(Window w) {
Dimension size = getRepackSize(w);
if (!w.getSize().equals(size)) w.setSize(size);
}
/** Gets the dimension of this window were it to be repacked. */
public static Dimension getRepackSize(Window w) {
Dimension size = w.getSize();
Dimension pref = w.getPreferredSize();
if (size.width >= pref.width && size.height >= pref.height) return size;
return new Dimension(size.width < pref.width ? pref.width : size.width,
size.height < pref.height ? pref.height : size.height);
}
/** Sets the title of the given window. */
public static void setWindowTitle(Window w, String title) {
if (w instanceof Frame) ((Frame) w).setTitle(title);
else if (w instanceof Dialog) ((Dialog) w).setTitle(title);
else w.setName(title);
}
/** Gets the title of the given window. */
public static String getWindowTitle(Window w) {
if (w instanceof Frame) return ((Frame) w).getTitle();
else if (w instanceof Dialog) return ((Dialog) w).getTitle();
else return w.getName();
}
/** Key mask for use with keyboard shortcuts on this operating system. */
public static final int MENU_MASK =
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
/** Sets the keyboard shortcut for the given menu item. */
public static void setMenuShortcut(GUIFrame frame,
String menu, String item, int keycode)
{
JMenuItem jmi = frame.getMenuItem(menu, item);
if (jmi == null) return;
jmi.setAccelerator(KeyStroke.getKeyStroke(keycode, MENU_MASK));
}
/**
* Creates a copy of this menu bar, whose contents update automatically
* whenever the original menu bar changes.
*/
public static JMenuBar cloneMenuBar(JMenuBar menubar) {
if (menubar == null) return null;
JMenuBar jmb = new JMenuBar();
int count = menubar.getMenuCount();
for (int i=0; i<count; i++) jmb.add(cloneMenuItem(menubar.getMenu(i)));
return jmb;
}
/**
* Creates a copy of this menu item, whose contents update automatically
* whenever the original menu item changes.
*/
public static JMenuItem cloneMenuItem(JMenuItem item) {
if (item == null) return null;
JMenuItem jmi;
if (item instanceof JMenu) {
JMenu menu = (JMenu) item;
JMenu jm = new JMenu();
int count = menu.getItemCount();
for (int i=0; i<count; i++) {
JMenuItem ijmi = cloneMenuItem(menu.getItem(i));
if (ijmi == null) jm.addSeparator();
else jm.add(ijmi);
}
jmi = jm;
}
else jmi = new JMenuItem();
ActionListener[] l = item.getActionListeners();
for (int i=0; i<l.length; i++) jmi.addActionListener(l[i]);
jmi.setActionCommand(item.getActionCommand());
syncMenuItem(item, jmi);
linkMenuItem(item, jmi);
return jmi;
}
/**
* Configures a scroll pane's properties to always show horizontal and
* vertical scroll bars. This method only exists to match the Macintosh
* Aqua Look and Feel as closely as possible.
*/
public static void configureScrollPane(JScrollPane scroll) {
if (!LAFUtil.isMacLookAndFeel()) return;
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
}
/** Constructs a JFileChooser that recognizes accepted VisBio file types. */
public static JFileChooser getVisBioFileChooser() {
JFileChooser dialog = new JFileChooser(System.getProperty("user.dir"));
Vector filters = new Vector();
// TIFF - tiff/TiffForm, bio/FluoviewTiffForm, ij/ImageJForm
FileFilter tiff = new ExtensionFileFilter(
new String[] {"tif", "tiff"}, "Multi-page TIFF stacks");
filters.add(tiff);
// Bio-Rad PIC - bio/BioRadForm
FileFilter biorad = new ExtensionFileFilter("pic", "Bio-Rad PIC files");
filters.add(biorad);
// Deltavision - bio/DeltavisionForm
FileFilter deltavision = new ExtensionFileFilter("dv",
"Deltavision files");
filters.add(deltavision);
// IPLab - bio/IPLabForm
FileFilter iplab = new ExtensionFileFilter("ipl", "IPLab files");
filters.add(iplab);
// Leica - bio/LeicaForm
FileFilter leica = new ExtensionFileFilter("lei", "Leica files");
filters.add(leica);
// Metamorph STK - bio/MetamorphForm
FileFilter metamorph = new ExtensionFileFilter("stk",
"Metamorph STK files");
filters.add(metamorph);
// Openlab LIFF - bio/OpenlabForm
FileFilter openlab = new OpenlabFileFilter();
filters.add(openlab);
// PerkinElmer - bio/PerkinElmerForm
FileFilter perkinElmer = new ExtensionFileFilter(new String[]
{"tim", "zpo", "csv", "htm"}, "PerkinElmer files");
filters.add(perkinElmer);
// QuickTime - qt/QTForm
FileFilter qt = new ExtensionFileFilter("mov", "QuickTime movies");
filters.add(qt);
// Zeiss LSM - bio/ZeissForm
FileFilter lsm = new ExtensionFileFilter("lsm", "Zeiss LSM files");
filters.add(lsm);
// Zeiss ZVI - bio/ZVIForm
FileFilter zvi = new ExtensionFileFilter("zvi", "Zeiss ZVI files");
filters.add(zvi);
// BMP - ij/ImageJForm
FileFilter bmp = new ExtensionFileFilter("bmp", "BMP images");
filters.add(bmp);
// DICOM - ij/ImageJForm
FileFilter dicom = new ExtensionFileFilter("dicom", "DICOM images");
filters.add(dicom);
// FITS - ij/ImageJForm
FileFilter fits = new ExtensionFileFilter("fits", "FITS images");
filters.add(fits);
// GIF - ij/ImageJForm
FileFilter gif = new ExtensionFileFilter("gif", "GIF images");
filters.add(gif);
// JPEG - ij/ImageJForm
FileFilter jpeg = new ExtensionFileFilter(
new String[] {"jpg", "jpeg", "jpe"}, "JPEG images");
filters.add(jpeg);
// PGM - ij/ImageJForm
FileFilter pgm = new ExtensionFileFilter("pgm", "PGM images");
filters.add(pgm);
// PICT - qt/PictForm
FileFilter pict = new ExtensionFileFilter("pict", "PICT images");
filters.add(pict);
// PNG - ij/ImageJForm
FileFilter png = new ExtensionFileFilter("png", "PNG images");
filters.add(png);
// combination filter
FileFilter[] ff = new FileFilter[filters.size()];
filters.copyInto(ff);
FileFilter combo = new ComboFileFilter(ff, "All VisBio file types");
// add filters to dialog
dialog.addChoosableFileFilter(combo);
dialog.addChoosableFileFilter(tiff);
dialog.addChoosableFileFilter(biorad);
dialog.addChoosableFileFilter(deltavision);
dialog.addChoosableFileFilter(iplab);
dialog.addChoosableFileFilter(leica);
dialog.addChoosableFileFilter(metamorph);
dialog.addChoosableFileFilter(openlab);
dialog.addChoosableFileFilter(perkinElmer);
dialog.addChoosableFileFilter(qt);
dialog.addChoosableFileFilter(lsm);
dialog.addChoosableFileFilter(zvi);
dialog.addChoosableFileFilter(bmp);
dialog.addChoosableFileFilter(dicom);
dialog.addChoosableFileFilter(fits);
dialog.addChoosableFileFilter(gif);
dialog.addChoosableFileFilter(jpeg);
dialog.addChoosableFileFilter(pgm);
dialog.addChoosableFileFilter(pict);
dialog.addChoosableFileFilter(png);
dialog.setFileFilter(combo);
return dialog;
}
/** Pops up a message box, blocking the current thread. */
public static void pause(String msg) {
JOptionPane.showMessageDialog(null, msg, "VisBio",
JOptionPane.PLAIN_MESSAGE);
}
/** Pops up a message box, blocking the current thread. */
public static void pause(Throwable t) {
CharArrayWriter caw = new CharArrayWriter();
t.printStackTrace(new PrintWriter(caw));
pause(caw.toString());
}
// -- Helper methods --
/**
* Forces slave menu item to reflect master menu item
* using a property change listener.
*/
protected static void linkMenuItem(JMenuItem master, JMenuItem slave) {
final JMenuItem source = master, dest = slave;
source.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent e) {
syncMenuItem(source, dest);
}
});
}
/** Brings the destination menu item into sync with the source item. */
protected static void syncMenuItem(JMenuItem source, JMenuItem dest) {
boolean enabled = source.isEnabled();
if (dest.isEnabled() != enabled) dest.setEnabled(enabled);
int mnemonic = source.getMnemonic();
if (dest.getMnemonic() != mnemonic) dest.setMnemonic(mnemonic);
String text = source.getText();
if (dest.getText() != text) dest.setText(text);
KeyStroke accel = source.getAccelerator();
if (dest.getAccelerator() != accel) dest.setAccelerator(accel);
}
}
| loci/visbio/util/SwingUtil.java | //
// SwingUtil.java
//
/*
VisBio application for visualization of multidimensional
biological image data. Copyright (C) 2002-2005 Curtis Rueden.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.visbio.util;
import java.awt.*;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.CharArrayWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.util.Enumeration;
import java.util.Vector;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import visad.util.*;
/** SwingUtil contains useful Swing functions. */
public abstract class SwingUtil {
/** Constructs a JButton with an icon from the given file id. */
public static JButton makeButton(Object owner, String id,
String altText, int wpad, int hpad)
{
URL url = owner.getClass().getResource(id);
ImageIcon icon = null;
if (url != null) icon = new ImageIcon(url);
JButton button;
if (icon == null) button = new JButton(altText);
else {
button = new JButton(icon);
button.setPreferredSize(new Dimension(
icon.getIconWidth() + wpad, icon.getIconHeight() + hpad));
}
return button;
}
/** Constructs a JToggleButton with an icon from the given file id. */
public static JToggleButton makeToggleButton(Object owner,
String id, String altText, int wpad, int hpad)
{
URL url = owner.getClass().getResource(id);
ImageIcon icon = null;
if (url != null) icon = new ImageIcon(url);
JToggleButton button;
if (icon == null) button = new JToggleButton(altText);
else {
button = new JToggleButton(icon);
button.setPreferredSize(new Dimension(
icon.getIconWidth() + wpad, icon.getIconHeight() + hpad));
}
return button;
}
/** Fully expands the given JTree from the specified node. */
public static void expandTree(JTree tree, DefaultMutableTreeNode node) {
if (node.isLeaf()) return;
tree.expandPath(new TreePath(node.getPath()));
Enumeration e = node.children();
while (e.hasMoreElements()) {
expandTree(tree, (DefaultMutableTreeNode) e.nextElement());
}
}
/**
* Toggles the cursor for the given component and all child components
* between the wait cursor and the normal one.
*/
public static void setWaitCursor(Component c, boolean wait) {
setCursor(c, wait ? Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR) : null);
}
/**
* Sets the cursor for the given component and
* all child components to the given cursor.
*/
public static void setCursor(Component c, Cursor cursor) {
c.setCursor(cursor);
if (c instanceof Container) {
Container contain = (Container) c;
Component[] sub = contain.getComponents();
for (int i=0; i<sub.length; i++) setCursor(sub[i], cursor);
}
}
/** Gets the containing window for the given component. */
public static Window getWindow(Component c) {
while (c != null) {
if (c instanceof Window) return (Window) c;
c = c.getParent();
}
return null;
}
/**
* Enlarges a window to its preferred width
* and/or height if it is too small.
*/
public static void repack(Window w) {
Dimension size = getRepackSize(w);
if (!w.getSize().equals(size)) w.setSize(size);
}
/** Gets the dimension of this window were it to be repacked. */
public static Dimension getRepackSize(Window w) {
Dimension size = w.getSize();
Dimension pref = w.getPreferredSize();
if (size.width >= pref.width && size.height >= pref.height) return size;
return new Dimension(size.width < pref.width ? pref.width : size.width,
size.height < pref.height ? pref.height : size.height);
}
/** Sets the title of the given window. */
public static void setWindowTitle(Window w, String title) {
if (w instanceof Frame) ((Frame) w).setTitle(title);
else if (w instanceof Dialog) ((Dialog) w).setTitle(title);
else w.setName(title);
}
/** Gets the title of the given window. */
public static String getWindowTitle(Window w) {
if (w instanceof Frame) return ((Frame) w).getTitle();
else if (w instanceof Dialog) return ((Dialog) w).getTitle();
else return w.getName();
}
/** Key mask for use with keyboard shortcuts on this operating system. */
public static final int MENU_MASK =
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
/** Sets the keyboard shortcut for the given menu item. */
public static void setMenuShortcut(GUIFrame frame,
String menu, String item, int keycode)
{
JMenuItem jmi = frame.getMenuItem(menu, item);
if (jmi == null) return;
jmi.setAccelerator(KeyStroke.getKeyStroke(keycode, MENU_MASK));
}
/**
* Creates a copy of this menu bar, whose contents update automatically
* whenever the original menu bar changes.
*/
public static JMenuBar cloneMenuBar(JMenuBar menubar) {
if (menubar == null) return null;
JMenuBar jmb = new JMenuBar();
int count = menubar.getMenuCount();
for (int i=0; i<count; i++) jmb.add(cloneMenuItem(menubar.getMenu(i)));
return jmb;
}
/**
* Creates a copy of this menu item, whose contents update automatically
* whenever the original menu item changes.
*/
public static JMenuItem cloneMenuItem(JMenuItem item) {
if (item == null) return null;
JMenuItem jmi;
if (item instanceof JMenu) {
JMenu menu = (JMenu) item;
JMenu jm = new JMenu();
int count = menu.getItemCount();
for (int i=0; i<count; i++) {
JMenuItem ijmi = cloneMenuItem(menu.getItem(i));
if (ijmi == null) jm.addSeparator();
else jm.add(ijmi);
}
jmi = jm;
}
else jmi = new JMenuItem();
ActionListener[] l = item.getActionListeners();
for (int i=0; i<l.length; i++) jmi.addActionListener(l[i]);
jmi.setActionCommand(item.getActionCommand());
syncMenuItem(item, jmi);
linkMenuItem(item, jmi);
return jmi;
}
/**
* Configures a scroll pane's properties to always show horizontal and
* vertical scroll bars. This method only exists to match the Macintosh
* Aqua Look and Feel as closely as possible.
*/
public static void configureScrollPane(JScrollPane scroll) {
if (!LAFUtil.isMacLookAndFeel()) return;
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
}
/** Constructs a JFileChooser that recognizes accepted VisBio file types. */
public static JFileChooser getVisBioFileChooser() {
JFileChooser dialog = new JFileChooser(System.getProperty("user.dir"));
Vector filters = new Vector();
// TIFF - tiff/TiffForm, bio/FluoviewTiffForm, ij/ImageJForm
FileFilter tiff = new ExtensionFileFilter(
new String[] {"tif", "tiff"}, "Multi-page TIFF stacks");
filters.add(tiff);
// Bio-Rad PIC - bio/BioRadForm
FileFilter biorad = new ExtensionFileFilter("pic", "Bio-Rad PIC files");
filters.add(biorad);
// Deltavision - bio/DeltavisionForm
FileFilter deltavision = new ExtensionFileFilter("dv",
"Deltavision files");
filters.add(deltavision);
// IPLab - bio/IPLabForm
FileFilter iplab = new ExtensionFileFilter("ipl", "IPLab files");
filters.add(iplab);
// Leica - bio/LeicaForm
FileFilter leica = new ExtensionFileFilter("lei", "Leica files");
filters.add(leica);
// Metamorph STK - bio/MetamorphForm
FileFilter metamorph = new ExtensionFileFilter("stk",
"Metamorph STK files");
filters.add(metamorph);
// Openlab LIFF - bio/OpenlabForm
FileFilter openlab = new OpenlabFileFilter();
filters.add(openlab);
// PerkinElmer - bio/PerkinElmerForm
FileFilter perkinElmer = new ExtensionFileFilter(new String[]
{"tim", "zpo", "csv", "htm"}, "PerkinElmer files");
filters.add(perkinElmer);
// QuickTime - qt/QTForm
FileFilter qt = new ExtensionFileFilter("mov", "QuickTime movies");
filters.add(qt);
// Zeiss LSM - bio/ZeissForm
FileFilter lsm = new ExtensionFileFilter("lsm", "Zeiss LSM files");
filters.add(lsm);
// Zeiss ZVI - bio/ZVIForm
FileFilter zvi = new ExtensionFileFilter("zvi", "Zeiss ZVI files");
filters.add(zvi);
// BMP - ij/ImageJForm
FileFilter bmp = new ExtensionFileFilter("bmp", "BMP images");
filters.add(bmp);
// DICOM - ij/ImageJForm
FileFilter dicom = new ExtensionFileFilter("dicom", "DICOM images");
filters.add(dicom);
// FITS - ij/ImageJForm
FileFilter fits = new ExtensionFileFilter("fits", "FITS images");
filters.add(fits);
// GIF - ij/ImageJForm
FileFilter gif = new ExtensionFileFilter("gif", "GIF images");
filters.add(gif);
// JPEG - ij/ImageJForm
FileFilter jpeg = new ExtensionFileFilter(
new String[] {"jpg", "jpeg", "jpe"}, "JPEG images");
filters.add(jpeg);
// PGM - ij/ImageJForm
FileFilter pgm = new ExtensionFileFilter("pgm", "PGM images");
filters.add(pgm);
// PICT - qt/PictForm
FileFilter pict = new ExtensionFileFilter("pict", "PICT images");
filters.add(pict);
// PNG - ij/ImageJForm
FileFilter png = new ExtensionFileFilter("png", "PNG images");
filters.add(png);
// combination filter
FileFilter[] ff = new FileFilter[filters.size()];
filters.copyInto(ff);
FileFilter combo = new ComboFileFilter(ff, "All VisBio file types");
// add filters to dialog
dialog.addChoosableFileFilter(combo);
dialog.addChoosableFileFilter(tiff);
dialog.addChoosableFileFilter(biorad);
dialog.addChoosableFileFilter(deltavision);
dialog.addChoosableFileFilter(iplab);
dialog.addChoosableFileFilter(leica);
dialog.addChoosableFileFilter(metamorph);
dialog.addChoosableFileFilter(openlab);
dialog.addChoosableFileFilter(perkinElmer);
dialog.addChoosableFileFilter(qt);
dialog.addChoosableFileFilter(lsm);
dialog.addChoosableFileFilter(zvi);
dialog.addChoosableFileFilter(bmp);
dialog.addChoosableFileFilter(dicom);
dialog.addChoosableFileFilter(fits);
dialog.addChoosableFileFilter(gif);
dialog.addChoosableFileFilter(jpeg);
dialog.addChoosableFileFilter(pgm);
dialog.addChoosableFileFilter(pict);
dialog.addChoosableFileFilter(png);
return dialog;
}
/** Pops up a message box, blocking the current thread. */
public static void pause(String msg) {
JOptionPane.showMessageDialog(null, msg, "VisBio",
JOptionPane.PLAIN_MESSAGE);
}
/** Pops up a message box, blocking the current thread. */
public static void pause(Throwable t) {
CharArrayWriter caw = new CharArrayWriter();
t.printStackTrace(new PrintWriter(caw));
pause(caw.toString());
}
// -- Helper methods --
/**
* Forces slave menu item to reflect master menu item
* using a property change listener.
*/
protected static void linkMenuItem(JMenuItem master, JMenuItem slave) {
final JMenuItem source = master, dest = slave;
source.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent e) {
syncMenuItem(source, dest);
}
});
}
/** Brings the destination menu item into sync with the source item. */
protected static void syncMenuItem(JMenuItem source, JMenuItem dest) {
boolean enabled = source.isEnabled();
if (dest.isEnabled() != enabled) dest.setEnabled(enabled);
int mnemonic = source.getMnemonic();
if (dest.getMnemonic() != mnemonic) dest.setMnemonic(mnemonic);
String text = source.getText();
if (dest.getText() != text) dest.setText(text);
KeyStroke accel = source.getAccelerator();
if (dest.getAccelerator() != accel) dest.setAccelerator(accel);
}
}
| Default to "All VisBio file types" filter.
| loci/visbio/util/SwingUtil.java | Default to "All VisBio file types" filter. |
|
Java | bsd-3-clause | 2198203ddb4e474e9ae7e8dbd46b19f75bae83fd | 0 | pandiaraj44/react-native,exponent/react-native,exponent/react-native,myntra/react-native,pandiaraj44/react-native,exponentjs/react-native,janicduplessis/react-native,exponent/react-native,javache/react-native,pandiaraj44/react-native,hoangpham95/react-native,javache/react-native,javache/react-native,hoangpham95/react-native,hoangpham95/react-native,javache/react-native,facebook/react-native,facebook/react-native,pandiaraj44/react-native,hoangpham95/react-native,javache/react-native,myntra/react-native,janicduplessis/react-native,myntra/react-native,janicduplessis/react-native,exponentjs/react-native,hammerandchisel/react-native,myntra/react-native,exponent/react-native,hammerandchisel/react-native,facebook/react-native,hoangpham95/react-native,exponentjs/react-native,pandiaraj44/react-native,arthuralee/react-native,hammerandchisel/react-native,facebook/react-native,exponentjs/react-native,myntra/react-native,exponentjs/react-native,pandiaraj44/react-native,exponent/react-native,pandiaraj44/react-native,myntra/react-native,exponent/react-native,hoangpham95/react-native,hammerandchisel/react-native,janicduplessis/react-native,javache/react-native,facebook/react-native,arthuralee/react-native,pandiaraj44/react-native,exponentjs/react-native,exponentjs/react-native,janicduplessis/react-native,arthuralee/react-native,javache/react-native,facebook/react-native,arthuralee/react-native,javache/react-native,hammerandchisel/react-native,janicduplessis/react-native,hammerandchisel/react-native,hoangpham95/react-native,exponentjs/react-native,janicduplessis/react-native,facebook/react-native,facebook/react-native,myntra/react-native,exponent/react-native,myntra/react-native,arthuralee/react-native,facebook/react-native,myntra/react-native,hammerandchisel/react-native,janicduplessis/react-native,exponent/react-native,javache/react-native,hammerandchisel/react-native,hoangpham95/react-native | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.modules.core;
import com.facebook.common.logging.FLog;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.BaseJavaModule;
import com.facebook.react.bridge.JavaOnlyMap;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.common.JavascriptException;
import com.facebook.react.common.ReactConstants;
import com.facebook.react.devsupport.interfaces.DevSupportManager;
import com.facebook.react.module.annotations.ReactModule;
import com.facebook.react.util.ExceptionDataHelper;
import com.facebook.react.util.JSStackTrace;
@ReactModule(name = ExceptionsManagerModule.NAME)
public class ExceptionsManagerModule extends BaseJavaModule {
public static final String NAME = "ExceptionsManager";
private final DevSupportManager mDevSupportManager;
public ExceptionsManagerModule(DevSupportManager devSupportManager) {
mDevSupportManager = devSupportManager;
}
@Override
public String getName() {
return NAME;
}
@ReactMethod
public void reportFatalException(String message, ReadableArray stack, int id) {
JavaOnlyMap data = new JavaOnlyMap();
data.putString("message", message);
data.putArray("stack", stack);
data.putInt("id", id);
data.putBoolean("isFatal", true);
reportException(data);
}
@ReactMethod
public void reportSoftException(String message, ReadableArray stack, int id) {
JavaOnlyMap data = new JavaOnlyMap();
data.putString("message", message);
data.putArray("stack", stack);
data.putInt("id", id);
data.putBoolean("isFatal", false);
reportException(data);
}
@ReactMethod
public void reportException(ReadableMap data) {
String message = data.hasKey("message") ? data.getString("message") : "";
ReadableArray stack = data.hasKey("stack") ? data.getArray("stack") : Arguments.createArray();
int id = data.hasKey("id") ? data.getInt("id") : -1;
boolean isFatal = data.hasKey("isFatal") ? data.getBoolean("isFatal") : false;
if (mDevSupportManager.getDevSupportEnabled()) {
mDevSupportManager.showNewJSError(message, stack, id);
} else {
String extraDataAsJson = ExceptionDataHelper.getExtraDataAsJson(data);
if (isFatal) {
throw new JavascriptException(JSStackTrace.format(message, stack))
.setExtraDataAsJson(extraDataAsJson);
} else {
FLog.e(ReactConstants.TAG, JSStackTrace.format(message, stack));
if (extraDataAsJson != null) {
FLog.d(ReactConstants.TAG, "extraData: %s", extraDataAsJson);
}
}
}
}
@ReactMethod
public void updateExceptionMessage(String title, ReadableArray details, int exceptionId) {
if (mDevSupportManager.getDevSupportEnabled()) {
mDevSupportManager.updateJSError(title, details, exceptionId);
}
}
@ReactMethod
public void dismissRedbox() {
if (mDevSupportManager.getDevSupportEnabled()) {
mDevSupportManager.hideRedboxDialog();
}
}
}
| ReactAndroid/src/main/java/com/facebook/react/modules/core/ExceptionsManagerModule.java | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.facebook.react.modules.core;
import com.facebook.common.logging.FLog;
import com.facebook.react.bridge.BaseJavaModule;
import com.facebook.react.bridge.JavaOnlyMap;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.common.JavascriptException;
import com.facebook.react.common.ReactConstants;
import com.facebook.react.devsupport.interfaces.DevSupportManager;
import com.facebook.react.module.annotations.ReactModule;
import com.facebook.react.util.ExceptionDataHelper;
import com.facebook.react.util.JSStackTrace;
@ReactModule(name = ExceptionsManagerModule.NAME)
public class ExceptionsManagerModule extends BaseJavaModule {
public static final String NAME = "ExceptionsManager";
private final DevSupportManager mDevSupportManager;
public ExceptionsManagerModule(DevSupportManager devSupportManager) {
mDevSupportManager = devSupportManager;
}
@Override
public String getName() {
return NAME;
}
@ReactMethod
public void reportFatalException(String message, ReadableArray stack, int id) {
JavaOnlyMap data = new JavaOnlyMap();
data.putString("message", message);
data.putArray("stack", stack);
data.putInt("id", id);
data.putBoolean("isFatal", true);
reportException(data);
}
@ReactMethod
public void reportSoftException(String message, ReadableArray stack, int id) {
JavaOnlyMap data = new JavaOnlyMap();
data.putString("message", message);
data.putArray("stack", stack);
data.putInt("id", id);
data.putBoolean("isFatal", false);
reportException(data);
}
@ReactMethod
public void reportException(ReadableMap data) {
String message = data.getString("message");
ReadableArray stack = data.getArray("stack");
int id = data.getInt("id");
boolean isFatal = data.getBoolean("isFatal");
if (mDevSupportManager.getDevSupportEnabled()) {
mDevSupportManager.showNewJSError(message, stack, id);
} else {
String extraDataAsJson = ExceptionDataHelper.getExtraDataAsJson(data);
if (isFatal) {
throw new JavascriptException(JSStackTrace.format(message, stack))
.setExtraDataAsJson(extraDataAsJson);
} else {
FLog.e(ReactConstants.TAG, JSStackTrace.format(message, stack));
if (extraDataAsJson != null) {
FLog.d(ReactConstants.TAG, "extraData: %s", extraDataAsJson);
}
}
}
}
@ReactMethod
public void updateExceptionMessage(String title, ReadableArray details, int exceptionId) {
if (mDevSupportManager.getDevSupportEnabled()) {
mDevSupportManager.updateJSError(title, details, exceptionId);
}
}
@ReactMethod
public void dismissRedbox() {
if (mDevSupportManager.getDevSupportEnabled()) {
mDevSupportManager.hideRedboxDialog();
}
}
}
| - Add null/undefined check for error handling
Summary: Same as title. Changing as per suggestion.
Reviewed By: furdei
Differential Revision: D16615807
fbshipit-source-id: 1c35ae1471beb2460e975841f367ffd49ce34494
| ReactAndroid/src/main/java/com/facebook/react/modules/core/ExceptionsManagerModule.java | - Add null/undefined check for error handling |
|
Java | apache-2.0 | 844b8465c95f54a6db6ceb0fa2ee5ae3024e2001 | 0 | MICommunity/psi-jami,MICommunity/psi-jami,MICommunity/psi-jami | jami-bridges/jami-uniprot/src/main/java/psidev/psi/mi/jami/bridges/uniprot/uniprot/uniprotutil/UniprotToJAMI.java | package psidev.psi.mi.jami.bridges.uniprot.uniprot.uniprotutil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import psidev.psi.mi.jami.bridges.exception.BadResultException;
import psidev.psi.mi.jami.bridges.exception.EntryNotFoundException;
import psidev.psi.mi.jami.bridges.exception.FetcherException;
import psidev.psi.mi.jami.model.CvTerm;
import psidev.psi.mi.jami.model.Organism;
import psidev.psi.mi.jami.model.Protein;
import psidev.psi.mi.jami.model.Xref;
import psidev.psi.mi.jami.model.impl.DefaultCvTerm;
import psidev.psi.mi.jami.model.impl.DefaultOrganism;
import psidev.psi.mi.jami.model.impl.DefaultProtein;
import psidev.psi.mi.jami.model.impl.DefaultXref;
import psidev.psi.mi.jami.utils.factory.AliasFactory;
import psidev.psi.mi.jami.utils.factory.ChecksumFactory;
import psidev.psi.mi.jami.utils.factory.CvTermFactory;
import psidev.psi.mi.jami.utils.factory.XrefFactory;
import uk.ac.ebi.kraken.interfaces.uniprot.*;
import uk.ac.ebi.kraken.interfaces.uniprot.dbx.ensembl.Ensembl;
import uk.ac.ebi.kraken.interfaces.uniprot.dbx.flybase.FlyBase;
import uk.ac.ebi.kraken.interfaces.uniprot.dbx.go.Go;
import uk.ac.ebi.kraken.interfaces.uniprot.dbx.interpro.InterPro;
import uk.ac.ebi.kraken.interfaces.uniprot.dbx.ipi.Ipi;
import uk.ac.ebi.kraken.interfaces.uniprot.dbx.pdb.Pdb;
import uk.ac.ebi.kraken.interfaces.uniprot.dbx.reactome.Reactome;
import uk.ac.ebi.kraken.interfaces.uniprot.dbx.refseq.RefSeq;
import uk.ac.ebi.kraken.interfaces.uniprot.dbx.wormbase.WormBase;
import uk.ac.ebi.kraken.interfaces.uniprot.description.Field;
import uk.ac.ebi.kraken.interfaces.uniprot.description.FieldType;
import uk.ac.ebi.kraken.interfaces.uniprot.genename.GeneNameSynonym;
import uk.ac.ebi.kraken.interfaces.uniprot.genename.ORFName;
import uk.ac.ebi.kraken.interfaces.uniprot.genename.OrderedLocusName;
import uk.ac.ebi.kraken.interfaces.uniprot.DatabaseCrossReference;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created with IntelliJ IDEA.
*
* @author: Gabriel Aldam ([email protected])
* Date: 14/05/13
* Time: 13:41
*/
public class UniprotToJAMI {
private final static Logger log = LoggerFactory.getLogger(UniprotToJAMI.class.getName());
public static Protein getProteinFromEntry(UniProtEntry e)
throws FetcherException {
if(e == null){
throw new EntryNotFoundException("Uniprot entry was null.");
}
String shortName = null;
String fullName = null;
//THIS ID HAS BEEN TAKEN FROM THE 'ID' name
List<Field> fields = e.getProteinDescription().getRecommendedName().getFields();
for(Field f: fields){
if(f.getType() == FieldType.SHORT){
if(shortName == null){
shortName = f.getValue();
}
else{log.debug("Uniprot entry has multiple rec. shortName: "+shortName+", "+f.getValue());}
}
else if(f.getType() == FieldType.FULL){
if(fullName == null){
fullName = f.getValue();
}
else{log.debug("Uniprot entry has multiple rec. fullName: "+fullName+", "+f.getValue());}
}
}
Protein p;
//SHORTNAME - ShortName/FullName/UniprotID/UniprotAC
if(shortName != null){
p = new DefaultProtein(shortName);
}else if(fullName != null){
p = new DefaultProtein(fullName);
}else if(e.getUniProtId() != null){
p = new DefaultProtein(e.getUniProtId().getValue());
}else if(e.getPrimaryUniProtAccession() != null){
p = new DefaultProtein(e.getPrimaryUniProtAccession().getValue());
} else {
throw new BadResultException(
"The Uniprot entry has no names, accessions, or identifiers.");
}
//FULLNAME
if(fullName != null){
p.setFullName(fullName);
}
//PRIMARY ACCESSION
if(e.getPrimaryUniProtAccession() != null){
p.setUniprotkb(e.getPrimaryUniProtAccession().getValue());
} else {
throw new BadResultException(
"The Uniprot entry ["+p.getShortName()+"] has no primary Accession.");
}
XrefFactory xrefFactory = new XrefFactory();
//UNIPROT ID AS SECONDARY AC
if(e.getUniProtId() != null){
p.getIdentifiers().add(
xrefFactory.createUniprotSecondary(e.getUniProtId().getValue()));
}
//SECONDARY ACs
if(e.getSecondaryUniProtAccessions() != null
&& e.getSecondaryUniProtAccessions().size() > 0) {
for(SecondaryUniProtAccession ac : e.getSecondaryUniProtAccessions()){
if(ac.getValue() != null){
p.getIdentifiers().add(
xrefFactory.createUniprotSecondary(ac.getValue()));
}
}
}
//TODO review the aliases
//Aliases
if(e.getGenes() != null && e.getGenes().size() > 0){
for(Gene g : e.getGenes()){
//Gene Name
if(g.hasGeneName()){
p.getAliases().add(AliasFactory.createGeneName(
g.getGeneName().getValue()));
}
//Gene Name Synonym
if(g.getGeneNameSynonyms() != null
&& g.getGeneNameSynonyms().size() > 0){
for(GeneNameSynonym gns : g.getGeneNameSynonyms()){
p.getAliases().add(AliasFactory.createGeneNameSynonym(
gns.getValue()));
}
}
//ORF names
if(g.getORFNames() != null
&& g.getORFNames().size() > 0){
for(ORFName orf : g.getORFNames()){
p.getAliases().add(AliasFactory.createOrfName(
orf.getValue()));
}
}
//Locus Names
if(g.getOrderedLocusNames() != null
&& g.getOrderedLocusNames().size() > 0){
for(OrderedLocusName oln : g.getOrderedLocusNames()){
p.getAliases().add(AliasFactory.createLocusName(
oln.getValue()));
}
}
}
}
//Database Xrefs
for(DatabaseCrossReference dbxref : e.getDatabaseCrossReferences()){
Xref dbxrefStandardised = getDatabaseXref(dbxref);
if(dbxrefStandardised != null){
p.getXrefs().add(dbxrefStandardised);
}
}
//SEQUENCE // CHECKSUMS
p.setSequence(e.getSequence().getValue());
ChecksumFactory cf = new ChecksumFactory();
//todo add MI term for crc64 checksums
p.getChecksums().add(cf.createAnnotation("CRC64", null, e.getSequence().getCRC64()));
//Rogid will be calculated at enrichment - the equation need not be applied in an organism conflict
p.setOrganism(getOrganismFromEntry(e));
return p;
}
private static Map<DatabaseType,CvTerm> databaseMap = null;
protected static void initiateDatabaseMap(){
databaseMap = new HashMap<DatabaseType, CvTerm>();
databaseMap.put(DatabaseType.GO, new DefaultCvTerm("go" , "MI:0448"));
databaseMap.put(DatabaseType.INTERPRO, new DefaultCvTerm("interpro" , "MI:0449"));
databaseMap.put(DatabaseType.PDB, new DefaultCvTerm("pdb" , "MI:0460"));
databaseMap.put(DatabaseType.REACTOME, new DefaultCvTerm("reactome" , "MI:0467"));
databaseMap.put(DatabaseType.ENSEMBL, new DefaultCvTerm("ensembl" , "MI:0476"));
databaseMap.put(DatabaseType.WORMBASE, new DefaultCvTerm("wormbase" , "MI:0487" ));
databaseMap.put(DatabaseType.FLYBASE, new DefaultCvTerm("flybase" , "MI:0478" ));
databaseMap.put(DatabaseType.REFSEQ, new DefaultCvTerm("refseq" , "MI:0481" ));
databaseMap.put(DatabaseType.IPI, new DefaultCvTerm("ipi" , "MI:0675" ));
}
protected static Xref getDatabaseXref(DatabaseCrossReference dbxref){
if(databaseMap == null) initiateDatabaseMap();
if (databaseMap.containsKey(dbxref.getDatabase())){
CvTerm database = databaseMap.get(dbxref.getDatabase());
String id = null;
if(dbxref.getDatabase() == DatabaseType.GO){
Go db = (Go)dbxref;
if(db.hasGoId()) id = db.getGoId().getValue();
}
else if(dbxref.getDatabase() == DatabaseType.INTERPRO){
InterPro db = (InterPro)dbxref;
if(db.hasInterProId()) id = db.getInterProId().getValue();
}
else if(dbxref.getDatabase() == DatabaseType.PDB){
Pdb db = (Pdb)dbxref;
if(db.hasPdbAccessionNumber()) id = db.getPdbAccessionNumber().getValue();
}
else if(dbxref.getDatabase() == DatabaseType.REACTOME){
Reactome db = (Reactome)dbxref;
if(db.hasReactomeAccessionNumber()) id = db.getReactomeAccessionNumber().getValue();
}
else if(dbxref.getDatabase() == DatabaseType.ENSEMBL){
//Todo check that the order f these is correct
Ensembl db = (Ensembl)dbxref;
if(db.hasEnsemblProteinIdentifier()) id = db.getEnsemblProteinIdentifier().getValue();
else if(db.hasEnsemblTranscriptIdentifier()) id = db.getEnsemblTranscriptIdentifier().getValue();
else if(db.hasEnsemblGeneIdentifier()) id = db.getEnsemblGeneIdentifier().getValue();
}
else if(dbxref.getDatabase() == DatabaseType.WORMBASE){
WormBase db = (WormBase)dbxref;
if(db.hasWormBaseAccessionNumber()) id = db.getWormBaseAccessionNumber().getValue();
}
else if(dbxref.getDatabase() == DatabaseType.FLYBASE){
FlyBase db = (FlyBase)dbxref;
if(db.hasFlyBaseAccessionNumber()) id = db.getFlyBaseAccessionNumber().getValue();
}
else if(dbxref.getDatabase() == DatabaseType.REFSEQ){
RefSeq db = (RefSeq)dbxref;
if(db.hasRefSeqAccessionNumber()) id = db.getRefSeqAccessionNumber().getValue();
}
else if(dbxref.getDatabase() == DatabaseType.IPI){
Ipi db = (Ipi)dbxref;
if(db.hasIpiAcNumber()) id = db.getIpiAcNumber().getValue();
}
if(id != null) return new DefaultXref(database, id);
}
return null;
}
public static Organism getOrganismFromEntry(UniProtEntry e)
throws FetcherException{
//TODO Change where ogrnaisms come from
Organism o;
if(e.getNcbiTaxonomyIds() == null
|| e.getNcbiTaxonomyIds().isEmpty()){
o = new DefaultOrganism(-3); //Unknown
} else if(e.getNcbiTaxonomyIds().size() > 1){
throw new BadResultException(
"Uniprot entry ["+e.getPrimaryUniProtAccession().getValue()+"] "
+"has multiple organisms.");
} else {
String id = e.getNcbiTaxonomyIds().get(0).getValue();
try{
o = new DefaultOrganism( Integer.parseInt( id ) );
}catch(NumberFormatException n){
throw new BadResultException("NbiTaxonomyID could not be cast to an integer",n);
}
}
//Todo catch null pointer exception
o.setCommonName(e.getOrganism().getCommonName().getValue());
o.setScientificName(e.getOrganism().getScientificName().getValue());
return o;
}
}
| Added dependency for uniprot bridge | jami-bridges/jami-uniprot/src/main/java/psidev/psi/mi/jami/bridges/uniprot/uniprot/uniprotutil/UniprotToJAMI.java | Added dependency for uniprot bridge |
||
Java | mit | cc93e82e0ca129252c436a36d577f3eda5789ee2 | 0 | prl-tokyo/MAPE-autoscaling-analysis-service,prl-tokyo/MAPE-autoscaling-analysis-service | package jp.ac.nii.prl.mape.autoscaling.analysis.model;
import java.util.List;
import java.util.Optional;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonManagedReference;
@Entity
public class Deployment {
@Id
@GeneratedValue
@JsonIgnore
private Integer id;
@JsonIgnore
@OneToOne(mappedBy="deployment")
private Adaptation adaptation;
@OneToMany(mappedBy="deployment")
private List<Instance> instances;
@OneToMany(mappedBy="deployment")
private List<InstanceType> instanceTypes;
@JsonManagedReference
public Adaptation getAdaptation() {
return adaptation;
}
public Integer getId() {
return id;
}
public Optional<Instance> getInstanceByInstID(String instID) {
for (Instance instance:instances) {
if (instance.getInstID().equals(instID))
return Optional.of(instance);
}
return Optional.empty();
}
public Optional<InstanceType> getInstanceTypeByInstType(String instType) {
for (InstanceType instanceType:instanceTypes) {
if (instanceType.getTypeID().equals(instType))
return Optional.of(instanceType);
}
return Optional.empty();
}
@JsonManagedReference
public List<Instance> getInstances() {
return instances;
}
@JsonManagedReference
public List<InstanceType> getInstanceTypes() {
return instanceTypes;
}
public int getNumberCPUs() {
int cpus = 0;
for (Instance instance:instances)
cpus += instance.getInstanceType().getTypeCPUs();
return cpus;
}
public void setAdaptation(Adaptation adaptation) {
this.adaptation = adaptation;
}
public void setId(Integer id) {
this.id = id;
}
public void setInstances(List<Instance> instances) {
this.instances = instances;
}
public void setInstanceTypes(List<InstanceType> instanceTypes) {
this.instanceTypes = instanceTypes;
}
public int size() {
return instances.size();
}
@Override
public String toString() {
return String.format("Deployment %d with %d virtual machines", id, instances.size());
}
}
| src/main/java/jp/ac/nii/prl/mape/autoscaling/analysis/model/Deployment.java | package jp.ac.nii.prl.mape.autoscaling.analysis.model;
import java.util.List;
import java.util.Optional;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonManagedReference;
@Entity
public class Deployment {
@Id
@GeneratedValue
@JsonIgnore
private Integer id;
@JsonIgnore
@OneToOne(mappedBy="deployment")
private Adaptation adaptation;
@OneToMany(mappedBy="deployment")
private List<Instance> instances;
@OneToMany(mappedBy="deployment")
private List<InstanceType> instanceTypes;
@JsonManagedReference
public Adaptation getAdaptation() {
return adaptation;
}
public Integer getId() {
return id;
}
public Optional<Instance> getInstanceByInstID(String instID) {
for (Instance instance:instances) {
if (instance.getInstID().equals(instID))
return Optional.of(instance);
}
return Optional.empty();
}
public Optional<InstanceType> getInstanceTypeByInstType(String instType) {
for (InstanceType instanceType:instanceTypes) {
if (instanceType.getTypeID().equals(instType))
return Optional.of(instanceType);
}
return Optional.empty();
}
@JsonManagedReference
public List<Instance> getInstances() {
return instances;
}
@JsonManagedReference
public List<InstanceType> getInstanceTypes() {
return instanceTypes;
}
public int getNumberCPUs() {
int cpus = 0;
for (Instance instance:instances)
cpus += instance.getInstanceType().getTypeCPUs();
return cpus;
}
public void setAdaptation(Adaptation adaptation) {
this.adaptation = adaptation;
}
public void setId(Integer id) {
this.id = id;
}
public void setInstances(List<Instance> instances) {
this.instances = instances;
}
public void setInstanceTypes(List<InstanceType> instanceTypes) {
this.instanceTypes = instanceTypes;
}
public int size() {
return instances.size();
}
public String toString() {
return String.format("Deployment %d with %d virtual machines", id, instances.size());
}
}
| Annotation | src/main/java/jp/ac/nii/prl/mape/autoscaling/analysis/model/Deployment.java | Annotation |
|
Java | mit | 824646e3c047ee23ad83b9adb28ae69ab2e4fa33 | 0 | softwarespartan/TWS | package com.examples;
import com.ib.client.*;
import com.tws.ContractFactory;
import java.util.HashMap;
import java.util.concurrent.*;
public class MarketDepthAdv {
public int reqId = 0;
public final BlockingQueue<ContractDetails> results = new ArrayBlockingQueue<ContractDetails>(1000);
public final HashMap<Integer,String> contractIdMap = new HashMap<>();
// create connection object for to communicate with TWS
public final EClientSocket eClientSocket = new EClientSocket(new EWrapper() {
@Override
public void tickPrice(int tickerId, int field, double price, int canAutoExecute) {
}
@Override
public void tickSize(int tickerId, int field, int size) {
}
@Override
public void tickOptionComputation(int tickerId, int field, double impliedVol, double delta, double optPrice, double pvDividend, double gamma, double vega, double theta, double undPrice) {
}
@Override
public void tickGeneric(int tickerId, int tickType, double value) {
}
@Override
public void tickString(int tickerId, int tickType, String value) {
}
@Override
public void tickEFP(int tickerId, int tickType, double basisPoints, String formattedBasisPoints, double impliedFuture, int holdDays, String futureExpiry, double dividendImpact, double dividendsToExpiry) {
}
@Override
public void orderStatus(int orderId, String status, int filled, int remaining, double avgFillPrice, int permId, int parentId, double lastFillPrice, int clientId, String whyHeld) {
}
@Override
public void openOrder(int orderId, Contract contract, Order order, OrderState orderState) {
}
@Override
public void openOrderEnd() {
}
@Override
public void updateAccountValue(String key, String value, String currency, String accountName) {
}
@Override
public void updatePortfolio(Contract contract, int position, double marketPrice, double marketValue, double averageCost, double unrealizedPNL, double realizedPNL, String accountName) {
}
@Override
public void updateAccountTime(String timeStamp) {
}
@Override
public void accountDownloadEnd(String accountName) {
}
@Override
public void nextValidId(int orderId) {
}
@Override
public void contractDetails(int reqId, ContractDetails contractDetails) {
results.add(contractDetails);
}
@Override
public void bondContractDetails(int reqId, ContractDetails contractDetails) {
}
@Override
public void contractDetailsEnd(int reqId) {
System.out.println("contractDetailEnd was called");
}
@Override
public void execDetails(int reqId, Contract contract, Execution execution) {
}
@Override
public void execDetailsEnd(int reqId) {
}
@Override
public void updateMktDepth(int tickerId, int position, int operation, int side, double price, int size) {
String exchange = Integer.toString(tickerId);
if ( contractIdMap.containsKey(tickerId) ) exchange = (String) contractIdMap.get(tickerId);
System.out.println("updateMktDepth: "+exchange+" "+position+" "+operation+" "+side+" "+price+" "+size);
}
@Override
public void updateMktDepthL2(int tickerId, int position, String marketMaker, int operation, int side, double price, int size) {
String exchange = Integer.toString(tickerId);
if ( contractIdMap.containsKey(tickerId) ) exchange = (String) contractIdMap.get(tickerId);
System.out.println("updateMktDepthL2: "+exchange+":"+marketMaker+" "+position+" "+operation+" "+side+" "+price+" "+size);
}
@Override
public void updateNewsBulletin(int msgId, int msgType, String message, String origExchange) {
}
@Override
public void managedAccounts(String accountsList) {
}
@Override
public void receiveFA(int faDataType, String xml) {
}
@Override
public void historicalData(int reqId, String date, double open, double high, double low, double close, int volume, int count, double WAP, boolean hasGaps) {
}
@Override
public void scannerParameters(String xml) {
}
@Override
public void scannerData(int reqId, int rank, ContractDetails contractDetails, String distance, String benchmark, String projection, String legsStr) {
}
@Override
public void scannerDataEnd(int reqId) {
}
@Override
public void realtimeBar(int reqId, long time, double open, double high, double low, double close, long volume, double wap, int count) {
}
@Override
public void currentTime(long time) {
}
@Override
public void fundamentalData(int reqId, String data) {
}
@Override
public void deltaNeutralValidation(int reqId, UnderComp underComp) {
}
@Override
public void tickSnapshotEnd(int reqId) {
}
@Override
public void marketDataType(int reqId, int marketDataType) {
}
@Override
public void commissionReport(CommissionReport commissionReport) {
}
@Override
public void position(String account, Contract contract, int pos, double avgCost) {
}
@Override
public void positionEnd() {
}
@Override
public void accountSummary(int reqId, String account, String tag, String value, String currency) {
}
@Override
public void accountSummaryEnd(int reqId) {
}
@Override
public void verifyMessageAPI(String apiData) {
}
@Override
public void verifyCompleted(boolean isSuccessful, String errorText) {
}
@Override
public void displayGroupList(int reqId, String groups) {
}
@Override
public void displayGroupUpdated(int reqId, String contractInfo) {
}
@Override
public void error(Exception e) {
e.printStackTrace(); results.add(new ContractDetails());
}
@Override
public void error(String str) {
System.out.println(str); results.add(new ContractDetails());
}
@Override
public void error(int id, int errorCode, String errorMsg) {
System.out.println(" "+id+" "+errorCode+": "+errorMsg);
if (id != -1) results.add(new ContractDetails());
}
@Override
public void connectionClosed() {
System.out.println("connection closed ...");
}
});
public final ExecutorService executorService = Executors.newSingleThreadExecutor();
public ContractDetails getContractDetails(Contract contract) throws InterruptedException,ExecutionException {
this.eClientSocket.reqContractDetails(0,contract);
ContractDetails contractDetails = executorService.submit( () -> results.take() ).get();
return contractDetails;
}
public void reqMarketDepth(String symbol, int numRows) throws ExecutionException, InterruptedException {
Contract contract = ContractFactory.GenericStockContract(symbol);
ContractDetails contractDetails = this.getContractDetails(contract);
int id = this.reqId++;
for (String exchange : contractDetails.m_validExchanges.split(",")) {
System.out.println("requesting market depth from exchange: "+exchange);
contract.m_primaryExch = exchange;
contract.m_exchange = exchange;
this.contractIdMap.put(id,exchange);
this.eClientSocket.reqMktDepth(id, contract, numRows, null);
id = id + 1;
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
MarketDepthAdv marketDepth = new MarketDepthAdv();
// try to connect to TWS
marketDepth.eClientSocket.eConnect("127.0.0.1", 7496, 0);
// initialize a contract for symbols to BUY
//Contract contract = ContractFactory.GenericStockContract("FB");
//"SMART","ISE","CHX","ARCA","ISLAND","VWAP","IBSX","DRCTEDGE","BEX","BATS","EDGEA","LAVA","CSFBALGO","JEFFALGO","BYX","IEX","TPLUS2","PSX"
// set the exchange
//contract.m_exchange = ""; contract.m_primaryExch = "";
//ContractDetails contractDetails = marketDepth.getContractDetails(contract);
//if ( contractDetails.m_summary.m_symbol != null)
// System.out.println(com.ib.client.EWrapperMsgGenerator.contractDetails(0,contractDetails));
marketDepth.reqMarketDepth("FB",5);
//marketDepth.executorService.shutdown();
// place the order
//eClientSocket.reqMktDepth(6352, contract, 10, null);
// // set the exchange
// contract.m_exchange = "ARCA";
//
// // place the order
// eClientSocket.reqMktDepth(6353, contract, 10, null);
//
// // set the exchange
// contract.m_exchange = "BATS";
//
// // place the order
// eClientSocket.reqMktDepth(6354, contract, 10, null);
//
// // set the exchange
// contract.m_exchange = "EDGEA";
//
// // place the order
// eClientSocket.reqMktDepth(6355, contract, 10, null);
}
}
| src/com/examples/MarketDepthAdv.java | package com.examples;
import com.ib.client.*;
import com.tws.ContractFactory;
import java.util.HashMap;
import java.util.concurrent.*;
public class MarketDepthAdv {
public int reqId = 0;
public final BlockingQueue<ContractDetails> results = new ArrayBlockingQueue<ContractDetails>(1000);
public final HashMap<Integer,String> contractIdMap = new HashMap<>();
// create connection object for to communicate with TWS
public final EClientSocket eClientSocket = new EClientSocket(new EWrapper() {
@Override
public void tickPrice(int tickerId, int field, double price, int canAutoExecute) {
}
@Override
public void tickSize(int tickerId, int field, int size) {
}
@Override
public void tickOptionComputation(int tickerId, int field, double impliedVol, double delta, double optPrice, double pvDividend, double gamma, double vega, double theta, double undPrice) {
}
@Override
public void tickGeneric(int tickerId, int tickType, double value) {
}
@Override
public void tickString(int tickerId, int tickType, String value) {
}
@Override
public void tickEFP(int tickerId, int tickType, double basisPoints, String formattedBasisPoints, double impliedFuture, int holdDays, String futureExpiry, double dividendImpact, double dividendsToExpiry) {
}
@Override
public void orderStatus(int orderId, String status, int filled, int remaining, double avgFillPrice, int permId, int parentId, double lastFillPrice, int clientId, String whyHeld) {
}
@Override
public void openOrder(int orderId, Contract contract, Order order, OrderState orderState) {
}
@Override
public void openOrderEnd() {
}
@Override
public void updateAccountValue(String key, String value, String currency, String accountName) {
}
@Override
public void updatePortfolio(Contract contract, int position, double marketPrice, double marketValue, double averageCost, double unrealizedPNL, double realizedPNL, String accountName) {
}
@Override
public void updateAccountTime(String timeStamp) {
}
@Override
public void accountDownloadEnd(String accountName) {
}
@Override
public void nextValidId(int orderId) {
}
@Override
public void contractDetails(int reqId, ContractDetails contractDetails) {
results.add(contractDetails);
}
@Override
public void bondContractDetails(int reqId, ContractDetails contractDetails) {
}
@Override
public void contractDetailsEnd(int reqId) {
System.out.println("contractDetailEnd was called");
}
@Override
public void execDetails(int reqId, Contract contract, Execution execution) {
}
@Override
public void execDetailsEnd(int reqId) {
}
@Override
public void updateMktDepth(int tickerId, int position, int operation, int side, double price, int size) {
String exchange = Integer.toString(tickerId);
if ( contractIdMap.containsKey(tickerId) ) exchange = (String) contractIdMap.get(tickerId);
System.out.println("updateMktDepth: "+exchange+" "+position+" "+operation+" "+side+" "+price+" "+size);
}
@Override
public void updateMktDepthL2(int tickerId, int position, String marketMaker, int operation, int side, double price, int size) {
}
@Override
public void updateNewsBulletin(int msgId, int msgType, String message, String origExchange) {
}
@Override
public void managedAccounts(String accountsList) {
}
@Override
public void receiveFA(int faDataType, String xml) {
}
@Override
public void historicalData(int reqId, String date, double open, double high, double low, double close, int volume, int count, double WAP, boolean hasGaps) {
}
@Override
public void scannerParameters(String xml) {
}
@Override
public void scannerData(int reqId, int rank, ContractDetails contractDetails, String distance, String benchmark, String projection, String legsStr) {
}
@Override
public void scannerDataEnd(int reqId) {
}
@Override
public void realtimeBar(int reqId, long time, double open, double high, double low, double close, long volume, double wap, int count) {
}
@Override
public void currentTime(long time) {
}
@Override
public void fundamentalData(int reqId, String data) {
}
@Override
public void deltaNeutralValidation(int reqId, UnderComp underComp) {
}
@Override
public void tickSnapshotEnd(int reqId) {
}
@Override
public void marketDataType(int reqId, int marketDataType) {
}
@Override
public void commissionReport(CommissionReport commissionReport) {
}
@Override
public void position(String account, Contract contract, int pos, double avgCost) {
}
@Override
public void positionEnd() {
}
@Override
public void accountSummary(int reqId, String account, String tag, String value, String currency) {
}
@Override
public void accountSummaryEnd(int reqId) {
}
@Override
public void verifyMessageAPI(String apiData) {
}
@Override
public void verifyCompleted(boolean isSuccessful, String errorText) {
}
@Override
public void displayGroupList(int reqId, String groups) {
}
@Override
public void displayGroupUpdated(int reqId, String contractInfo) {
}
@Override
public void error(Exception e) {
e.printStackTrace(); results.add(new ContractDetails());
}
@Override
public void error(String str) {
System.out.println(str); results.add(new ContractDetails());
}
@Override
public void error(int id, int errorCode, String errorMsg) {
System.out.println(" "+id+" "+errorCode+": "+errorMsg);
if (id != -1) results.add(new ContractDetails());
}
@Override
public void connectionClosed() {
System.out.println("connection closed ...");
}
});
public final ExecutorService executorService = Executors.newSingleThreadExecutor();
public ContractDetails getContractDetails(Contract contract) throws InterruptedException,ExecutionException {
this.eClientSocket.reqContractDetails(0,contract);
ContractDetails contractDetails = executorService.submit( () -> results.take() ).get();
return contractDetails;
}
public void reqMarketDepth(String symbol, int numRows) throws ExecutionException, InterruptedException {
Contract contract = ContractFactory.GenericStockContract(symbol);
ContractDetails contractDetails = this.getContractDetails(contract);
int id = this.reqId++;
for (String exchange : contractDetails.m_validExchanges.split(",")) {
System.out.println("requesting market depth from exchange: "+exchange);
contract.m_primaryExch = exchange;
contract.m_exchange = exchange;
this.contractIdMap.put(id,exchange);
this.eClientSocket.reqMktDepth(id, contract, numRows, null);
id = id + 1;
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
MarketDepthAdv marketDepth = new MarketDepthAdv();
// try to connect to TWS
marketDepth.eClientSocket.eConnect("127.0.0.1", 7496, 0);
// initialize a contract for symbols to BUY
//Contract contract = ContractFactory.GenericStockContract("FB");
//"SMART","ISE","CHX","ARCA","ISLAND","VWAP","IBSX","DRCTEDGE","BEX","BATS","EDGEA","LAVA","CSFBALGO","JEFFALGO","BYX","IEX","TPLUS2","PSX"
// set the exchange
//contract.m_exchange = ""; contract.m_primaryExch = "";
//ContractDetails contractDetails = marketDepth.getContractDetails(contract);
//if ( contractDetails.m_summary.m_symbol != null)
// System.out.println(com.ib.client.EWrapperMsgGenerator.contractDetails(0,contractDetails));
marketDepth.reqMarketDepth("SPY",5);
//marketDepth.executorService.shutdown();
// place the order
//eClientSocket.reqMktDepth(6352, contract, 10, null);
// // set the exchange
// contract.m_exchange = "ARCA";
//
// // place the order
// eClientSocket.reqMktDepth(6353, contract, 10, null);
//
// // set the exchange
// contract.m_exchange = "BATS";
//
// // place the order
// eClientSocket.reqMktDepth(6354, contract, 10, null);
//
// // set the exchange
// contract.m_exchange = "EDGEA";
//
// // place the order
// eClientSocket.reqMktDepth(6355, contract, 10, null);
}
}
| implemented updateMarketDepthL2
| src/com/examples/MarketDepthAdv.java | implemented updateMarketDepthL2 |
|
Java | mit | b0d3b57ce13f85cc59581549d6cf8569e803f556 | 0 | natemara/wumpus | package edu.miamioh.cse283.htw;
import java.util.*;
public class Room {
public static final int EMPTY = 0;
public static final int BATS = 1;
public static final int HOLE = 2;
public static final int WUMPUS = 3;
public static final int OTHER_PLAYERS = 4;
/**
* Players currently in this room.
*/
protected ArrayList<ClientProxy> players;
/**
* Rooms that this room is connected to.
*/
protected HashSet<Room> connected;
/**
* ID number of this room.
*/
protected int roomId;
protected int contents;
/**
* Constructor.
*/
public Room(int contents) {
players = new ArrayList<ClientProxy>();
connected = new HashSet<Room>();
this.contents = contents;
}
public Room() {
this(EMPTY);
}
/**
* Set this room's id number.
*/
public void setIdNumber(int n) {
roomId = n;
}
/**
* Get this room's id number.
*/
public int getIdNumber() {
return roomId;
}
/**
* Connect room r to this room (bidirectional).
*/
public void connectRoom(Room r) {
connected.add(r);
r.connected.add(r);
}
/**
* Called when a player enters this room.
*/
public synchronized void enterRoom(ClientProxy c) {
ArrayList<String> notifications = new ArrayList<String>();
switch (contents) {
case EMPTY:
players.add(c);
break;
case OTHER_PLAYERS:
players.add(c);
break;
case WUMPUS:
notifications.add("You hear a snarl and turn to see the horrible Wumpus!");
notifications.add("The wumpus eats you, and you are dead!");
c.sendNotifications(notifications);
c.kill();
break;
}
}
/**
* Called when a player leaves this room.
*/
public synchronized void leaveRoom(ClientProxy c) {
players.remove(c);
}
/**
* Returns a connected Room (if room is valid), otherwise returns null.
*/
public Room getRoom(int room) {
for (Room r : connected) {
if (r.getIdNumber() == room) {
return r;
}
}
return null;
}
/**
* Returns a string describing what a player sees in this room.
*/
public synchronized ArrayList<String> getSensed() {
ArrayList<String> msg = new ArrayList<String>();
msg.add(String.format("You are in room %d.", roomId));
for (Room r : connected) {
switch (r.contents) {
case WUMPUS:
msg.add("You smell the smelly smell of a Wumpus!");
break;
case BATS:
msg.add("You hear the screech of the bats");
break;
case OTHER_PLAYERS:
msg.add("You hear the stomping of adventurer's feet");
break;
case HOLE:
msg.add("You feel the rush of the wind");
break;
}
}
String t = "You see tunnels to rooms ";
int c = 0;
for (Room r : connected) {
++c;
if (c == connected.size()) {
t = t.concat("and " + r.getIdNumber() + ".");
} else {
t = t.concat("" + r.getIdNumber() + ", ");
}
}
msg.add(t);
return msg;
}
}
| src/edu/miamioh/cse283/htw/Room.java | package edu.miamioh.cse283.htw;
import java.util.*;
public class Room {
public static final int EMPTY = 0;
public static final int BATS = 1;
public static final int HOLE = 2;
public static final int WUMPUS = 3;
public static final int OTHER_PLAYERS = 4;
/**
* Players currently in this room.
*/
protected ArrayList<ClientProxy> players;
/**
* Rooms that this room is connected to.
*/
protected HashSet<Room> connected;
/**
* ID number of this room.
*/
protected int roomId;
protected int contents;
/**
* Constructor.
*/
public Room(int contents) {
players = new ArrayList<ClientProxy>();
connected = new HashSet<Room>();
this.contents = contents;
}
public Room() {
this(EMPTY);
}
/**
* Set this room's id number.
*/
public void setIdNumber(int n) {
roomId = n;
}
/**
* Get this room's id number.
*/
public int getIdNumber() {
return roomId;
}
/**
* Connect room r to this room (bidirectional).
*/
public void connectRoom(Room r) {
connected.add(r);
r.connected.add(r);
}
/**
* Called when a player enters this room.
*/
public synchronized void enterRoom(ClientProxy c) {
ArrayList<String> notifications = new ArrayList<String>();
switch (contents) {
case EMPTY:
players.add(c);
break;
case OTHER_PLAYERS:
players.add(c);
break;
case WUMPUS:
notifications.add("You hear a snarl and turn to see the horrible Wumpus!");
notifications.add("The wumpus eats you, and you are dead!");
c.sendNotifications(notifications);
c.kill();
break;
}
}
/**
* Called when a player leaves this room.
*/
public synchronized void leaveRoom(ClientProxy c) {
players.remove(c);
}
/**
* Returns a connected Room (if room is valid), otherwise returns null.
*/
public Room getRoom(int room) {
for (Room r : connected) {
if (r.getIdNumber() == room) {
return r;
}
}
return null;
}
/**
* Returns a string describing what a player sees in this room.
*/
public synchronized ArrayList<String> getSensed() {
ArrayList<String> msg = new ArrayList<String>();
msg.add(String.format("You are in room %d.", roomId));
msg.add("Room is empty.");
String t = "You see tunnels to rooms ";
int c = 0;
for (Room r : connected) {
++c;
if (c == connected.size()) {
t = t.concat("and " + r.getIdNumber() + ".");
} else {
t = t.concat("" + r.getIdNumber() + ", ");
}
}
msg.add(t);
return msg;
}
}
| show player their senses
| src/edu/miamioh/cse283/htw/Room.java | show player their senses |
|
Java | mit | 9398b08d4b945c7d4a4d4a6dd3bac37507c05375 | 0 | pietermartin/sqlg,pietermartin/sqlg,pietermartin/sqlg,pietermartin/sqlg | package org.umlg.sqlg.test.topology;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.Test;
import org.umlg.sqlg.structure.SqlgGraph;
import org.umlg.sqlg.test.BaseTest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author Pieter Martin (https://github.com/pietermartin)
* Date: 2017/06/19
*/
@SuppressWarnings("Duplicates")
public class TestDeadLock extends BaseTest {
@BeforeClass
public static void beforeClass() {
Assume.assumeFalse(isH2());
}
@Test
public void testDeadLock4() throws InterruptedException {
Vertex a1 = this.sqlgGraph.addVertex(T.label, "A", "nameA1", "haloA1");
Vertex b1 = this.sqlgGraph.addVertex(T.label, "B", "nameB1", "haloB1");
this.sqlgGraph.tx().commit();
Thread t1 = new Thread(() -> {
//Lock table A
for (int i = 0; i < 3; i++) {
try {
this.sqlgGraph.addVertex(T.label, "A", "nameA2", "haloA2");
b1.property("nameB1", "haloAgainB2");
this.sqlgGraph.tx().commit();
break;
} catch (Exception e) {
this.sqlgGraph.tx().rollback();
}
}
}, "First writer");
Thread t2 = new Thread(() -> {
//Lock table B
for (int i = 0; i < 3; i++) {
try {
this.sqlgGraph.addVertex(T.label, "B", "nameB2", "haloB2");
a1.property("nameA1", "haloAgainA1");
this.sqlgGraph.tx().commit();
break;
} catch (Exception e) {
this.sqlgGraph.tx().rollback();
}
}
}, "Second writer");
t1.start();
t2.start();
t1.join();
t2.join();
Assert.assertEquals(2, this.sqlgGraph.traversal().V().hasLabel("A").count().next(), 0);
Assert.assertEquals(2, this.sqlgGraph.traversal().V().hasLabel("B").count().next(), 0);
Assert.assertEquals(1, this.sqlgGraph.traversal().V().hasLabel("B").has("nameB1", "haloAgainB2").count().next(), 0);
Assert.assertEquals(1, this.sqlgGraph.traversal().V().hasLabel("A").has("nameA1", "haloAgainA1").count().next(), 0);
}
@Test
public void testDeadLock3() throws InterruptedException {
SqlgGraph g = this.sqlgGraph;
Map<String, Object> m1 = new HashMap<>();
m1.put("name", "name1");
g.addVertex("s1.v1", m1);
g.tx().commit();
CountDownLatch t1Wrote = new CountDownLatch(1);
CountDownLatch t2Wrote = new CountDownLatch(1);
Thread t1 = new Thread(() -> {
Map<String, Object> m11 = new HashMap<>();
m11.put("name", "name2");
g.addVertex("s1.v1", m11);
t1Wrote.countDown();
try {
t2Wrote.await(10, TimeUnit.SECONDS);
Map<String, Object> m2 = new HashMap<>();
m2.put("name", "name3");
m2.put("att1", "val1");
g.addVertex("s1.v1", m2);
g.tx().commit();
} catch (InterruptedException ie) {
Assert.fail(ie.getMessage());
}
}, "First writer");
Thread t2 = new Thread(() -> {
try {
t1Wrote.await();
Map<String, Object> m112 = new HashMap<>();
m112.put("name", "name4");
m112.put("att2", "val2");
g.addVertex("s1.v1", m112);
t2Wrote.countDown();
g.tx().commit();
} catch (InterruptedException ie) {
Assert.fail(ie.getMessage());
}
}, "Second writer");
t1.start();
t2.start();
t1.join();
t2.join();
if (isPostgres()) {
Assert.assertEquals(4L, g.traversal().V().hasLabel("s1.v1").count().next(), 0);
} else if (isHsqldb()) {
Assert.assertEquals(1L, g.traversal().V().hasLabel("s1.v1").count().next(), 0);
} else if (isH2()) {
Assert.assertEquals(3L, g.traversal().V().hasLabel("s1.v1").count().next(), 0);
}
}
@Test
public void testDeadLock2() throws InterruptedException {
this.sqlgGraph.addVertex(T.label, "A");
this.sqlgGraph.tx().commit();
CountDownLatch latch = new CountDownLatch(1);
Thread thread1 = new Thread(() -> {
//#1 open a transaction.
this.sqlgGraph.traversal().V().hasLabel("A").next();
try {
System.out.println("await");
latch.await();
//sleep for a bit to let Thread2 first take the topology lock
Thread.sleep(1000);
System.out.println("thread1 wakeup");
//This will try to take a read lock that will dead lock
this.sqlgGraph.traversal().V().hasLabel("A").next();
System.out.println("thread1 complete");
this.sqlgGraph.tx().commit();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}, "thread1");
Thread thread2 = new Thread(() -> {
//#2 take the topology lock, adding a name field will lock the topology.
//this will not be able to complete while Thread1's transaction is still in progress.
//It locks in postgres.
latch.countDown();
this.sqlgGraph.addVertex(T.label, "A", "name", "a");
this.sqlgGraph.tx().commit();
System.out.println("thread2 fini");
}, "thread2");
thread1.start();
Thread.sleep(1000);
thread2.start();
thread1.join();
thread2.join();
}
/**
* this deadlocks!
*
* @throws Exception
*/
@Test
public void testDeadlock1() throws Exception {
final Vertex v1 = sqlgGraph.addVertex(T.label, "t1", "name", "n1");
Vertex v2 = sqlgGraph.addVertex(T.label, "t1", "name", "n2");
Vertex v3 = sqlgGraph.addVertex(T.label, "t2", "name", "n3");
v1.addEdge("e1", v2);
sqlgGraph.tx().commit();
// sqlgGraph.getTopology().setLockTimeout(5);
Object o1 = new Object();
Object o2 = new Object();
AtomicInteger ok = new AtomicInteger(0);
Thread t1 = new Thread(() -> {
try {
synchronized (o1) {
o1.wait();
}
GraphTraversal<Vertex, Vertex> gt = sqlgGraph.traversal().V().hasLabel("t1").out("e1");
int cnt = 0;
// this lock the E_e1 table and then request topology read lock
while (gt.hasNext()) {
gt.next();
synchronized (o2) {
o2.notify();
}
if (cnt == 0) {
synchronized (o1) {
o1.wait(1000);
}
}
cnt++;
}
sqlgGraph.tx().commit();
ok.incrementAndGet();
} catch (Exception e) {
e.printStackTrace();
//fail(e.getMessage());
}
}, "thread-1");
t1.start();
Thread t2 = new Thread(() -> {
try {
synchronized (o2) {
o2.wait();
}
// this locks the topology and then tries to modify the E_e1 table
v1.addEdge("e1", v3);
synchronized (o1) {
o1.notify();
}
sqlgGraph.tx().commit();
ok.incrementAndGet();
} catch (Exception e) {
e.printStackTrace();
//fail(e.getMessage());
}
}, "thread-2");
t2.start();
Thread.sleep(1000);
synchronized (o1) {
o1.notifyAll();
}
t1.join();
t2.join();
Assert.assertEquals(2, ok.get());
}
@Test
public void testDeadlock1DifferentGraphs() throws Exception {
Vertex v1 = sqlgGraph.addVertex(T.label, "t1", "name", "n1");
Vertex v2 = sqlgGraph.addVertex(T.label, "t1", "name", "n2");
Vertex v3 = sqlgGraph.addVertex(T.label, "t2", "name", "n3");
v1.addEdge("e1", v2);
sqlgGraph.tx().commit();
Object o1 = new Object();
Object o2 = new Object();
AtomicInteger ok = new AtomicInteger(0);
Thread t1 = new Thread(() -> {
try {
synchronized (o1) {
o1.wait();
}
GraphTraversal<Vertex, Vertex> gt = sqlgGraph.traversal().V().hasLabel("t1").out("e1");
int cnt = 0;
// this lock the E_e1 table and then request topology read lock
while (gt.hasNext()) {
gt.next();
synchronized (o2) {
o2.notify();
}
if (cnt == 0) {
synchronized (o1) {
o1.wait(1000);
}
}
cnt++;
}
sqlgGraph.tx().commit();
ok.incrementAndGet();
} catch (Exception e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
}, "thread-1");
t1.start();
Thread t2 = new Thread(() -> {
try {
try (SqlgGraph sqlgGraph1 = SqlgGraph.open(getConfigurationClone())) {
Vertex v1b = sqlgGraph1.vertices(v1.id()).next();
Vertex v3b = sqlgGraph1.vertices(v3.id()).next();
synchronized (o2) {
o2.wait();
}
// this locks the topology and then tries to modify the E_e1 table
v1b.addEdge("e1", v3b);
synchronized (o1) {
o1.notify();
}
sqlgGraph1.tx().commit();
ok.incrementAndGet();
}
} catch (Exception e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
}, "thread-2");
t2.start();
Thread.sleep(1000);
synchronized (o1) {
o1.notifyAll();
}
t1.join();
t2.join();
Assert.assertEquals(2, ok.get());
}
}
| sqlg-test/src/main/java/org/umlg/sqlg/test/topology/TestDeadLock.java | package org.umlg.sqlg.test.topology;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Assert;
import org.junit.Test;
import org.umlg.sqlg.structure.SqlgGraph;
import org.umlg.sqlg.test.BaseTest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author Pieter Martin (https://github.com/pietermartin)
* Date: 2017/06/19
*/
@SuppressWarnings("Duplicates")
public class TestDeadLock extends BaseTest {
@Test
public void testDeadLock4() throws InterruptedException {
Vertex a1 = this.sqlgGraph.addVertex(T.label, "A", "nameA1", "haloA1");
Vertex b1 = this.sqlgGraph.addVertex(T.label, "B", "nameB1", "haloB1");
this.sqlgGraph.tx().commit();
Thread t1 = new Thread(() -> {
//Lock table A
for (int i = 0; i < 3; i++) {
try {
this.sqlgGraph.addVertex(T.label, "A", "nameA2", "haloA2");
b1.property("nameB1", "haloAgainB2");
this.sqlgGraph.tx().commit();
break;
} catch (Exception e) {
this.sqlgGraph.tx().rollback();
}
}
}, "First writer");
Thread t2 = new Thread(() -> {
//Lock table B
for (int i = 0; i < 3; i++) {
try {
this.sqlgGraph.addVertex(T.label, "B", "nameB2", "haloB2");
a1.property("nameA1", "haloAgainA1");
this.sqlgGraph.tx().commit();
break;
} catch (Exception e) {
this.sqlgGraph.tx().rollback();
}
}
}, "Second writer");
t1.start();
t2.start();
t1.join();
t2.join();
Assert.assertEquals(2, this.sqlgGraph.traversal().V().hasLabel("A").count().next(), 0);
Assert.assertEquals(2, this.sqlgGraph.traversal().V().hasLabel("B").count().next(), 0);
Assert.assertEquals(1, this.sqlgGraph.traversal().V().hasLabel("B").has("nameB1", "haloAgainB2").count().next(), 0);
Assert.assertEquals(1, this.sqlgGraph.traversal().V().hasLabel("A").has("nameA1", "haloAgainA1").count().next(), 0);
}
@Test
public void testDeadLock3() throws InterruptedException {
SqlgGraph g = this.sqlgGraph;
Map<String, Object> m1 = new HashMap<>();
m1.put("name", "name1");
g.addVertex("s1.v1", m1);
g.tx().commit();
CountDownLatch t1Wrote = new CountDownLatch(1);
CountDownLatch t2Wrote = new CountDownLatch(1);
Thread t1 = new Thread(() -> {
Map<String, Object> m11 = new HashMap<>();
m11.put("name", "name2");
g.addVertex("s1.v1", m11);
t1Wrote.countDown();
try {
t2Wrote.await(10, TimeUnit.SECONDS);
Map<String, Object> m2 = new HashMap<>();
m2.put("name", "name3");
m2.put("att1", "val1");
g.addVertex("s1.v1", m2);
g.tx().commit();
} catch (InterruptedException ie) {
Assert.fail(ie.getMessage());
}
}, "First writer");
Thread t2 = new Thread(() -> {
try {
t1Wrote.await();
Map<String, Object> m112 = new HashMap<>();
m112.put("name", "name4");
m112.put("att2", "val2");
g.addVertex("s1.v1", m112);
t2Wrote.countDown();
g.tx().commit();
} catch (InterruptedException ie) {
Assert.fail(ie.getMessage());
}
}, "Second writer");
t1.start();
t2.start();
t1.join();
t2.join();
if (isPostgres()) {
Assert.assertEquals(4L, g.traversal().V().hasLabel("s1.v1").count().next(), 0);
} else if (isHsqldb()) {
Assert.assertEquals(1L, g.traversal().V().hasLabel("s1.v1").count().next(), 0);
} else if (isH2()) {
Assert.assertEquals(3L, g.traversal().V().hasLabel("s1.v1").count().next(), 0);
}
}
@Test
public void testDeadLock2() throws InterruptedException {
this.sqlgGraph.addVertex(T.label, "A");
this.sqlgGraph.tx().commit();
CountDownLatch latch = new CountDownLatch(1);
Thread thread1 = new Thread(() -> {
//#1 open a transaction.
this.sqlgGraph.traversal().V().hasLabel("A").next();
try {
System.out.println("await");
latch.await();
//sleep for a bit to let Thread2 first take the topology lock
Thread.sleep(1000);
System.out.println("thread1 wakeup");
//This will try to take a read lock that will dead lock
this.sqlgGraph.traversal().V().hasLabel("A").next();
System.out.println("thread1 complete");
this.sqlgGraph.tx().commit();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}, "thread1");
Thread thread2 = new Thread(() -> {
//#2 take the topology lock, adding a name field will lock the topology.
//this will not be able to complete while Thread1's transaction is still in progress.
//It locks in postgres.
latch.countDown();
this.sqlgGraph.addVertex(T.label, "A", "name", "a");
this.sqlgGraph.tx().commit();
System.out.println("thread2 fini");
}, "thread2");
thread1.start();
Thread.sleep(1000);
thread2.start();
thread1.join();
thread2.join();
}
/**
* this deadlocks!
*
* @throws Exception
*/
@Test
public void testDeadlock1() throws Exception {
final Vertex v1 = sqlgGraph.addVertex(T.label, "t1", "name", "n1");
Vertex v2 = sqlgGraph.addVertex(T.label, "t1", "name", "n2");
Vertex v3 = sqlgGraph.addVertex(T.label, "t2", "name", "n3");
v1.addEdge("e1", v2);
sqlgGraph.tx().commit();
// sqlgGraph.getTopology().setLockTimeout(5);
Object o1 = new Object();
Object o2 = new Object();
AtomicInteger ok = new AtomicInteger(0);
Thread t1 = new Thread(() -> {
try {
synchronized (o1) {
o1.wait();
}
GraphTraversal<Vertex, Vertex> gt = sqlgGraph.traversal().V().hasLabel("t1").out("e1");
int cnt = 0;
// this lock the E_e1 table and then request topology read lock
while (gt.hasNext()) {
gt.next();
synchronized (o2) {
o2.notify();
}
if (cnt == 0) {
synchronized (o1) {
o1.wait(1000);
}
}
cnt++;
}
sqlgGraph.tx().commit();
ok.incrementAndGet();
} catch (Exception e) {
e.printStackTrace();
//fail(e.getMessage());
}
}, "thread-1");
t1.start();
Thread t2 = new Thread(() -> {
try {
synchronized (o2) {
o2.wait();
}
// this locks the topology and then tries to modify the E_e1 table
v1.addEdge("e1", v3);
synchronized (o1) {
o1.notify();
}
sqlgGraph.tx().commit();
ok.incrementAndGet();
} catch (Exception e) {
e.printStackTrace();
//fail(e.getMessage());
}
}, "thread-2");
t2.start();
Thread.sleep(1000);
synchronized (o1) {
o1.notifyAll();
}
t1.join();
t2.join();
Assert.assertEquals(2, ok.get());
}
@Test
public void testDeadlock1DifferentGraphs() throws Exception {
Vertex v1 = sqlgGraph.addVertex(T.label, "t1", "name", "n1");
Vertex v2 = sqlgGraph.addVertex(T.label, "t1", "name", "n2");
Vertex v3 = sqlgGraph.addVertex(T.label, "t2", "name", "n3");
v1.addEdge("e1", v2);
sqlgGraph.tx().commit();
Object o1 = new Object();
Object o2 = new Object();
AtomicInteger ok = new AtomicInteger(0);
Thread t1 = new Thread(() -> {
try {
synchronized (o1) {
o1.wait();
}
GraphTraversal<Vertex, Vertex> gt = sqlgGraph.traversal().V().hasLabel("t1").out("e1");
int cnt = 0;
// this lock the E_e1 table and then request topology read lock
while (gt.hasNext()) {
gt.next();
synchronized (o2) {
o2.notify();
}
if (cnt == 0) {
synchronized (o1) {
o1.wait(1000);
}
}
cnt++;
}
sqlgGraph.tx().commit();
ok.incrementAndGet();
} catch (Exception e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
}, "thread-1");
t1.start();
Thread t2 = new Thread(() -> {
try {
try (SqlgGraph sqlgGraph1 = SqlgGraph.open(getConfigurationClone())) {
Vertex v1b = sqlgGraph1.vertices(v1.id()).next();
Vertex v3b = sqlgGraph1.vertices(v3.id()).next();
synchronized (o2) {
o2.wait();
}
// this locks the topology and then tries to modify the E_e1 table
v1b.addEdge("e1", v3b);
synchronized (o1) {
o1.notify();
}
sqlgGraph1.tx().commit();
ok.incrementAndGet();
}
} catch (Exception e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
}, "thread-2");
t2.start();
Thread.sleep(1000);
synchronized (o1) {
o1.notifyAll();
}
t1.join();
t2.join();
Assert.assertEquals(2, ok.get());
}
}
| skip for H2, it fails intermittently
| sqlg-test/src/main/java/org/umlg/sqlg/test/topology/TestDeadLock.java | skip for H2, it fails intermittently |
|
Java | mit | e2849c53cac34350826128eadcdf9e9574bad51b | 0 | OpenMods/OpenPeripheral-Addons | package openperipheral.addons.sensors;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import net.minecraft.block.Block;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.item.*;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.MathHelper;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import openmods.utils.WorldUtils;
import openperipheral.api.ApiAccess;
import openperipheral.api.adapter.IPeripheralAdapter;
import openperipheral.api.adapter.method.Arg;
import openperipheral.api.adapter.method.ReturnType;
import openperipheral.api.adapter.method.ScriptCallable;
import openperipheral.api.meta.IEntityPartialMetaBuilder;
import openperipheral.api.meta.IMetaProviderProxy;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.mojang.authlib.GameProfile;
public class AdapterSensor implements IPeripheralAdapter {
private static final String DONT_EVER_CHANGE_THIS_TEXT_OTHERWISE_YOU_WILL_RUIN_EVERYTHING = "Entity not found";
public static enum SupportedEntityTypes {
MOB(EntityLiving.class),
MINECART(EntityMinecart.class),
ITEM(EntityItem.class),
ITEM_FRAME(EntityItemFrame.class),
PAINTING(EntityPainting.class);
public final Class<? extends Entity> cls;
private SupportedEntityTypes(Class<? extends Entity> cls) {
this.cls = cls;
}
}
@Override
public Class<?> getTargetClass() {
return ISensorEnvironment.class;
}
@Override
public String getSourceId() {
return "openperipheral_sensor";
}
private static AxisAlignedBB getBoundingBox(Vec3 location, double range) {
return AxisAlignedBB.getBoundingBox(
location.xCoord, location.yCoord, location.zCoord,
location.xCoord + 1, location.yCoord + 1, location.zCoord + 1)
.expand(range, range, range);
}
private static AxisAlignedBB getBoundingBox(ISensorEnvironment env) {
return getBoundingBox(env.getLocation(), env.getSensorRange());
}
private static List<Integer> listEntityIds(ISensorEnvironment env, Class<? extends Entity> entityClass) {
List<Integer> ids = Lists.newArrayList();
final AxisAlignedBB aabb = getBoundingBox(env);
for (Entity entity : WorldUtils.getEntitiesWithinAABB(env.getWorld(), entityClass, aabb))
ids.add(entity.getEntityId());
return ids;
}
private static IMetaProviderProxy getEntityInfoById(ISensorEnvironment sensor, int mobId, Class<? extends Entity> cls) {
Entity mob = sensor.getWorld().getEntityByID(mobId);
Preconditions.checkArgument(cls.isInstance(mob), DONT_EVER_CHANGE_THIS_TEXT_OTHERWISE_YOU_WILL_RUIN_EVERYTHING);
return getEntityInfo(sensor, mob);
}
private static IMetaProviderProxy getPlayerInfo(ISensorEnvironment sensor, String username) {
EntityPlayer player = sensor.getWorld().getPlayerEntityByName(username);
return getEntityInfo(sensor, player);
}
private static IMetaProviderProxy getPlayerInfo(ISensorEnvironment sensor, UUID uuid) {
EntityPlayer player = sensor.getWorld().func_152378_a(uuid);
return getEntityInfo(sensor, player);
}
private static IMetaProviderProxy getEntityInfo(ISensorEnvironment sensor, Entity mob) {
Preconditions.checkNotNull(mob, DONT_EVER_CHANGE_THIS_TEXT_OTHERWISE_YOU_WILL_RUIN_EVERYTHING);
final AxisAlignedBB aabb = getBoundingBox(sensor);
Preconditions.checkArgument(mob.boundingBox.intersectsWith(aabb), DONT_EVER_CHANGE_THIS_TEXT_OTHERWISE_YOU_WILL_RUIN_EVERYTHING);
final Vec3 sensorPos = sensor.getLocation();
return ApiAccess.getApi(IEntityPartialMetaBuilder.class).createProxy(mob, sensorPos);
}
@ScriptCallable(returnTypes = ReturnType.OBJECT, description = "Get the ids of all the mobs in range. Deprecated, please use getEntityIds('mob')")
public List<Integer> getMobIds(ISensorEnvironment env) {
return listEntityIds(env, EntityLiving.class);
}
@ScriptCallable(returnTypes = ReturnType.OBJECT, description = "Get full details of a particular mob if it's in range. Deprecated, please use getEntityData(id, 'mob')")
public IMetaProviderProxy getMobData(ISensorEnvironment sensor,
@Arg(name = "mobId", description = "The id retrieved from getMobIds()") int id) {
return getEntityInfoById(sensor, id, EntityLiving.class);
}
@ScriptCallable(returnTypes = ReturnType.OBJECT, description = "Get the ids of all the minecarts in range. Deprecated, please use getEntityIds('minecart')")
public List<Integer> getMinecartIds(ISensorEnvironment env) {
return listEntityIds(env, EntityMinecart.class);
}
@ScriptCallable(returnTypes = ReturnType.OBJECT, description = "Get full details of a particular minecart if it's in range. Deprecated, please use getEntityIds(id, 'minecraft')")
public IMetaProviderProxy getMinecartData(ISensorEnvironment sensor,
@Arg(name = "minecartId", description = "The id retrieved from getMinecartIds()") int id) {
return getEntityInfoById(sensor, id, EntityMinecart.class);
}
@ScriptCallable(returnTypes = ReturnType.OBJECT, description = "Get the ids of all entities of single type in range")
public List<Integer> getEntityIds(ISensorEnvironment env, @Arg(name = "type") SupportedEntityTypes type) {
return listEntityIds(env, type.cls);
}
@ScriptCallable(returnTypes = ReturnType.OBJECT, description = "Get full details of a particular entity if it's in range")
public IMetaProviderProxy getEntityData(ISensorEnvironment sensor,
@Arg(name = "id", description = "The id retrieved from getEntityIds()") int id,
@Arg(name = "type") SupportedEntityTypes type) {
return getEntityInfoById(sensor, id, type.cls);
}
@ScriptCallable(returnTypes = ReturnType.OBJECT, description = "Get the usernames of all the players in range")
public List<GameProfile> getPlayers(ISensorEnvironment env) {
List<EntityPlayer> players = WorldUtils.getEntitiesWithinAABB(env.getWorld(), EntityPlayer.class, getBoundingBox(env));
List<GameProfile> names = Lists.newArrayList();
for (EntityPlayer player : players)
names.add(player.getGameProfile());
return names;
}
@ScriptCallable(returnTypes = ReturnType.OBJECT, description = "Get full details of a particular player if they're in range")
public IMetaProviderProxy getPlayerByName(ISensorEnvironment env,
@Arg(name = "username", description = "The players username") String username) {
return getPlayerInfo(env, username);
}
@ScriptCallable(returnTypes = ReturnType.OBJECT, description = "Get full details of a particular player if they're in range")
public IMetaProviderProxy getPlayerByUUID(ISensorEnvironment env,
@Arg(name = "uuid", description = "The players uuid") UUID uuid) {
return getPlayerInfo(env, uuid);
}
@ScriptCallable(returnTypes = ReturnType.TABLE, description = "Get a table of information about the surrounding area. Includes whether each block is UNKNOWN, AIR, LIQUID or SOLID")
public Map<Integer, Map<String, Object>> sonicScan(ISensorEnvironment env) {
int range = 1 + env.getSensorRange() / 2;
World world = env.getWorld();
Map<Integer, Map<String, Object>> results = Maps.newHashMap();
Vec3 sensorPos = env.getLocation();
int sx = MathHelper.floor_double(sensorPos.xCoord);
int sy = MathHelper.floor_double(sensorPos.yCoord);
int sz = MathHelper.floor_double(sensorPos.zCoord);
final int rangeSq = range * range;
int i = 0;
for (int x = -range; x <= range; x++) {
for (int y = -range; y <= range; y++) {
for (int z = -range; z <= range; z++) {
final int bx = sx + x;
final int by = sy + y;
final int bz = sz + z;
if (!world.blockExists(bx, by, bz)) continue;
final int distSq = x * x + y * y + z * z;
if (distSq == 0 || distSq > rangeSq) continue;
Block block = world.getBlock(bx, by, bz);
String type;
if (block == null || world.isAirBlock(bx, by, bz)) type = "AIR";
else if (block.getMaterial().isLiquid()) type = "LIQUID";
else if (block.getMaterial().isSolid()) type = "SOLID";
else type = "UNKNOWN";
Map<String, Object> tmp = Maps.newHashMap();
tmp.put("x", x);
tmp.put("y", y);
tmp.put("z", z);
tmp.put("type", type);
results.put(++i, tmp);
}
}
}
return results;
}
}
| src/main/java/openperipheral/addons/sensors/AdapterSensor.java | package openperipheral.addons.sensors;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import net.minecraft.block.Block;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.item.EntityMinecart;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.MathHelper;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import openmods.utils.WorldUtils;
import openperipheral.api.ApiAccess;
import openperipheral.api.adapter.IPeripheralAdapter;
import openperipheral.api.adapter.method.Arg;
import openperipheral.api.adapter.method.ReturnType;
import openperipheral.api.adapter.method.ScriptCallable;
import openperipheral.api.meta.IEntityPartialMetaBuilder;
import openperipheral.api.meta.IMetaProviderProxy;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.mojang.authlib.GameProfile;
public class AdapterSensor implements IPeripheralAdapter {
private static final String DONT_EVER_CHANGE_THIS_TEXT_OTHERWISE_YOU_WILL_RUIN_EVERYTHING = "Entity not found";
@Override
public Class<?> getTargetClass() {
return ISensorEnvironment.class;
}
@Override
public String getSourceId() {
return "openperipheral_sensor";
}
private static AxisAlignedBB getBoundingBox(Vec3 location, double range) {
return AxisAlignedBB.getBoundingBox(
location.xCoord, location.yCoord, location.zCoord,
location.xCoord + 1, location.yCoord + 1, location.zCoord + 1)
.expand(range, range, range);
}
private static AxisAlignedBB getBoundingBox(ISensorEnvironment env) {
return getBoundingBox(env.getLocation(), env.getSensorRange());
}
private static List<Integer> listEntityIds(ISensorEnvironment env, Class<? extends Entity> entityClass) {
List<Integer> ids = Lists.newArrayList();
final AxisAlignedBB aabb = getBoundingBox(env);
for (Entity entity : WorldUtils.getEntitiesWithinAABB(env.getWorld(), entityClass, aabb))
ids.add(entity.getEntityId());
return ids;
}
private static IMetaProviderProxy getEntityInfoById(ISensorEnvironment sensor, int mobId) {
Entity mob = sensor.getWorld().getEntityByID(mobId);
return getEntityInfo(sensor, mob);
}
private static IMetaProviderProxy getPlayerInfo(ISensorEnvironment sensor, String username) {
EntityPlayer player = sensor.getWorld().getPlayerEntityByName(username);
return getEntityInfo(sensor, player);
}
private static IMetaProviderProxy getPlayerInfo(ISensorEnvironment sensor, UUID uuid) {
EntityPlayer player = sensor.getWorld().func_152378_a(uuid);
return getEntityInfo(sensor, player);
}
protected static IMetaProviderProxy getEntityInfo(ISensorEnvironment sensor, Entity mob) {
Preconditions.checkNotNull(mob, DONT_EVER_CHANGE_THIS_TEXT_OTHERWISE_YOU_WILL_RUIN_EVERYTHING);
final AxisAlignedBB aabb = getBoundingBox(sensor);
Preconditions.checkArgument(mob.boundingBox.intersectsWith(aabb), DONT_EVER_CHANGE_THIS_TEXT_OTHERWISE_YOU_WILL_RUIN_EVERYTHING);
final Vec3 sensorPos = sensor.getLocation();
return ApiAccess.getApi(IEntityPartialMetaBuilder.class).createProxy(mob, sensorPos);
}
@ScriptCallable(returnTypes = ReturnType.OBJECT, description = "Get the usernames of all the players in range")
public List<GameProfile> getPlayers(ISensorEnvironment env) {
List<EntityPlayer> players = WorldUtils.getEntitiesWithinAABB(env.getWorld(), EntityPlayer.class, getBoundingBox(env));
List<GameProfile> names = Lists.newArrayList();
for (EntityPlayer player : players)
names.add(player.getGameProfile());
return names;
}
@ScriptCallable(returnTypes = ReturnType.OBJECT, description = "Get the ids of all the mobs in range")
public List<Integer> getMobIds(ISensorEnvironment env) {
return listEntityIds(env, EntityLiving.class);
}
@ScriptCallable(returnTypes = ReturnType.OBJECT, description = "Get the ids of all the minecarts in range")
public List<Integer> getMinecartIds(ISensorEnvironment env) {
return listEntityIds(env, EntityMinecart.class);
}
@ScriptCallable(returnTypes = ReturnType.OBJECT, description = "Get full details of a particular player if they're in range")
public IMetaProviderProxy getPlayerByName(ISensorEnvironment env,
@Arg(name = "username", description = "The players username") String username) {
return getPlayerInfo(env, username);
}
@ScriptCallable(returnTypes = ReturnType.OBJECT, description = "Get full details of a particular player if they're in range")
public IMetaProviderProxy getPlayerByUUID(ISensorEnvironment env,
@Arg(name = "uuid", description = "The players uuid") UUID uuid) {
return getPlayerInfo(env, uuid);
}
@ScriptCallable(returnTypes = ReturnType.OBJECT, description = "Get full details of a particular mob if it's in range")
public IMetaProviderProxy getMobData(ISensorEnvironment sensor,
@Arg(name = "mobId", description = "The mob id retrieved from getMobIds()") int mobId) {
return getEntityInfoById(sensor, mobId);
}
@ScriptCallable(returnTypes = ReturnType.OBJECT, description = "Get full details of a particular minecart if it's in range")
public IMetaProviderProxy getMinecartData(ISensorEnvironment sensor,
@Arg(name = "minecartId", description = "The minecart id retrieved from getMobIds()") int minecartId) {
return getEntityInfoById(sensor, minecartId);
}
@ScriptCallable(returnTypes = ReturnType.TABLE, description = "Get a table of information about the surrounding area. Includes whether each block is UNKNOWN, AIR, LIQUID or SOLID")
public Map<Integer, Map<String, Object>> sonicScan(ISensorEnvironment env) {
int range = 1 + env.getSensorRange() / 2;
World world = env.getWorld();
Map<Integer, Map<String, Object>> results = Maps.newHashMap();
Vec3 sensorPos = env.getLocation();
int sx = MathHelper.floor_double(sensorPos.xCoord);
int sy = MathHelper.floor_double(sensorPos.yCoord);
int sz = MathHelper.floor_double(sensorPos.zCoord);
final int rangeSq = range * range;
int i = 0;
for (int x = -range; x <= range; x++) {
for (int y = -range; y <= range; y++) {
for (int z = -range; z <= range; z++) {
final int bx = sx + x;
final int by = sy + y;
final int bz = sz + z;
if (!world.blockExists(bx, by, bz)) continue;
final int distSq = x * x + y * y + z * z;
if (distSq == 0 || distSq > rangeSq) continue;
Block block = world.getBlock(bx, by, bz);
String type;
if (block == null || world.isAirBlock(bx, by, bz)) type = "AIR";
else if (block.getMaterial().isLiquid()) type = "LIQUID";
else if (block.getMaterial().isSolid()) type = "SOLID";
else type = "UNKNOWN";
Map<String, Object> tmp = Maps.newHashMap();
tmp.put("x", x);
tmp.put("y", y);
tmp.put("z", z);
tmp.put("type", type);
results.put(++i, tmp);
}
}
}
return results;
}
}
| Add new entity types to sensor
| src/main/java/openperipheral/addons/sensors/AdapterSensor.java | Add new entity types to sensor |
|
Java | agpl-3.0 | dba3033dcff6d3acfcb5bc04aab16f9e63ee1a6f | 0 | splicemachine/spliceengine,CompilerWorks/spliceengine,CompilerWorks/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine,CompilerWorks/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine,CompilerWorks/spliceengine,CompilerWorks/spliceengine,CompilerWorks/spliceengine | package org.apache.derby.impl.sql.execute.operations;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.splicemachine.derby.test.framework.*;
import com.splicemachine.homeless.TestUtils;
import org.apache.log4j.Logger;
import org.junit.Assert;
import org.junit.ClassRule;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import static com.splicemachine.homeless.TestUtils.executeSql;
import static com.splicemachine.homeless.TestUtils.o;
public class DistinctGroupedAggregateOperationIT extends SpliceUnitTest {
public static final String CLASS_NAME = DistinctGroupedAggregateOperationIT.class.getSimpleName().toUpperCase();
protected static SpliceWatcher spliceClassWatcher = new DefaultedSpliceWatcher(CLASS_NAME);
public static final String TABLE_NAME_1 = "A";
private static Logger LOG = Logger.getLogger(DistinctGroupedAggregateOperationIT.class);
protected static SpliceSchemaWatcher spliceSchemaWatcher = new SpliceSchemaWatcher(CLASS_NAME);
protected static SpliceTableWatcher spliceTableWatcher = new SpliceTableWatcher(TABLE_NAME_1,CLASS_NAME,"(oid int, quantity int)");
@ClassRule
public static TestRule chain = RuleChain.outerRule(spliceClassWatcher)
.around(spliceSchemaWatcher)
.around(spliceTableWatcher)
.around(new SpliceDataWatcher(){
@Override
protected void starting(Description description) {
try {
Statement s = spliceClassWatcher.getStatement();
s.execute(format("insert into %s.%s values(1, 5)",CLASS_NAME,TABLE_NAME_1));
s.execute(format("insert into %s.%s values(2, 2)",CLASS_NAME,TABLE_NAME_1));
s.execute(format("insert into %s.%s values(2, 1)",CLASS_NAME,TABLE_NAME_1));
s.execute(format("insert into %s.%s values(3, 10)",CLASS_NAME,TABLE_NAME_1));
s.execute(format("insert into %s.%s values(3, 5)",CLASS_NAME,TABLE_NAME_1));
s.execute(format("insert into %s.%s values(3, 1)",CLASS_NAME,TABLE_NAME_1));
s.execute(format("insert into %s.%s values(3, 1)",CLASS_NAME,TABLE_NAME_1));
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
finally {
spliceClassWatcher.closeAll();
}
}
})
.around(TestUtils
.createStringDataWatcher(spliceClassWatcher,
"create table t1 (c1 int, c2 int); " +
"insert into t1 values (null, null), (1,1), " +
"(null, null), (2,1), (3,1), (10,10);",
CLASS_NAME));
public SpliceWatcher methodWatcher = new DefaultedSpliceWatcher(CLASS_NAME);
@Test
public void testMultipleDistinctAggregates() throws Exception {
ResultSet rs = methodWatcher.executeQuery(format("select oid, sum(distinct quantity) as summation,count(distinct quantity) as count from %s group by oid",this.getTableReference(TABLE_NAME_1)));
int j = 0;
Set<Integer> correctOids = Sets.newHashSet(1,2,3);
Map<Integer,Integer> correctSums = Maps.newHashMap();
correctSums.put(1,5);
correctSums.put(2,3);
correctSums.put(3,16);
Map<Integer,Integer> correctCounts = Maps.newHashMap();
correctCounts.put(1,1);
correctCounts.put(2,2);
correctCounts.put(3,3);
while (rs.next()) {
int oid = rs.getInt(1);
Assert.assertTrue("Duplicate row for oid "+ oid,correctOids.contains(oid));
correctOids.remove(oid);
int sum = rs.getInt(2);
Assert.assertEquals("Incorrect sum for oid "+ oid,correctSums.get(oid).intValue(),sum);
int count = rs.getInt(3);
Assert.assertEquals("Incorrect count for oid "+ oid,correctCounts.get(oid).intValue(),count);
j++;
}
Assert.assertEquals("Incorrect row count!",3,j);
Assert.assertEquals("Incorrect number of oids returned!",0,correctOids.size());
}
@Test
public void testDistinctGroupedAggregate() throws Exception {
ResultSet rs = methodWatcher.executeQuery(format("select oid, sum(distinct quantity) as summation from %s group by oid",this.getTableReference(TABLE_NAME_1)));
int j = 0;
Set<Integer> correctOids = Sets.newHashSet(1,2,3);
Map<Integer,Integer> correctSums = Maps.newHashMap();
correctSums.put(1,5);
correctSums.put(2,3);
correctSums.put(3,16);
while (rs.next()) {
int oid = rs.getInt(1);
Assert.assertTrue("Duplicate row for oid "+ oid,correctOids.contains(oid));
correctOids.remove(oid);
int sum = rs.getInt(2);
Assert.assertEquals("Incorrect sum for oid "+ oid,correctSums.get(oid).intValue(),sum);
j++;
}
Assert.assertEquals("Incorrect row count!",3,j);
Assert.assertEquals("Incorrect number of oids returned!",0,correctOids.size());
}
@Ignore("DB-1277")
@Test
public void testDistinctAndNonDistinctAggregate() throws Exception {
List<Object[]> sumExpected = Arrays.asList(new Object[]{null}, o(6L), o(10L));
List<Object[]> sumRows = TestUtils.resultSetToArrays(methodWatcher.executeQuery("select sum(c1) " +
"from t1 group by c2 " +
"order by 1"));
Assert.assertArrayEquals(sumExpected.toArray(), sumRows.toArray());
List<Object[]> sumDistinctExpected = Arrays.asList(new Object[]{null}, o(6L), o(10L));
List<Object[]> sumDistinctRows = TestUtils
.resultSetToArrays(methodWatcher.executeQuery("select sum(distinct c1) " +
"from t1 group by c2 " +
"order by 1"));
Assert.assertArrayEquals(sumDistinctExpected.toArray(), sumDistinctRows.toArray());
List<Object[]> bothSumsExpected = Arrays.asList(o(null, null), o(6L, 6L), o(10L, 10L));
List<Object[]> bothSumsRows = TestUtils
.resultSetToArrays(methodWatcher.executeQuery("select sum(distinct c1), " +
"sum(c1) " +
"from t1 group by c2 " +
"order by 1"));
for (Object[] o: bothSumsRows){
System.out.println(Arrays.toString(o));
}
Assert.assertArrayEquals(bothSumsExpected.toArray(), bothSumsRows.toArray());
}
}
| structured_derby/src/test/java/org/apache/derby/impl/sql/execute/operations/DistinctGroupedAggregateOperationIT.java | package org.apache.derby.impl.sql.execute.operations;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.splicemachine.derby.test.framework.*;
import com.splicemachine.homeless.TestUtils;
import org.apache.log4j.Logger;
import org.junit.Assert;
import org.junit.ClassRule;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import static com.splicemachine.homeless.TestUtils.executeSql;
import static com.splicemachine.homeless.TestUtils.o;
public class DistinctGroupedAggregateOperationIT extends SpliceUnitTest {
public static final String CLASS_NAME = DistinctGroupedAggregateOperationIT.class.getSimpleName().toUpperCase();
protected static SpliceWatcher spliceClassWatcher = new DefaultedSpliceWatcher(CLASS_NAME);
public static final String TABLE_NAME_1 = "A";
private static Logger LOG = Logger.getLogger(DistinctGroupedAggregateOperationIT.class);
protected static SpliceSchemaWatcher spliceSchemaWatcher = new SpliceSchemaWatcher(CLASS_NAME);
protected static SpliceTableWatcher spliceTableWatcher = new SpliceTableWatcher(TABLE_NAME_1,CLASS_NAME,"(oid int, quantity int)");
@ClassRule
public static TestRule chain = RuleChain.outerRule(spliceClassWatcher)
.around(spliceSchemaWatcher)
.around(spliceTableWatcher)
.around(new SpliceDataWatcher(){
@Override
protected void starting(Description description) {
try {
Statement s = spliceClassWatcher.getStatement();
s.execute(format("insert into %s.%s values(1, 5)",CLASS_NAME,TABLE_NAME_1));
s.execute(format("insert into %s.%s values(2, 2)",CLASS_NAME,TABLE_NAME_1));
s.execute(format("insert into %s.%s values(2, 1)",CLASS_NAME,TABLE_NAME_1));
s.execute(format("insert into %s.%s values(3, 10)",CLASS_NAME,TABLE_NAME_1));
s.execute(format("insert into %s.%s values(3, 5)",CLASS_NAME,TABLE_NAME_1));
s.execute(format("insert into %s.%s values(3, 1)",CLASS_NAME,TABLE_NAME_1));
s.execute(format("insert into %s.%s values(3, 1)",CLASS_NAME,TABLE_NAME_1));
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
finally {
spliceClassWatcher.closeAll();
}
}
})
.around(TestUtils
.createStringDataWatcher(spliceClassWatcher,
"create table t1 (c1 int, c2 int); " +
"insert into t1 values (null, null), (1,1), " +
"(null, null), (2,1), (3,1), (10,10);",
CLASS_NAME));
public SpliceWatcher methodWatcher = new DefaultedSpliceWatcher(CLASS_NAME);
@Test
public void testMultipleDistinctAggregates() throws Exception {
ResultSet rs = methodWatcher.executeQuery(format("select oid, sum(distinct quantity) as summation,count(distinct quantity) as count from %s group by oid",this.getTableReference(TABLE_NAME_1)));
int j = 0;
Set<Integer> correctOids = Sets.newHashSet(1,2,3);
Map<Integer,Integer> correctSums = Maps.newHashMap();
correctSums.put(1,5);
correctSums.put(2,3);
correctSums.put(3,16);
Map<Integer,Integer> correctCounts = Maps.newHashMap();
correctCounts.put(1,1);
correctCounts.put(2,2);
correctCounts.put(3,3);
while (rs.next()) {
int oid = rs.getInt(1);
Assert.assertTrue("Duplicate row for oid "+ oid,correctOids.contains(oid));
correctOids.remove(oid);
int sum = rs.getInt(2);
Assert.assertEquals("Incorrect sum for oid "+ oid,correctSums.get(oid).intValue(),sum);
int count = rs.getInt(3);
Assert.assertEquals("Incorrect count for oid "+ oid,correctCounts.get(oid).intValue(),count);
j++;
}
Assert.assertEquals("Incorrect row count!",3,j);
Assert.assertEquals("Incorrect number of oids returned!",0,correctOids.size());
}
@Test
public void testDistinctGroupedAggregate() throws Exception {
ResultSet rs = methodWatcher.executeQuery(format("select oid, sum(distinct quantity) as summation from %s group by oid",this.getTableReference(TABLE_NAME_1)));
int j = 0;
Set<Integer> correctOids = Sets.newHashSet(1,2,3);
Map<Integer,Integer> correctSums = Maps.newHashMap();
correctSums.put(1,5);
correctSums.put(2,3);
correctSums.put(3,16);
while (rs.next()) {
int oid = rs.getInt(1);
Assert.assertTrue("Duplicate row for oid "+ oid,correctOids.contains(oid));
correctOids.remove(oid);
int sum = rs.getInt(2);
Assert.assertEquals("Incorrect sum for oid "+ oid,correctSums.get(oid).intValue(),sum);
j++;
}
Assert.assertEquals("Incorrect row count!",3,j);
Assert.assertEquals("Incorrect number of oids returned!",0,correctOids.size());
}
//@Ignore("DB-1277")
@Test
public void testDistinctAndNonDistinctAggregate() throws Exception {
List<Object[]> sumExpected = Arrays.asList(new Object[]{null}, o(6L), o(10L));
List<Object[]> sumRows = TestUtils.resultSetToArrays(methodWatcher.executeQuery("select sum(c1) " +
"from t1 group by c2 " +
"order by 1"));
Assert.assertArrayEquals(sumExpected.toArray(), sumRows.toArray());
List<Object[]> sumDistinctExpected = Arrays.asList(new Object[]{null}, o(6L), o(10L));
List<Object[]> sumDistinctRows = TestUtils
.resultSetToArrays(methodWatcher.executeQuery("select sum(distinct c1) " +
"from t1 group by c2 " +
"order by 1"));
Assert.assertArrayEquals(sumDistinctExpected.toArray(), sumDistinctRows.toArray());
List<Object[]> bothSumsExpected = Arrays.asList(o(null, null), o(6L, 6L), o(10L, 10L));
List<Object[]> bothSumsRows = TestUtils
.resultSetToArrays(methodWatcher.executeQuery("select sum(distinct c1), " +
"sum(c1) " +
"from t1 group by c2 " +
"order by 1"));
for (Object[] o: bothSumsRows){
System.out.println(Arrays.toString(o));
}
Assert.assertArrayEquals(bothSumsExpected.toArray(), bothSumsRows.toArray());
}
}
| DB-1277 Ignore IT until ORDER BY problem identified
| structured_derby/src/test/java/org/apache/derby/impl/sql/execute/operations/DistinctGroupedAggregateOperationIT.java | DB-1277 Ignore IT until ORDER BY problem identified |
|
Java | agpl-3.0 | d107dca359db39cfb6f4818d85d5811fb4abd042 | 0 | elki-project/elki,elki-project/elki,elki-project/elki | package de.lmu.ifi.dbs.elki.algorithm.outlier.trivial;
import java.util.HashSet;
import de.lmu.ifi.dbs.elki.algorithm.AbstractAlgorithm;
import de.lmu.ifi.dbs.elki.algorithm.outlier.OutlierAlgorithm;
import de.lmu.ifi.dbs.elki.data.NumberVector;
import de.lmu.ifi.dbs.elki.data.model.GeneratorModel;
import de.lmu.ifi.dbs.elki.data.model.Model;
import de.lmu.ifi.dbs.elki.data.type.NoSupportedDataTypeException;
import de.lmu.ifi.dbs.elki.data.type.SimpleTypeInformation;
import de.lmu.ifi.dbs.elki.data.type.TypeInformation;
import de.lmu.ifi.dbs.elki.data.type.TypeUtil;
import de.lmu.ifi.dbs.elki.database.Database;
import de.lmu.ifi.dbs.elki.database.datastore.DataStoreFactory;
import de.lmu.ifi.dbs.elki.database.datastore.DataStoreUtil;
import de.lmu.ifi.dbs.elki.database.datastore.WritableDataStore;
import de.lmu.ifi.dbs.elki.database.ids.DBID;
import de.lmu.ifi.dbs.elki.database.relation.MaterializedRelation;
import de.lmu.ifi.dbs.elki.database.relation.Relation;
import de.lmu.ifi.dbs.elki.logging.Logging;
import de.lmu.ifi.dbs.elki.math.linearalgebra.Vector;
import de.lmu.ifi.dbs.elki.math.statistics.distribution.ChiSquaredDistribution;
import de.lmu.ifi.dbs.elki.math.statistics.distribution.Distribution;
import de.lmu.ifi.dbs.elki.math.statistics.distribution.NormalDistribution;
import de.lmu.ifi.dbs.elki.result.outlier.OutlierResult;
import de.lmu.ifi.dbs.elki.result.outlier.OutlierScoreMeta;
import de.lmu.ifi.dbs.elki.result.outlier.ProbabilisticOutlierScore;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.AbstractParameterizer;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.OptionID;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameterization.Parameterization;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.parameters.DoubleParameter;
/**
* Extract outlier score from the model the objects were generated by.
*
* This algorithm can only be applied to data that was freshly generated, to the
* generator model information is still available.
*
* @author Erich Schubert
*/
public class TrivialGeneratedOutlier extends AbstractAlgorithm<OutlierResult> implements OutlierAlgorithm {
/**
* Class logger
*/
private static final Logging logger = Logging.getLogger(TrivialGeneratedOutlier.class);
/**
* Expected share of outliers
*/
public static final OptionID EXPECT_ID = OptionID.getOrCreateOptionID("modeloutlier.expect", "Expected amount of outliers, for making the scores more intuitive.");
/**
* Expected share of outliers.
*/
double expect = 0.01;
/**
* Constructor.
*
* @param expect Expected share of outliers
*/
public TrivialGeneratedOutlier(double expect) {
super();
this.expect = expect;
}
/**
* Constructor.
*/
public TrivialGeneratedOutlier() {
this(0.01);
}
@Override
public TypeInformation[] getInputTypeRestriction() {
return TypeUtil.array(TypeUtil.NUMBER_VECTOR_FIELD, new SimpleTypeInformation<Model>(Model.class), TypeUtil.GUESSED_LABEL);
}
@Override
public OutlierResult run(Database database) throws IllegalStateException {
Relation<NumberVector<?, ?>> vecs = database.getRelation(TypeUtil.NUMBER_VECTOR_FIELD);
Relation<Model> models = database.getRelation(new SimpleTypeInformation<Model>(Model.class));
// Prefer a true class label
try {
Relation<?> relation = database.getRelation(TypeUtil.CLASSLABEL);
return run(models, vecs, relation);
}
catch(NoSupportedDataTypeException e) {
// Otherwise, try any labellike.
return run(models, vecs, database.getRelation(TypeUtil.GUESSED_LABEL));
}
}
/**
* Run the algorithm
*
* @param models Model relation
* @param vecs Vector relation
* @param labels Label relation
* @return Outlier result
*/
public OutlierResult run(Relation<Model> models, Relation<NumberVector<?, ?>> vecs, Relation<?> labels) {
WritableDataStore<Double> scores = DataStoreUtil.makeStorage(models.getDBIDs(), DataStoreFactory.HINT_HOT, Double.class);
HashSet<GeneratorModel> generators = new HashSet<GeneratorModel>();
for(DBID id : models.iterDBIDs()) {
Model model = models.get(id);
if(model instanceof GeneratorModel) {
generators.add((GeneratorModel) model);
}
}
if(generators.size() == 0) {
logger.warning("No generator models found for dataset - all points will be considered outliers.");
}
for(DBID id : models.iterDBIDs()) {
double score = 0.0;
// Convert to a math vector
Vector v = vecs.get(id).getColumnVector();
for(GeneratorModel gen : generators) {
Vector tv = v;
// Transform backwards
if(gen.getTransform() != null) {
tv = gen.getTransform().applyInverse(v);
}
final int dim = tv.getDimensionality();
double lensq = 0.0;
int norm = 0;
for(int i = 0; i < dim; i++) {
Distribution dist = gen.getDistribution(i);
if(dist instanceof NormalDistribution) {
NormalDistribution d = (NormalDistribution) dist;
double delta = (tv.get(i) - d.getMean()) / d.getStddev();
lensq += delta * delta;
norm += 1;
}
}
if(norm > 0) {
// The squared distances are ChiSquared distributed
score = Math.max(score, 1 - ChiSquaredDistribution.cdf(lensq, norm));
}
}
// score inversion.
score = expect / (expect + score);
scores.put(id, score);
}
Relation<Double> scoreres = new MaterializedRelation<Double>("Model outlier scores", "model-outlier", TypeUtil.DOUBLE, scores, models.getDBIDs());
OutlierScoreMeta meta = new ProbabilisticOutlierScore(0., 1.);
return new OutlierResult(meta, scoreres);
}
@Override
protected Logging getLogger() {
return logger;
}
/**
* Parameterization class.
*
* @author Erich Schubert
*
* @apiviz.exclude
*/
public static class Parameterizer extends AbstractParameterizer {
/**
* Expected share of outliers
*/
double expect;
@Override
protected void makeOptions(Parameterization config) {
super.makeOptions(config);
DoubleParameter expectP = new DoubleParameter(EXPECT_ID, 0.01);
if(config.grab(expectP)) {
expect = expectP.getValue();
}
}
@Override
protected TrivialGeneratedOutlier makeInstance() {
return new TrivialGeneratedOutlier(expect);
}
}
} | src/de/lmu/ifi/dbs/elki/algorithm/outlier/trivial/TrivialGeneratedOutlier.java | package de.lmu.ifi.dbs.elki.algorithm.outlier.trivial;
import java.util.HashSet;
import java.util.regex.Pattern;
import de.lmu.ifi.dbs.elki.algorithm.AbstractAlgorithm;
import de.lmu.ifi.dbs.elki.algorithm.outlier.OutlierAlgorithm;
import de.lmu.ifi.dbs.elki.data.NumberVector;
import de.lmu.ifi.dbs.elki.data.model.GeneratorModel;
import de.lmu.ifi.dbs.elki.data.model.Model;
import de.lmu.ifi.dbs.elki.data.type.NoSupportedDataTypeException;
import de.lmu.ifi.dbs.elki.data.type.SimpleTypeInformation;
import de.lmu.ifi.dbs.elki.data.type.TypeInformation;
import de.lmu.ifi.dbs.elki.data.type.TypeUtil;
import de.lmu.ifi.dbs.elki.database.Database;
import de.lmu.ifi.dbs.elki.database.datastore.DataStoreFactory;
import de.lmu.ifi.dbs.elki.database.datastore.DataStoreUtil;
import de.lmu.ifi.dbs.elki.database.datastore.WritableDataStore;
import de.lmu.ifi.dbs.elki.database.ids.DBID;
import de.lmu.ifi.dbs.elki.database.relation.MaterializedRelation;
import de.lmu.ifi.dbs.elki.database.relation.Relation;
import de.lmu.ifi.dbs.elki.logging.Logging;
import de.lmu.ifi.dbs.elki.math.linearalgebra.Vector;
import de.lmu.ifi.dbs.elki.math.statistics.distribution.ChiSquaredDistribution;
import de.lmu.ifi.dbs.elki.math.statistics.distribution.Distribution;
import de.lmu.ifi.dbs.elki.math.statistics.distribution.NormalDistribution;
import de.lmu.ifi.dbs.elki.result.outlier.OutlierResult;
import de.lmu.ifi.dbs.elki.result.outlier.OutlierScoreMeta;
import de.lmu.ifi.dbs.elki.result.outlier.ProbabilisticOutlierScore;
/**
* Extract outlier score from the model the objects were generated by.
*
* This algorithm can only be applied to data that was freshly generated, to the
* generator model information is still available.
*
* @author Erich Schubert
*/
public class TrivialGeneratedOutlier extends AbstractAlgorithm<OutlierResult> implements OutlierAlgorithm {
/**
* Class logger
*/
private static final Logging logger = Logging.getLogger(TrivialGeneratedOutlier.class);
/**
* The pattern we match with.
*/
final Pattern pattern;
/**
* Constructor.
*
* @param pattern Pattern to match with.
*/
public TrivialGeneratedOutlier(Pattern pattern) {
super();
this.pattern = pattern;
}
/**
* Constructor.
*/
public TrivialGeneratedOutlier() {
this(Pattern.compile(ByLabelOutlier.DEFAULT_PATTERN));
}
@Override
public TypeInformation[] getInputTypeRestriction() {
return TypeUtil.array(TypeUtil.NUMBER_VECTOR_FIELD, new SimpleTypeInformation<Model>(Model.class), TypeUtil.GUESSED_LABEL);
}
@Override
public OutlierResult run(Database database) throws IllegalStateException {
Relation<NumberVector<?, ?>> vecs = database.getRelation(TypeUtil.NUMBER_VECTOR_FIELD);
Relation<Model> models = database.getRelation(new SimpleTypeInformation<Model>(Model.class));
// Prefer a true class label
try {
Relation<?> relation = database.getRelation(TypeUtil.CLASSLABEL);
return run(models, vecs, relation);
}
catch(NoSupportedDataTypeException e) {
// Otherwise, try any labellike.
return run(models, vecs, database.getRelation(TypeUtil.GUESSED_LABEL));
}
}
/**
* Run the algorithm
*
* @param models Model relation
* @param vecs Vector relation
* @param labels Label relation
* @return Outlier result
*/
public OutlierResult run(Relation<Model> models, Relation<NumberVector<?, ?>> vecs, Relation<?> labels) {
WritableDataStore<Double> scores = DataStoreUtil.makeStorage(models.getDBIDs(), DataStoreFactory.HINT_HOT, Double.class);
HashSet<GeneratorModel> generators = new HashSet<GeneratorModel>();
for(DBID id : models.iterDBIDs()) {
Model model = models.get(id);
if(model instanceof GeneratorModel) {
generators.add((GeneratorModel) model);
}
}
if(generators.size() == 0) {
logger.warning("No generator models found for dataset - all points will be considered outliers.");
}
for(DBID id : models.iterDBIDs()) {
double score = 1.0;
// Convert to a math vector
Vector v = vecs.get(id).getColumnVector();
for(GeneratorModel gen : generators) {
Vector tv = v;
// Transform backwards
if(gen.getTransform() != null) {
tv = gen.getTransform().applyInverse(v);
}
final int dim = tv.getDimensionality();
double lensq = 0.0;
int norm = 0;
for(int i = 0; i < dim; i++) {
Distribution dist = gen.getDistribution(i);
if(dist instanceof NormalDistribution) {
NormalDistribution d = (NormalDistribution) dist;
double delta = (tv.get(i) - d.getMean()) / d.getStddev();
lensq += delta * delta;
norm += 1;
}
}
if(norm > 0) {
// The squared distances are ChiSquared distributed
score = Math.min(score, ChiSquaredDistribution.cdf(lensq, norm));
}
// Estimate probability
// double like = 1.0;
// for(int i = 0; i < tv.getDimensionality(); i++) {
// like *= gen.getDistribution(i).pdf(tv.get(i));
// }
// Adjust for dimensionaliy - geometric mean
// like = Math.pow(like, 1. / tv.getDimensionality());
// if (like > 0) {
// score = Math.min(score, (2 / like) / (like + 1 / like));
// }
}
scores.put(id, score);
}
Relation<Double> scoreres = new MaterializedRelation<Double>("Model outlier scores", "model-outlier", TypeUtil.DOUBLE, scores, models.getDBIDs());
OutlierScoreMeta meta = new ProbabilisticOutlierScore(0., 1.);
return new OutlierResult(meta, scoreres);
}
@Override
protected Logging getLogger() {
return logger;
}
}
| New, improved scaling.
| src/de/lmu/ifi/dbs/elki/algorithm/outlier/trivial/TrivialGeneratedOutlier.java | New, improved scaling. |
|
Java | agpl-3.0 | fa11c36d9ac16ff1990c621f43f7de6d512556dd | 0 | duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test | c12b5f56-2e61-11e5-9284-b827eb9e62be | hello.java | c125e79c-2e61-11e5-9284-b827eb9e62be | c12b5f56-2e61-11e5-9284-b827eb9e62be | hello.java | c12b5f56-2e61-11e5-9284-b827eb9e62be |
|
Java | lgpl-2.1 | 5a11482e5eb2682f32a5e243fac2e223218c3a52 | 0 | open-eid/digidoc4j,open-eid/digidoc4j,open-eid/digidoc4j | package org.digidoc4j.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public final class ResourceUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(ResourceUtils.class);
public static boolean isResourceAccessible(String path) {
try {
return ResourceUtils.class.getClassLoader().getResource(path) != null;
} catch (RuntimeException e) {
LOGGER.debug("Failed to acquire resource URL for path: " + path, e);
return false;
}
}
public static boolean isFileReadable(String path) {
try {
Path pathToFile = Paths.get(path);
return Files.isRegularFile(pathToFile) && Files.isReadable(pathToFile);
} catch (RuntimeException e) {
LOGGER.debug("Failed to check if path exists as a regular file and is readable: " + path, e);
return false;
}
}
private ResourceUtils() {}
}
| digidoc4j/src/main/java/org/digidoc4j/utils/ResourceUtils.java | package org.digidoc4j.utils;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public final class ResourceUtils {
public static boolean isResourceAccessible(String path) {
try {
return ResourceUtils.class.getClassLoader().getResource(path) != null;
} catch (RuntimeException e) {
return false;
}
}
public static boolean isFileReadable(String path) {
try {
Path pathToFile = Paths.get(path);
return Files.isRegularFile(pathToFile) && Files.isReadable(pathToFile);
} catch (RuntimeException e) {
return false;
}
}
private ResourceUtils() {}
}
| DD4J-332 Added debug logging for ResourceUtils on failures
| digidoc4j/src/main/java/org/digidoc4j/utils/ResourceUtils.java | DD4J-332 Added debug logging for ResourceUtils on failures |
|
Java | lgpl-2.1 | 552f747694885fc366393bdea4b49a60fb494a8c | 0 | samskivert/samskivert,samskivert/samskivert | //
// $Id: ComboButtonBox.java,v 1.2 2002/03/10 05:27:35 mdb Exp $
package com.samskivert.swing;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.border.Border;
import javax.swing.BorderFactory;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import com.samskivert.Log;
/**
* Used to display a horizontal or vertical array of buttons, out of which
* only one is selectable at a time (which will be represented by
* rendering it with an indented border, whereas the other buttons will
* render with an extruded border.
*/
public class ComboButtonBox extends JPanel
implements SwingConstants, ListDataListener, MouseListener
{
/**
* Constructs a button box with the specified orientation (either
* {@link #HORIZONTAL} or {@link #VERTICAL}.
*/
public ComboButtonBox (int orientation)
{
this(orientation, new DefaultComboBoxModel());
}
/**
* Constructs a button box with the specified orientation (either
* {@link #HORIZONTAL} or {@link #VERTICAL}. The supplied model will
* be used to populate the buttons (see {@link #setModel} for more
* details).
*/
public ComboButtonBox (int orientation, ComboBoxModel model)
{
// set up our layout
setOrientation(orientation);
// set up our contents
setModel(model);
}
/**
* Sets the orientation of the box (either {@link #HORIZONTAL} or
* {@link #VERTICAL}.
*/
public void setOrientation (int orientation)
{
GroupLayout gl = (orientation == HORIZONTAL) ?
(GroupLayout)new HGroupLayout() : new VGroupLayout();
gl.setPolicy(GroupLayout.EQUALIZE);
setLayout(gl);
}
/**
* Provides the button box with a data model which it will display. If
* the model contains {@link Image} objects, they will be used to make
* icons for the buttons. Otherwise the button text will contain the
* string representation of the elements in the model.
*/
public void setModel (ComboBoxModel model)
{
// if we had a previous model, unregister ourselves from it
if (_model != null) {
_model.removeListDataListener(this);
}
// subscribe to our new model
_model = model;
_model.addListDataListener(this);
// rebuild the list
removeAll();
addButtons(0, _model.getSize());
}
/**
* Returns the model in use by the button box.
*/
public ComboBoxModel getModel ()
{
return _model;
}
/**
* Sets the index of the selected component. A value of -1 will clear
* the selection.
*/
public void setSelectedIndex (int selidx)
{
// update the display
updateSelection(selidx);
// let the model know what's up
Object item = (selidx == -1) ? null : _model.getElementAt(selidx);
_model.setSelectedItem(item);
}
/**
* Returns the index of the selected item.
*/
public int getSelectedIndex ()
{
return _selectedIndex;
}
/**
* Specifies the command that will be used when generating action
* events (which is done when the selection changes).
*/
public void setActionCommand (String actionCommand)
{
_actionCommand = actionCommand;
}
/**
* Adds a listener to our list of entities to be notified when the
* selection changes.
*/
public void addActionListener (ActionListener l)
{
listenerList.add(ActionListener.class, l);
}
/**
* Removes a listener from the list.
*/
public void removeActionListener (ActionListener l)
{
listenerList.remove(ActionListener.class, l);
}
/**
* Notifies our listeners when the selection changed.
*/
protected void fireActionPerformed ()
{
// guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// process the listeners last to first, notifying those that are
// interested in this event
for (int i = listeners.length-2; i >= 0; i -= 2) {
if (listeners[i] == ActionListener.class) {
// lazily create the event:
if (_actionEvent == null) {
_actionEvent = new ActionEvent(
this, ActionEvent.ACTION_PERFORMED, _actionCommand);
}
((ActionListener)listeners[i+1]).actionPerformed(_actionEvent);
}
}
}
// documentation inherited from interface
public void contentsChanged (ListDataEvent e)
{
// if this update is informing us of a new selection, reflect that
// in the UI
int start = e.getIndex0(), count = start - e.getIndex1() + 1;
if (start == -1) {
// figure out the selected index
int selidx = -1;
Object eitem = _model.getSelectedItem();
if (eitem != null) {
int ecount = _model.getSize();
for (int i = 0; i < ecount; i++) {
if (eitem == _model.getElementAt(i)) {
selidx = i;
break;
}
}
}
// and update it
updateSelection(selidx);
} else {
// replace the buttons in this range
removeButtons(start, count);
addButtons(start, count);
}
}
// documentation inherited from interface
public void intervalAdded (ListDataEvent e)
{
int start = e.getIndex0(), count = e.getIndex1() - start + 1;
// adjust the selected index
if (_selectedIndex >= start) {
_selectedIndex += count;
}
// add buttons for the new interval
addButtons(start, count);
}
// documentation inherited from interface
public void intervalRemoved (ListDataEvent e)
{
// remove the buttons in the specified interval
int start = e.getIndex0(), count = e.getIndex1() - start + 1;
removeButtons(start, count);
revalidate();
repaint();
}
// documentation inherited from interface
public void mouseClicked (MouseEvent e)
{
}
// documentation inherited from interface
public void mousePressed (MouseEvent e)
{
// keep track of the selected button
_selectedButton = (JLabel)e.getSource();
// if the selected button is already selected, ignore the click
if (_selectedButton.getBorder() == SELECTED_BORDER) {
_selectedButton = null;
} else {
_selectedButton.setBorder(SELECTED_BORDER);
_selectedButton.repaint();
}
}
// documentation inherited from interface
public void mouseReleased (MouseEvent e)
{
// if the mouse was released within the bounds of the button, go
// ahead and select it properly
if (_selectedButton != null) {
if (_selectedButton.contains(e.getX(), e.getY())) {
// tell the model that the selection has changed (and
// we'll respond and do our business
Object elem = _selectedButton.getClientProperty("element");
_model.setSelectedItem(elem);
} else {
_selectedButton.setBorder(DESELECTED_BORDER);
_selectedButton.repaint();
}
// clear out the selected button indicator
_selectedButton = null;
}
}
// documentation inherited from interface
public void mouseEntered (MouseEvent e)
{
}
// documentation inherited from interface
public void mouseExited (MouseEvent e)
{
}
/**
* Adds buttons for the specified range of model elements.
*/
protected void addButtons (int start, int count)
{
Object selobj = _model.getSelectedItem();
for (int i = start; i < count; i++) {
Object elem = _model.getElementAt(i);
if (selobj == elem) {
_selectedIndex = i;
}
JLabel ibut = null;
if (elem instanceof Image) {
ibut = new JLabel(new ImageIcon((Image)elem));
} else {
ibut = new JLabel(elem.toString());
}
ibut.putClientProperty("element", elem);
ibut.addMouseListener(this);
ibut.setBorder((_selectedIndex == i) ?
SELECTED_BORDER : DESELECTED_BORDER);
add(ibut, i);
}
revalidate();
repaint();
}
/**
* Removes the buttons in the specified interval.
*/
protected void removeButtons (int start, int count)
{
while (count-- > 0) {
remove(start);
}
// adjust the selected index
if (_selectedIndex >= start) {
if (start + count > _selectedIndex) {
_selectedIndex = -1;
} else {
_selectedIndex -= count;
}
}
}
/**
* Sets the selection to the specified index and updates the buttons
* to reflect the change. This does not update the model.
*/
protected void updateSelection (int selidx)
{
// do nothing if this element is already selected
if (selidx == _selectedIndex) {
return;
}
// unhighlight the old component
if (_selectedIndex != -1) {
JLabel but = (JLabel)getComponent(_selectedIndex);
but.setBorder(DESELECTED_BORDER);
}
// save the new selection
_selectedIndex = selidx;
// if the selection is valid, highlight the new component
if (_selectedIndex != -1) {
JLabel but = (JLabel)getComponent(_selectedIndex);
but.setBorder(SELECTED_BORDER);
}
// fire an action performed to let listeners know about our
// changed selection
fireActionPerformed();
repaint();
}
/** The contents of the box. */
protected ComboBoxModel _model;
/** The index of the selected button. */
protected int _selectedIndex = -1;
/** The button over which the mouse was pressed. */
protected JLabel _selectedButton;
/** Used when notifying our listeners. */
protected ActionEvent _actionEvent;
/** The action command we generate when the selection changes. */
protected String _actionCommand;
/** The border used for selected components. */
protected static final Border SELECTED_BORDER =
BorderFactory.createLoweredBevelBorder();
/** The border used for non-selected components. */
protected static final Border DESELECTED_BORDER =
BorderFactory.createRaisedBevelBorder();
}
| projects/samskivert/src/java/com/samskivert/swing/ComboButtonBox.java | //
// $Id: ComboButtonBox.java,v 1.1 2002/03/10 05:10:37 mdb Exp $
package com.samskivert.swing;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.border.Border;
import javax.swing.BorderFactory;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import com.samskivert.Log;
/**
* Used to display a horizontal or vertical array of buttons, out of which
* only one is selectable at a time (which will be represented by
* rendering it with an indented border, whereas the other buttons will
* render with an extruded border.
*/
public class ComboButtonBox extends JPanel
implements SwingConstants, ListDataListener, MouseListener
{
/**
* Constructs a button box with the specified orientation (either
* {@link #HORIZONTAL} or {@link #VERTICAL}.
*/
public ComboButtonBox (int orientation)
{
this(orientation, new DefaultComboBoxModel());
}
/**
* Constructs a button box with the specified orientation (either
* {@link #HORIZONTAL} or {@link #VERTICAL}. The supplied model will
* be used to populate the buttons (see {@link #setModel} for more
* details).
*/
public ComboButtonBox (int orientation, ComboBoxModel model)
{
// set up our layout
setOrientation(orientation);
// set up our contents
setModel(model);
}
/**
* Sets the orientation of the box (either {@link #HORIZONTAL} or
* {@link #VERTICAL}.
*/
public void setOrientation (int orientation)
{
GroupLayout gl = (orientation == HORIZONTAL) ?
(GroupLayout)new HGroupLayout() : new VGroupLayout();
gl.setPolicy(GroupLayout.EQUALIZE);
setLayout(gl);
}
/**
* Provides the button box with a data model which it will display. If
* the model contains {@link Image} objects, they will be used to make
* icons for the buttons. Otherwise the button text will contain the
* string representation of the elements in the model.
*/
public void setModel (ComboBoxModel model)
{
// if we had a previous model, unregister ourselves from it
if (_model != null) {
_model.removeListDataListener(this);
}
// subscribe to our new model
_model = model;
_model.addListDataListener(this);
// rebuild the list
removeAll();
addButtons(0, _model.getSize());
}
/**
* Returns the model in use by the button box.
*/
public ComboBoxModel getModel ()
{
return _model;
}
/**
* Sets the index of the selected component. A value of -1 will clear
* the selection.
*/
public void setSelectedIndex (int selidx)
{
// update the display
updateSelection(selidx);
// let the model know what's up
Object item = (selidx == -1) ? null : _model.getElementAt(selidx);
_model.setSelectedItem(item);
}
/**
* Returns the index of the selected item.
*/
public int getSelectedIndex ()
{
return _selectedIndex;
}
/**
* Specifies the command that will be used when generating action
* events (which is done when the selection changes).
*/
public void setActionCommand (String actionCommand)
{
_actionCommand = actionCommand;
}
/**
* Adds a listener to our list of entities to be notified when the
* selection changes.
*/
public void addActionListener (ActionListener l)
{
listenerList.add(ActionListener.class, l);
}
/**
* Removes a listener from the list.
*/
public void removeActionListener (ActionListener l)
{
listenerList.remove(ActionListener.class, l);
}
/**
* Notifies our listeners when the selection changed.
*/
protected void fireActionPerformed ()
{
// guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// process the listeners last to first, notifying those that are
// interested in this event
for (int i = listeners.length-2; i >= 0; i -= 2) {
if (listeners[i] == ActionListener.class) {
// lazily create the event:
if (_actionEvent == null) {
_actionEvent = new ActionEvent(
this, ActionEvent.ACTION_PERFORMED, _actionCommand);
}
((ActionListener)listeners[i+1]).actionPerformed(_actionEvent);
}
}
}
// documentation inherited from interface
public void contentsChanged (ListDataEvent e)
{
// if this update is informing us of a new selection, reflect that
// in the UI
int start = e.getIndex0(), count = start - e.getIndex1() + 1;
if (start == -1) {
// figure out the selected index
int selidx = -1;
Object eitem = _model.getSelectedItem();
if (eitem != null) {
int ecount = _model.getSize();
for (int i = 0; i < ecount; i++) {
if (eitem == _model.getElementAt(i)) {
selidx = i;
break;
}
}
}
// and update it
updateSelection(selidx);
} else {
// replace the buttons in this range
removeButtons(start, count);
addButtons(start, count);
}
}
// documentation inherited from interface
public void intervalAdded (ListDataEvent e)
{
int start = e.getIndex0(), count = e.getIndex1() - start + 1;
// adjust the selected index
if (_selectedIndex >= start) {
_selectedIndex += count;
}
// add buttons for the new interval
addButtons(start, count);
}
// documentation inherited from interface
public void intervalRemoved (ListDataEvent e)
{
// remove the buttons in the specified interval
int start = e.getIndex0(), count = e.getIndex1() - start + 1;
removeButtons(start, count);
revalidate();
repaint();
}
// documentation inherited from interface
public void mouseClicked (MouseEvent e)
{
}
// documentation inherited from interface
public void mousePressed (MouseEvent e)
{
// keep track of the selected button
_selectedButton = (JLabel)e.getSource();
_selectedButton.setBorder(SELECTED_BORDER);
_selectedButton.repaint();
}
// documentation inherited from interface
public void mouseReleased (MouseEvent e)
{
// if the mouse was released within the bounds of the button, go
// ahead and select it properly
if (_selectedButton != null) {
if (_selectedButton.contains(e.getX(), e.getY())) {
// figure out which button this is
int selidx = -1;
int ccount = getComponentCount();
for (int i = 0; i < ccount; i++) {
if (_selectedButton == getComponent(i)) {
selidx = i;
break;
}
}
// sanity check
if (selidx == -1) {
Log.warning("Got action from non-button component!? " +
"[event=" + e + "].");
} else {
// if the selection changed, update our display and
// the model
setSelectedIndex(selidx);
}
} else {
_selectedButton.setBorder(DESELECTED_BORDER);
_selectedButton.repaint();
}
// clear out the selected button indicator
_selectedButton = null;
}
}
// documentation inherited from interface
public void mouseEntered (MouseEvent e)
{
}
// documentation inherited from interface
public void mouseExited (MouseEvent e)
{
}
/**
* Adds buttons for the specified range of model elements.
*/
protected void addButtons (int start, int count)
{
Object selobj = _model.getSelectedItem();
for (int i = start; i < count; i++) {
Object elem = _model.getElementAt(i);
if (selobj == elem) {
_selectedIndex = i;
}
JLabel ibut = null;
if (elem instanceof Image) {
ibut = new JLabel(new ImageIcon((Image)elem));
} else {
ibut = new JLabel(elem.toString());
}
ibut.addMouseListener(this);
ibut.setBorder((_selectedIndex == i) ?
SELECTED_BORDER : DESELECTED_BORDER);
add(ibut, i);
}
revalidate();
repaint();
}
/**
* Removes the buttons in the specified interval.
*/
protected void removeButtons (int start, int count)
{
while (count-- > 0) {
remove(start);
}
// adjust the selected index
if (_selectedIndex >= start) {
if (start + count > _selectedIndex) {
_selectedIndex = -1;
} else {
_selectedIndex -= count;
}
}
}
/**
* Sets the selection to the specified index and updates the buttons
* to reflect the change. This does not update the model.
*/
protected void updateSelection (int selidx)
{
// do nothing if this element is already selected
if (selidx == _selectedIndex) {
return;
}
// unhighlight the old component
if (_selectedIndex != -1) {
JLabel but = (JLabel)getComponent(_selectedIndex);
but.setBorder(DESELECTED_BORDER);
}
// save the new selection
_selectedIndex = selidx;
// if the selection is valid, highlight the new component
if (_selectedIndex != -1) {
JLabel but = (JLabel)getComponent(_selectedIndex);
but.setBorder(SELECTED_BORDER);
}
repaint();
}
/** The contents of the box. */
protected ComboBoxModel _model;
/** The index of the selected button. */
protected int _selectedIndex = -1;
/** The button over which the mouse was pressed. */
protected JLabel _selectedButton;
/** Used when notifying our listeners. */
protected ActionEvent _actionEvent;
/** The action command we generate when the selection changes. */
protected String _actionCommand;
/** The border used for selected components. */
protected static final Border SELECTED_BORDER =
BorderFactory.createLoweredBevelBorder();
/** The border used for non-selected components. */
protected static final Border DESELECTED_BORDER =
BorderFactory.createRaisedBevelBorder();
}
| Wasn't firing action performed; simplified selection management by letting
the model do the work.
git-svn-id: 64ebf368729f38804935acb7146e017e0f909c6b@645 6335cc39-0255-0410-8fd6-9bcaacd3b74c
| projects/samskivert/src/java/com/samskivert/swing/ComboButtonBox.java | Wasn't firing action performed; simplified selection management by letting the model do the work. |
|
Java | apache-2.0 | cb03314a18753e2238eb9b55f1e7e258b74d7c7b | 0 | fhoeben/hsac-fitnesse-plugin,fhoeben/hsac-fitnesse-plugin,fhoeben/hsac-fitnesse-plugin | package nl.hsac.fitnesse.symbols;
import fitnesse.wikitext.parser.*;
import nl.hsac.fitnesse.util.RandomUtil;
import java.util.HashMap;
import java.util.Map;
/**
* Generates random Dutch license plates.
* Usage: !randomDutchLicensePlate (Category) (Sidecode)
* Sidecodes 1-14 are supported (see: https://nl.wikipedia.org/wiki/Nederlands_kenteken)
* Sidecode 7 is used by default.
* Category expects a single letter that is used as the first letter in the license plate
* (f.e. D for mopeds, M for Motorcycle, V for light company cars, B for heavy company cars (>3500KG))
*/
public class RandomDutchLicensePlate extends SymbolBase implements Rule, Translation {
private static final RandomUtil RANDOM_UTIL = new RandomUtil();
private static final String CATEGORY = "Category";
private static final String SIDECODE = "Sidecode";
public RandomDutchLicensePlate() {
super("RandomDutchLicensePlate");
wikiMatcher(new Matcher().string("!randomDutchLicensePlate"));
wikiRule(this);
htmlTranslation(this);
}
public Maybe<Symbol> parse(Symbol current, Parser parser) {
Maybe<Symbol> result = storeParenthesisContent(current, parser, CATEGORY);
if (!result.isNothing()) {
result = storeParenthesisContent(current, parser, SIDECODE);
}
return result;
}
public String toTarget(Translator translator, Symbol symbol) {
String category = symbol.getProperty(CATEGORY, "");
String sideCode = symbol.getProperty(SIDECODE, "7");
return randomLicensePlate(sideCode, category.toUpperCase());
}
private String randomLicensePlate(String sideCode, String category) {
int sideCodeToUse = Integer.parseInt(sideCode);
if (sideCodeToUse > 14) {
throw new IllegalArgumentException("Sidecodes > 14 are unsupported!");
}
String licensePlate = sidecodePatterns().get(sideCodeToUse);
String permitted = "BDFGHJKLMNPRSTVXZ";
String permittedFirstLetter = "FGHJKLNPRSTXZ";
if (category.length() == 1) {
licensePlate = licensePlate.replaceFirst("@", category);
} else {
licensePlate = licensePlate.replaceFirst("@", RANDOM_UTIL.randomString(permittedFirstLetter, 1));
}
while (licensePlate.contains("@")) {
licensePlate = licensePlate.replaceFirst("@", RANDOM_UTIL.randomString(permitted, 1));
}
while (licensePlate.contains("#")) {
licensePlate = licensePlate.replaceFirst("#", RANDOM_UTIL.randomString("1234567890", 1));
}
return licensePlate;
}
private Map<Integer, String> sidecodePatterns() {
Map<Integer, String> patterns = new HashMap<>();
patterns.put(1, "@@-##-##"); //SideCode 1
patterns.put(2, "##-##-@@"); //SideCode 2
patterns.put(3, "##-@@-##"); //SideCode 3
patterns.put(4, "@@-##-@@"); //SideCode 4
patterns.put(5, "@@-@@-##"); //SideCode 5
patterns.put(6, "##-@@-@@"); //SideCode 6
patterns.put(7, "##-@@@-#"); //SideCode 7
patterns.put(8, "#-@@@-##"); //SideCode 8
patterns.put(9, "@@-###-@"); //SideCode 9
patterns.put(10, "@-###-@@"); //SideCode 10
patterns.put(11, "@@@-##-@"); //SideCode 11
patterns.put(12, "@-##-@@@"); //SideCode 12
patterns.put(13, "#-@@-###"); //SideCode 13
patterns.put(14, "###-@@-#"); //SideCode 14
return patterns;
}
}
| src/main/java/nl/hsac/fitnesse/symbols/RandomDutchLicensePlate.java | package nl.hsac.fitnesse.symbols;
import fitnesse.wikitext.parser.*;
import nl.hsac.fitnesse.util.RandomUtil;
import java.util.HashMap;
import java.util.Map;
/**
* Generates random Dutch license plates.
* Usage: !randomDutchLicensePlate (Category) (Sidecode)
* Sidecodes 1-14 are supported (see: https://nl.wikipedia.org/wiki/Nederlands_kenteken)
* Sidecode 7 is used by default.
* Category expects a single letter that is used as the first letter in the license plate
* (f.e. D for mopeds, M for Motorcycle, V for light company cars, B for heavy company cars (>3500KG))
*/
public class RandomDutchLicensePlate extends SymbolBase implements Rule, Translation {
private static final RandomUtil RANDOM_UTIL = new RandomUtil();
private static final String CATEGORY = "Category";
private static final String SIDECODE = "Sidecode";
public RandomDutchLicensePlate() {
super("RandomDutchLicensePlate");
wikiMatcher(new Matcher().string("!randomDutchLicensePlate"));
wikiRule(this);
htmlTranslation(this);
}
public Maybe<Symbol> parse(Symbol current, Parser parser) {
Maybe<Symbol> result = storeParenthesisContent(current, parser, CATEGORY);
if (!result.isNothing()) {
result = storeParenthesisContent(current, parser, SIDECODE);
}
return result;
}
public String toTarget(Translator translator, Symbol symbol) {
String category = symbol.getProperty(CATEGORY, "");
String sideCode = symbol.getProperty(SIDECODE, "7");
return randomLicensePlate(sideCode, category.toUpperCase());
}
private String randomLicensePlate(String sideCode, String category) {
int sideCodeToUse = Integer.parseInt(sideCode);
if (sideCodeToUse > 14) {
throw new IllegalArgumentException("Sidecodes > 14 are unsupported!");
}
String licensePlate = sidecodePatterns().get(sideCodeToUse);
String permitted = "BDFGHJKLMNPRSTVXZ";
String permittedFirstLetter = "FGHJKLNPRSTXZ";
if (category.length() == 1) {
licensePlate = licensePlate.replaceFirst("@", category);
} else {
licensePlate = licensePlate.replaceFirst("@", RANDOM_UTIL.randomString(permittedFirstLetter, 1));
}
while (licensePlate.contains("@")) {
licensePlate = licensePlate.replaceFirst("@", RANDOM_UTIL.randomString(permitted, 1));
}
while (licensePlate.contains("#")) {
licensePlate = licensePlate.replaceFirst("#", RANDOM_UTIL.randomString("1234567890", 1));
}
return licensePlate;
}
private Map<Integer, String> sidecodePatterns() {
Map<Integer, String> patterns = new HashMap<>();
patterns.put(1, "@@-##-##"); //SideCode 1
patterns.put(2, "##-##-@@"); //SideCode 2
patterns.put(3, "##-@@-##"); //SideCode 3
patterns.put(4, "@@-##-@@"); //SideCode 4
patterns.put(5, "@@-@@-##"); //SideCode 5
patterns.put(6, "##-@@-@@"); //SideCode 6
patterns.put(7, "##-@@@-#"); //SideCode 7
patterns.put(8, "#-@@@-##"); //SideCode 8
patterns.put(9, "@@-###-@"); //SideCode 9
patterns.put(10, "@-###-@@"); //SideCode 10
patterns.put(11, "@@@-##-@"); //SideCode 11
patterns.put(12, "@-##-@@@"); //SideCode 12
patterns.put(13, "#-@@-###"); //SideCode 13
patterns.put(14, "###-@@-#"); //SideCode 14
return patterns;
}
}
| Fix Javadoc
| src/main/java/nl/hsac/fitnesse/symbols/RandomDutchLicensePlate.java | Fix Javadoc |
|
Java | apache-2.0 | d0fad082ac853113e8f37c19b439cf1910c0f6e7 | 0 | finmath/finmath-lib,finmath/finmath-lib | /*
* (c) Copyright Christian P. Fries, Germany. Contact: [email protected].
*
* Created on 25.01.2004
*/
package net.finmath.optimizer;
/**
* This class implements a Golden Section search algorithm, i.e., a minimization,
* implemented as a question-and-answer search algorithm.
*
* Example:
* <pre>
* <code>
* GoldenSectionSearch search = new GoldenSectionSearch(-1.0, 5.0);
* while(search.getAccuracy() > 1E-11 && !search.isDone()) {
* double x = search.getNextPoint();
*
* double y = (x - 0.656) * (x - 0.656);
*
* search.setValue(y);
* }
* </code>
* </pre>
*
* For an example on how to use this class see also its main method.
*
* @author Christian Fries - http://www.christian-fries.de
* @version 1.1
*/
public class GoldenSectionSearch {
// This is the golden section ratio
public static final double GOLDEN_SECTION_RATIO = (3.0 - Math.sqrt(5.0)) / 2.0;
// We store the left and right end point of the interval and a middle point (placed at golden section ratio) together with their values
private final double[] points = new double[3]; // left, middle, right
private final double[] values = new double[3]; // left, middle, right
/*
* State of solver
*/
private double nextPoint; // Stores the next point to return by getPoint()
private boolean expectingValue = false; // Stores the state (true, if next call should be setValue(), false for getPoint())
private int numberOfIterations = 0; // Number of numberOfIterations
private double accuracy; // Current accuracy of solution
private boolean isDone = false; // Will be true if machine accuracy has been reached
public static void main(final String[] args) {
System.out.println("Test of GoldenSectionSearch Class.\n");
// Test 1
System.out.println("1. Find minimum of f(x) = (x - 0.656) * (x - 0.656):");
final GoldenSectionSearch search = new GoldenSectionSearch(-1.0, 5.0);
while(search.getAccuracy() > 1E-11 && !search.isDone()) {
final double x = search.getNextPoint();
final double y = (x - 0.656) * (x - 0.656);
search.setValue(y);
}
System.out.println("Result....: " + search.getBestPoint());
System.out.println("Solution..: 0.656");
System.out.println("Iterations: " + search.getNumberOfIterations() + "\n");
// Test 2
System.out.println("2. Find minimum of f(x) = cos(x) on [0.0,6.0]:");
final GoldenSectionSearch search2 = new GoldenSectionSearch(0.0, 6.0);
while(search2.getAccuracy() > 1E-11 && !search2.isDone()) {
final double x = search2.getNextPoint();
final double y = Math.cos(x);
search2.setValue(y);
}
System.out.println("Result....: " + search2.getBestPoint());
System.out.println("Solution..: " + Math.PI + " (Pi)");
System.out.println("Iterations: " + search2.getNumberOfIterations() + "\n");
}
/**
* @param leftPoint left point of search interval
* @param rightPoint right point of search interval
*/
public GoldenSectionSearch(final double leftPoint, final double rightPoint) {
super();
points[0] = leftPoint;
points[1] = getGoldenSection(leftPoint, rightPoint);
points[2] = rightPoint;
nextPoint = points[0];
accuracy = points[2]-points[0];
}
/**
* @return Returns the best point obtained so far.
*/
public double getBestPoint() {
// Lazy: we always return the middle point as best point
return points[1];
}
/**
* Returns the next point for which a valuation is requested.
*
* @return Returns the next point for which a value should be set using <code>setValue</code>.
*/
public double getNextPoint() {
expectingValue = true;
return nextPoint;
}
/**
* Set the value corresponding to the point returned by a previous call of <code>getNextPoint()</code>.
* If setValue is called without prior call to getNextPoint(),
* e.g., when called twice, a RuntimeException is thrown.
*
* @param value Value corresponding to point returned by previous <code>getNextPoint()</code> call.
*/
public void setValue(final double value) {
if(!expectingValue) {
throw new RuntimeException("Call to setValue() perfomed without prior getNextPoint() call (e.g. call performed twice).");
}
if (numberOfIterations < 3) {
/**
* Initially fill values
*/
values[numberOfIterations] = value;
if (numberOfIterations < 2) {
nextPoint = points[numberOfIterations + 1];
} else {
if (points[1] - points[0] > points[2] - points[1]) {
nextPoint = getGoldenSection(points[0], points[1]);
} else {
nextPoint = getGoldenSection(points[1], points[2]);
}
}
}
else {
/**
* Golden section search update rule
*/
if (points[1] - points[0] > points[2] - points[1]) {
// The left interval is the large one
if (value < values[1]) {
/*
* Throw away right point
*/
points[2] = points[1];
values[2] = values[1];
points[1] = nextPoint;
values[1] = value;
} else {
/*
* Throw away left point
*/
points[0] = nextPoint;
values[0] = value;
}
} else {
// The right interval is the large one
if (value < values[1]) {
/*
* Throw away left point
*/
points[0] = points[1];
values[0] = values[1];
points[1] = nextPoint;
values[1] = value;
} else {
/*
* Throw away right point
*/
points[2] = nextPoint;
values[2] = value;
}
}
/*
* Update next point to ask value for (create point in larger interval)
*/
if (points[1] - points[0] > points[2] - points[1]) {
nextPoint = getGoldenSection(points[0], points[1]);
} else {
nextPoint = getGoldenSection(points[1], points[2]);
}
/*
* Save belt: check if still improve or if we have reached machine accuracy
*/
if(points[2]-points[0] >= accuracy) {
isDone = true;
}
accuracy = points[2]-points[0];
}
numberOfIterations++;
expectingValue = false;
}
public GoldenSectionSearch optimize() {
while(!isDone()) {
final double parameter = getNextPoint();
final double value = value(parameter);
this.setValue(value);
}
return this;
}
public double value(final double parameter) {
// You need to overwrite this mehtod with you own objective function
throw new RuntimeException("Objective function not overwritten.");
}
/**
* @return Returns the golden section of an interval.
*/
public static double getGoldenSection(final double left, final double right) {
return GOLDEN_SECTION_RATIO * left + (1.0 - GOLDEN_SECTION_RATIO) * right;
}
/**
* @return Returns the number of iterations needed so far.
*/
public int getNumberOfIterations() {
return numberOfIterations;
}
/**
* @return Returns the accuracy obtained so far.
*/
public double getAccuracy() {
return accuracy;
}
/**
* @return Returns true if the solver is unable to improve further. This may be either due to reached accuracy or due to no solution existing.
*/
public boolean isDone() {
return isDone;
}
}
| src/main/java/net/finmath/optimizer/GoldenSectionSearch.java | /*
* (c) Copyright Christian P. Fries, Germany. Contact: [email protected].
*
* Created on 25.01.2004
*/
package net.finmath.optimizer;
/**
* This class implements a Golden Section search algorithm, i.e., a minimization,
* implemented as a question-and-answer search algorithm.
*
* Example:
* <pre>
* <code>
* GoldenSectionSearch search = new GoldenSectionSearch(-1.0, 5.0);
* while(search.getAccuracy() > 1E-11 && !search.isDone()) {
* double x = search.getNextPoint();
*
* double y = (x - 0.656) * (x - 0.656);
*
* search.setValue(y);
* }
* </code>
* </pre>
*
* For an example on how to use this class see also its main method.
*
* @author Christian Fries - http://www.christian-fries.de
* @version 1.1
*/
public class GoldenSectionSearch {
// This is the golden section ratio
static final double GOLDEN_SECTION_RATIO = (3.0 - Math.sqrt(5.0)) / 2.0;
// We store the left and right end point of the interval and a middle point (placed at golden section ratio) together with their values
private final double[] points = new double[3]; // left, middle, right
private final double[] values = new double[3]; // left, middle, right
/*
* State of solver
*/
private double nextPoint; // Stores the next point to return by getPoint()
private boolean expectingValue = false; // Stores the state (true, if next call should be setValue(), false for getPoint())
private int numberOfIterations = 0; // Number of numberOfIterations
private double accuracy; // Current accuracy of solution
private boolean isDone = false; // Will be true if machine accuracy has been reached
public static void main(final String[] args) {
System.out.println("Test of GoldenSectionSearch Class.\n");
// Test 1
System.out.println("1. Find minimum of f(x) = (x - 0.656) * (x - 0.656):");
final GoldenSectionSearch search = new GoldenSectionSearch(-1.0, 5.0);
while(search.getAccuracy() > 1E-11 && !search.isDone()) {
final double x = search.getNextPoint();
final double y = (x - 0.656) * (x - 0.656);
search.setValue(y);
}
System.out.println("Result....: " + search.getBestPoint());
System.out.println("Solution..: 0.656");
System.out.println("Iterations: " + search.getNumberOfIterations() + "\n");
// Test 2
System.out.println("2. Find minimum of f(x) = cos(x) on [0.0,6.0]:");
final GoldenSectionSearch search2 = new GoldenSectionSearch(0.0, 6.0);
while(search2.getAccuracy() > 1E-11 && !search2.isDone()) {
final double x = search2.getNextPoint();
final double y = Math.cos(x);
search2.setValue(y);
}
System.out.println("Result....: " + search2.getBestPoint());
System.out.println("Solution..: " + Math.PI + " (Pi)");
System.out.println("Iterations: " + search2.getNumberOfIterations() + "\n");
}
/**
* @param leftPoint left point of search interval
* @param rightPoint right point of search interval
*/
public GoldenSectionSearch(final double leftPoint, final double rightPoint) {
super();
points[0] = leftPoint;
points[1] = getGoldenSection(leftPoint, rightPoint);
points[2] = rightPoint;
nextPoint = points[0];
accuracy = points[2]-points[0];
}
/**
* @return Returns the best point obtained so far.
*/
public double getBestPoint() {
// Lazy: we always return the middle point as best point
return points[1];
}
/**
* Returns the next point for which a valuation is requested.
*
* @return Returns the next point for which a value should be set using <code>setValue</code>.
*/
public double getNextPoint() {
expectingValue = true;
return nextPoint;
}
/**
* Set the value corresponding to the point returned by a previous call of <code>getNextPoint()</code>.
* If setValue is called without prior call to getNextPoint(),
* e.g., when called twice, a RuntimeException is thrown.
*
* @param value Value corresponding to point returned by previous <code>getNextPoint()</code> call.
*/
public void setValue(final double value) {
if(!expectingValue) {
throw new RuntimeException("Call to setValue() perfomed without prior getNextPoint() call (e.g. call performed twice).");
}
if (numberOfIterations < 3) {
/**
* Initially fill values
*/
values[numberOfIterations] = value;
if (numberOfIterations < 2) {
nextPoint = points[numberOfIterations + 1];
} else {
if (points[1] - points[0] > points[2] - points[1]) {
nextPoint = getGoldenSection(points[0], points[1]);
} else {
nextPoint = getGoldenSection(points[1], points[2]);
}
}
}
else {
/**
* Golden section search update rule
*/
if (points[1] - points[0] > points[2] - points[1]) {
// The left interval is the large one
if (value < values[1]) {
/*
* Throw away right point
*/
points[2] = points[1];
values[2] = values[1];
points[1] = nextPoint;
values[1] = value;
} else {
/*
* Throw away left point
*/
points[0] = nextPoint;
values[0] = value;
}
} else {
// The right interval is the large one
if (value < values[1]) {
/*
* Throw away left point
*/
points[0] = points[1];
values[0] = values[1];
points[1] = nextPoint;
values[1] = value;
} else {
/*
* Throw away right point
*/
points[2] = nextPoint;
values[2] = value;
}
}
/*
* Update next point to ask value for (create point in larger interval)
*/
if (points[1] - points[0] > points[2] - points[1]) {
nextPoint = getGoldenSection(points[0], points[1]);
} else {
nextPoint = getGoldenSection(points[1], points[2]);
}
/*
* Save belt: check if still improve or if we have reached machine accuracy
*/
if(points[2]-points[0] >= accuracy) {
isDone = true;
}
accuracy = points[2]-points[0];
}
numberOfIterations++;
expectingValue = false;
}
public GoldenSectionSearch optimize() {
while(!isDone()) {
final double parameter = getNextPoint();
final double value = value(parameter);
this.setValue(value);
}
return this;
}
public double value(final double parameter) {
// You need to overwrite this mehtod with you own objective function
throw new RuntimeException("Objective function not overwritten.");
}
/**
* @return Returns the golden section of an interval.
*/
static double getGoldenSection(final double left, final double right) {
return GOLDEN_SECTION_RATIO * left + (1.0 - GOLDEN_SECTION_RATIO) * right;
}
/**
* @return Returns the number of iterations needed so far.
*/
public int getNumberOfIterations() {
return numberOfIterations;
}
/**
* @return Returns the accuracy obtained so far.
*/
public double getAccuracy() {
return accuracy;
}
/**
* @return Returns true if the solver is unable to improve further. This may be either due to reached accuracy or due to no solution existing.
*/
public boolean isDone() {
return isDone;
}
}
| Golden Section is provided as public static method / constant. | src/main/java/net/finmath/optimizer/GoldenSectionSearch.java | Golden Section is provided as public static method / constant. |
|
Java | apache-2.0 | b7a63189cd81991db62c2937cf6dbab0beafb5a3 | 0 | twitter/heron,huijunwu/heron,huijunwu/heron,twitter/heron,huijunwu/heron,twitter/heron,twitter/heron,twitter/heron,twitter/heron,huijunwu/heron,huijunwu/heron,huijunwu/heron,twitter/heron,twitter/heron,huijunwu/heron,huijunwu/heron | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.heron.scheduler;
import java.io.PrintStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.google.common.annotations.VisibleForTesting;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.heron.api.generated.TopologyAPI;
import org.apache.heron.api.utils.TopologyUtils;
import org.apache.heron.common.basics.DryRunFormatType;
import org.apache.heron.common.basics.SysUtils;
import org.apache.heron.common.utils.logging.LoggingHelper;
import org.apache.heron.scheduler.dryrun.SubmitDryRunResponse;
import org.apache.heron.scheduler.utils.DryRunRenders;
import org.apache.heron.scheduler.utils.LauncherUtils;
import org.apache.heron.scheduler.utils.SubmitterUtils;
import org.apache.heron.spi.common.Config;
import org.apache.heron.spi.common.ConfigLoader;
import org.apache.heron.spi.common.Context;
import org.apache.heron.spi.common.Key;
import org.apache.heron.spi.packing.PackingException;
import org.apache.heron.spi.packing.PackingPlan;
import org.apache.heron.spi.scheduler.ILauncher;
import org.apache.heron.spi.scheduler.LauncherException;
import org.apache.heron.spi.statemgr.IStateManager;
import org.apache.heron.spi.statemgr.SchedulerStateManagerAdaptor;
import org.apache.heron.spi.uploader.IUploader;
import org.apache.heron.spi.uploader.UploaderException;
import org.apache.heron.spi.utils.ReflectionUtils;
/**
* Calls Uploader to upload topology package, and Launcher to launch Scheduler.
*/
public class SubmitterMain {
private static final Logger LOG = Logger.getLogger(SubmitterMain.class.getName());
/**
* Load the config parameters from the command line
*
* @param cluster name of the cluster
* @param role user role
* @param environ user provided environment/tag
* @param submitUser the submit user
* @param dryRun run as dry run
* @param dryRunFormat the dry run format
* @param verbose enable verbose logging
* @return config the command line config
*/
protected static Config commandLineConfigs(String cluster,
String role,
String environ,
String submitUser,
Boolean dryRun,
DryRunFormatType dryRunFormat,
Boolean verbose) {
return Config.newBuilder()
.put(Key.CLUSTER, cluster)
.put(Key.ROLE, role)
.put(Key.ENVIRON, environ)
.put(Key.SUBMIT_USER, submitUser)
.put(Key.DRY_RUN, dryRun)
.put(Key.DRY_RUN_FORMAT_TYPE, dryRunFormat)
.put(Key.VERBOSE, verbose)
.build();
}
// Print usage options
private static void usage(Options options) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("SubmitterMain", options);
}
// Construct all required command line options
private static Options constructOptions() {
Options options = new Options();
Option cluster = Option.builder("c")
.desc("Cluster name in which the topology needs to run on")
.longOpt("cluster")
.hasArgs()
.argName("cluster")
.required()
.build();
Option role = Option.builder("r")
.desc("Role under which the topology needs to run")
.longOpt("role")
.hasArgs()
.argName("role")
.required()
.build();
Option environment = Option.builder("e")
.desc("Environment under which the topology needs to run")
.longOpt("environment")
.hasArgs()
.argName("environment")
.required()
.build();
Option submitUser = Option.builder("s")
.desc("User submitting the topology")
.longOpt("submit_user")
.hasArgs()
.argName("submit userid")
.required()
.build();
Option heronHome = Option.builder("d")
.desc("Directory where heron is installed")
.longOpt("heron_home")
.hasArgs()
.argName("heron home dir")
.required()
.build();
Option configFile = Option.builder("p")
.desc("Path of the config files")
.longOpt("config_path")
.hasArgs()
.argName("config path")
.required()
.build();
Option configOverrides = Option.builder("o")
.desc("Command line override config path")
.longOpt("override_config_file")
.hasArgs()
.argName("override config file")
.build();
Option releaseFile = Option.builder("b")
.desc("Release file name")
.longOpt("release_file")
.hasArgs()
.argName("release information")
.build();
Option topologyPackage = Option.builder("y")
.desc("tar ball containing user submitted jar/tar, defn and config")
.longOpt("topology_package")
.hasArgs()
.argName("topology package")
.required()
.build();
Option topologyDefn = Option.builder("f")
.desc("serialized file containing Topology protobuf")
.longOpt("topology_defn")
.hasArgs()
.argName("topology definition")
.required()
.build();
Option topologyJar = Option.builder("j")
.desc("The filename of the heron topology jar/tar/pex file to be run by the executor")
.longOpt("topology_bin")
.hasArgs()
.argName("topology binary filename on the cluster")
.required()
.build();
Option dryRun = Option.builder("u")
.desc("run in dry-run mode")
.longOpt("dry_run")
.required(false)
.build();
Option dryRunFormat = Option.builder("t")
.desc("dry-run format")
.longOpt("dry_run_format")
.hasArg()
.required(false)
.build();
Option verbose = Option.builder("v")
.desc("Enable debug logs")
.longOpt("verbose")
.build();
options.addOption(cluster);
options.addOption(role);
options.addOption(environment);
options.addOption(submitUser);
options.addOption(heronHome);
options.addOption(configFile);
options.addOption(configOverrides);
options.addOption(releaseFile);
options.addOption(topologyPackage);
options.addOption(topologyDefn);
options.addOption(topologyJar);
options.addOption(dryRun);
options.addOption(dryRunFormat);
options.addOption(verbose);
return options;
}
// construct command line help options
private static Options constructHelpOptions() {
Options options = new Options();
Option help = Option.builder("h")
.desc("List all options and their description")
.longOpt("help")
.build();
options.addOption(help);
return options;
}
private static boolean isVerbose(CommandLine cmd) {
return cmd.hasOption("v");
}
@SuppressWarnings("JavadocMethod")
@VisibleForTesting
public static Config loadConfig(CommandLine cmd, TopologyAPI.Topology topology) {
String cluster = cmd.getOptionValue("cluster");
String role = cmd.getOptionValue("role");
String environ = cmd.getOptionValue("environment");
String submitUser = cmd.getOptionValue("submit_user");
String heronHome = cmd.getOptionValue("heron_home");
String configPath = cmd.getOptionValue("config_path");
String overrideConfigFile = cmd.getOptionValue("override_config_file");
String releaseFile = cmd.getOptionValue("release_file");
String topologyPackage = cmd.getOptionValue("topology_package");
String topologyDefnFile = cmd.getOptionValue("topology_defn");
String topologyBinaryFile = cmd.getOptionValue("topology_bin");
Boolean dryRun = false;
if (cmd.hasOption("u")) {
dryRun = true;
}
// Default dry-run output format type
DryRunFormatType dryRunFormat = DryRunFormatType.TABLE;
if (dryRun && cmd.hasOption("t")) {
String format = cmd.getOptionValue("dry_run_format");
dryRunFormat = DryRunFormatType.getDryRunFormatType(format);
LOG.fine(String.format("Running dry-run mode using format %s", format));
}
// first load the defaults, then the config from files to override it
// next add config parameters from the command line
// load the topology configs
// build the final config by expanding all the variables
return Config.toLocalMode(Config.newBuilder()
.putAll(ConfigLoader.loadConfig(heronHome, configPath, releaseFile, overrideConfigFile))
.putAll(commandLineConfigs(cluster, role, environ, submitUser, dryRun,
dryRunFormat, isVerbose(cmd)))
.putAll(SubmitterUtils.topologyConfigs(topologyPackage, topologyBinaryFile,
topologyDefnFile, topology))
.build());
}
public static void main(String[] args) throws Exception {
Options options = constructOptions();
Options helpOptions = constructHelpOptions();
CommandLineParser parser = new DefaultParser();
// parse the help options first.
CommandLine cmd = parser.parse(helpOptions, args, true);
if (cmd.hasOption("h")) {
usage(options);
return;
}
try {
// Now parse the required options
cmd = parser.parse(options, args);
} catch (ParseException e) {
usage(options);
throw new RuntimeException("Error parsing command line options: ", e);
}
Level logLevel = Level.INFO;
if (isVerbose(cmd)) {
logLevel = Level.ALL;
}
// init log
LoggingHelper.loggerInit(logLevel, false);
// load the topology definition into topology proto
TopologyAPI.Topology topology = TopologyUtils.getTopology(cmd.getOptionValue("topology_defn"));
Config config = loadConfig(cmd, topology);
LOG.fine("Static config loaded successfully");
LOG.fine(config.toString());
SubmitterMain submitterMain = new SubmitterMain(config, topology);
/* Meaning of exit status code:
- status code = 0:
program exits without error
- 0 < status code < 100:
program fails to execute before program execution. For example,
JVM cannot find or load main class
- 100 <= status code < 200:
program fails to launch after program execution. For example,
topology definition file fails to be loaded
- status code >= 200
program sends out dry-run response */
try {
submitterMain.submitTopology();
} catch (SubmitDryRunResponse response) {
LOG.log(Level.FINE, "Sending out dry-run response");
// Output may contain UTF-8 characters, so we should print using UTF-8 encoding
PrintStream out = new PrintStream(System.out, true, StandardCharsets.UTF_8.name());
out.print(DryRunRenders.render(response, Context.dryRunFormatType(config)));
// Exit with status code 200 to indicate dry-run response is sent out
// SUPPRESS CHECKSTYLE RegexpSinglelineJava
System.exit(200);
// SUPPRESS CHECKSTYLE IllegalCatch
} catch (Exception e) {
/* Since only stderr is used (by logging), we use stdout here to
propagate error message back to Python's executor.py (invoke site). */
LOG.log(Level.SEVERE, "Exception when submitting topology", e);
System.out.println(e.getMessage());
// Exit with status code 100 to indicate that error has happened on user-land
// SUPPRESS CHECKSTYLE RegexpSinglelineJava
System.exit(100);
}
LOG.log(Level.FINE, "Topology {0} submitted successfully", topology.getName());
}
// holds all the config read
private final Config config;
// topology definition
private final TopologyAPI.Topology topology;
public SubmitterMain(Config config, TopologyAPI.Topology topology) {
// initialize the options
this.config = config;
this.topology = topology;
}
/**
* Submit a topology
* 1. Instantiate necessary resources
* 2. Valid whether it is legal to submit a topology
* 3. Call LauncherRunner
*
*/
public void submitTopology() throws TopologySubmissionException {
// build primary runtime config first
Config primaryRuntime = Config.newBuilder()
.putAll(LauncherUtils.getInstance().createPrimaryRuntime(topology)).build();
// call launcher directly here if in dry-run mode
if (Context.dryRun(config)) {
callLauncherRunner(primaryRuntime);
return;
}
// 1. Do prepare work
// create an instance of state manager
String statemgrClass = Context.stateManagerClass(config);
IStateManager statemgr;
// Create an instance of the launcher class
String launcherClass = Context.launcherClass(config);
ILauncher launcher;
// create an instance of the uploader class
String uploaderClass = Context.uploaderClass(config);
IUploader uploader;
// create an instance of state manager
try {
statemgr = ReflectionUtils.newInstance(statemgrClass);
} catch (IllegalAccessException | InstantiationException | ClassNotFoundException e) {
throw new TopologySubmissionException(
String.format("Failed to instantiate state manager class '%s'", statemgrClass), e);
}
// create an instance of launcher
try {
launcher = ReflectionUtils.newInstance(launcherClass);
} catch (IllegalAccessException | InstantiationException | ClassNotFoundException e) {
throw new LauncherException(
String.format("Failed to instantiate launcher class '%s'", launcherClass), e);
}
// create an instance of uploader
try {
uploader = ReflectionUtils.newInstance(uploaderClass);
} catch (IllegalAccessException | InstantiationException | ClassNotFoundException e) {
throw new UploaderException(
String.format("Failed to instantiate uploader class '%s'", uploaderClass), e);
}
// Put it in a try block so that we can always clean resources
try {
// initialize the state manager
statemgr.initialize(config);
// initialize the uploader
uploader.initialize(config);
// TODO(mfu): timeout should read from config
SchedulerStateManagerAdaptor adaptor = new SchedulerStateManagerAdaptor(statemgr, 5000);
// Check if topology is already running
validateSubmit(adaptor, topology.getName());
LOG.log(Level.FINE, "Topology {0} to be submitted", topology.getName());
Config runtimeWithoutPackageURI = Config.newBuilder()
.putAll(primaryRuntime)
.putAll(LauncherUtils.getInstance().createAdaptorRuntime(adaptor))
.put(Key.LAUNCHER_CLASS_INSTANCE, launcher)
.build();
PackingPlan packingPlan = LauncherUtils.getInstance()
.createPackingPlan(config, runtimeWithoutPackageURI);
// The packing plan might call for a number of containers different than the config
// settings. If that's the case we need to modify the configs to match.
runtimeWithoutPackageURI =
updateNumContainersIfNeeded(runtimeWithoutPackageURI, topology, packingPlan);
// If the packing plan is valid we will upload necessary packages
URI packageURI = uploadPackage(uploader);
// Update the runtime config with the packageURI
Config runtimeAll = Config.newBuilder()
.putAll(runtimeWithoutPackageURI)
.put(Key.TOPOLOGY_PACKAGE_URI, packageURI)
.build();
callLauncherRunner(runtimeAll);
} catch (LauncherException | PackingException e) {
// we undo uploading of topology package only if launcher fails to
// launch topology, which will throw LauncherException or PackingException
uploader.undo();
throw e;
} finally {
SysUtils.closeIgnoringExceptions(uploader);
SysUtils.closeIgnoringExceptions(launcher);
SysUtils.closeIgnoringExceptions(statemgr);
}
}
/**
* Checks that the number of containers specified in the topology matches the number of containers
* called for in the packing plan. If they are different, returns a new config with settings
* updated to align with the packing plan. The new config will include an updated
* Key.TOPOLOGY_DEFINITION containing a cloned Topology with it's settings also updated.
*
* @param initialConfig initial config to clone and update (if necessary)
* @param initialTopology topology to check and clone/update (if necessary)
* @param packingPlan packing plan to compare settings with
* @return a new Config cloned from initialConfig and modified as needed to align with packedPlan
*/
@VisibleForTesting
Config updateNumContainersIfNeeded(Config initialConfig,
TopologyAPI.Topology initialTopology,
PackingPlan packingPlan) {
int configNumStreamManagers = TopologyUtils.getNumContainers(initialTopology);
int packingNumStreamManagers = packingPlan.getContainers().size();
if (configNumStreamManagers == packingNumStreamManagers) {
return initialConfig;
}
Config.Builder newConfigBuilder = Config.newBuilder()
.putAll(initialConfig)
.put(Key.NUM_CONTAINERS, packingNumStreamManagers + 1)
.put(Key.TOPOLOGY_DEFINITION,
cloneWithNewNumContainers(initialTopology, packingNumStreamManagers));
String packingClass = Context.packingClass(config);
LOG.warning(String.format("The packing plan (generated by %s) calls for a different number of "
+ "containers (%d) than what was explicitly set in the topology configs (%d). "
+ "Overriding the configs to specify %d containers. When using %s do not explicitly "
+ "call config.setNumStmgrs(..) or config.setNumWorkers(..).",
packingClass, packingNumStreamManagers, configNumStreamManagers,
packingNumStreamManagers, packingClass));
return newConfigBuilder.build();
}
private TopologyAPI.Topology cloneWithNewNumContainers(TopologyAPI.Topology initialTopology,
int numStreamManagers) {
TopologyAPI.Topology.Builder topologyBuilder = TopologyAPI.Topology.newBuilder(initialTopology);
TopologyAPI.Config.Builder configBuilder = TopologyAPI.Config.newBuilder();
for (TopologyAPI.Config.KeyValue keyValue : initialTopology.getTopologyConfig().getKvsList()) {
// override TOPOLOGY_STMGRS value once we find it
if (org.apache.heron.api.Config.TOPOLOGY_STMGRS.equals(keyValue.getKey())) {
TopologyAPI.Config.KeyValue.Builder kvBuilder = TopologyAPI.Config.KeyValue.newBuilder();
kvBuilder.setKey(keyValue.getKey());
kvBuilder.setValue(Integer.toString(numStreamManagers));
configBuilder.addKvs(kvBuilder.build());
} else {
configBuilder.addKvs(keyValue);
}
}
return topologyBuilder.setTopologyConfig(configBuilder).build();
}
protected void validateSubmit(SchedulerStateManagerAdaptor adaptor, String topologyName)
throws TopologySubmissionException {
// Check whether the topology has already been running
// TODO(rli): anti-pattern is too nested on this path to be refactored
Boolean isTopologyRunning = adaptor.isTopologyRunning(topologyName);
if (isTopologyRunning != null && isTopologyRunning.equals(Boolean.TRUE)) {
throw new TopologySubmissionException(
String.format("Topology '%s' already exists", topologyName));
}
}
protected URI uploadPackage(IUploader uploader) throws UploaderException {
// upload the topology package to the storage
return uploader.uploadPackage();
}
protected void callLauncherRunner(Config runtime)
throws LauncherException, PackingException, SubmitDryRunResponse {
// using launch runner, launch the topology
LaunchRunner launchRunner = new LaunchRunner(config, runtime);
launchRunner.call();
}
}
| heron/scheduler-core/src/java/org/apache/heron/scheduler/SubmitterMain.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.heron.scheduler;
import java.io.PrintStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.google.common.annotations.VisibleForTesting;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.heron.api.generated.TopologyAPI;
import org.apache.heron.api.utils.TopologyUtils;
import org.apache.heron.common.basics.DryRunFormatType;
import org.apache.heron.common.basics.SysUtils;
import org.apache.heron.common.utils.logging.LoggingHelper;
import org.apache.heron.scheduler.dryrun.SubmitDryRunResponse;
import org.apache.heron.scheduler.utils.DryRunRenders;
import org.apache.heron.scheduler.utils.LauncherUtils;
import org.apache.heron.scheduler.utils.SubmitterUtils;
import org.apache.heron.spi.common.Config;
import org.apache.heron.spi.common.ConfigLoader;
import org.apache.heron.spi.common.Context;
import org.apache.heron.spi.common.Key;
import org.apache.heron.spi.packing.PackingException;
import org.apache.heron.spi.packing.PackingPlan;
import org.apache.heron.spi.scheduler.ILauncher;
import org.apache.heron.spi.scheduler.LauncherException;
import org.apache.heron.spi.statemgr.IStateManager;
import org.apache.heron.spi.statemgr.SchedulerStateManagerAdaptor;
import org.apache.heron.spi.uploader.IUploader;
import org.apache.heron.spi.uploader.UploaderException;
import org.apache.heron.spi.utils.ReflectionUtils;
/**
* Calls Uploader to upload topology package, and Launcher to launch Scheduler.
*/
public class SubmitterMain {
private static final Logger LOG = Logger.getLogger(SubmitterMain.class.getName());
/**
* Load the config parameters from the command line
*
* @param cluster name of the cluster
* @param role user role
* @param environ user provided environment/tag
* @param submitUser the submit user
* @param dryRun run as dry run
* @param dryRunFormat the dry run format
* @param verbose enable verbose logging
* @return config the command line config
*/
protected static Config commandLineConfigs(String cluster,
String role,
String environ,
String submitUser,
Boolean dryRun,
DryRunFormatType dryRunFormat,
Boolean verbose) {
return Config.newBuilder()
.put(Key.CLUSTER, cluster)
.put(Key.ROLE, role)
.put(Key.ENVIRON, environ)
.put(Key.SUBMIT_USER, submitUser)
.put(Key.DRY_RUN, dryRun)
.put(Key.DRY_RUN_FORMAT_TYPE, dryRunFormat)
.put(Key.VERBOSE, verbose)
.build();
}
// Print usage options
private static void usage(Options options) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("SubmitterMain", options);
}
// Construct all required command line options
private static Options constructOptions() {
Options options = new Options();
Option cluster = Option.builder("c")
.desc("Cluster name in which the topology needs to run on")
.longOpt("cluster")
.hasArgs()
.argName("cluster")
.required()
.build();
Option role = Option.builder("r")
.desc("Role under which the topology needs to run")
.longOpt("role")
.hasArgs()
.argName("role")
.required()
.build();
Option environment = Option.builder("e")
.desc("Environment under which the topology needs to run")
.longOpt("environment")
.hasArgs()
.argName("environment")
.required()
.build();
Option submitUser = Option.builder("s")
.desc("User submitting the topology")
.longOpt("submit_user")
.hasArgs()
.argName("submit userid")
.required()
.build();
Option heronHome = Option.builder("d")
.desc("Directory where heron is installed")
.longOpt("heron_home")
.hasArgs()
.argName("heron home dir")
.required()
.build();
Option configFile = Option.builder("p")
.desc("Path of the config files")
.longOpt("config_path")
.hasArgs()
.argName("config path")
.required()
.build();
Option configOverrides = Option.builder("o")
.desc("Command line override config path")
.longOpt("override_config_file")
.hasArgs()
.argName("override config file")
.build();
Option releaseFile = Option.builder("b")
.desc("Release file name")
.longOpt("release_file")
.hasArgs()
.argName("release information")
.build();
Option topologyPackage = Option.builder("y")
.desc("tar ball containing user submitted jar/tar, defn and config")
.longOpt("topology_package")
.hasArgs()
.argName("topology package")
.required()
.build();
Option topologyDefn = Option.builder("f")
.desc("serialized file containing Topology protobuf")
.longOpt("topology_defn")
.hasArgs()
.argName("topology definition")
.required()
.build();
Option topologyJar = Option.builder("j")
.desc("The filename of the heron topology jar/tar/pex file to be run by the executor")
.longOpt("topology_bin")
.hasArgs()
.argName("topology binary filename on the cluster")
.required()
.build();
Option dryRun = Option.builder("u")
.desc("run in dry-run mode")
.longOpt("dry_run")
.required(false)
.build();
Option dryRunFormat = Option.builder("t")
.desc("dry-run format")
.longOpt("dry_run_format")
.hasArg()
.required(false)
.build();
Option verbose = Option.builder("v")
.desc("Enable debug logs")
.longOpt("verbose")
.build();
options.addOption(cluster);
options.addOption(role);
options.addOption(environment);
options.addOption(submitUser);
options.addOption(heronHome);
options.addOption(configFile);
options.addOption(configOverrides);
options.addOption(releaseFile);
options.addOption(topologyPackage);
options.addOption(topologyDefn);
options.addOption(topologyJar);
options.addOption(dryRun);
options.addOption(dryRunFormat);
options.addOption(verbose);
return options;
}
// construct command line help options
private static Options constructHelpOptions() {
Options options = new Options();
Option help = Option.builder("h")
.desc("List all options and their description")
.longOpt("help")
.build();
options.addOption(help);
return options;
}
private static boolean isVerbose(CommandLine cmd) {
return cmd.hasOption("v");
}
@SuppressWarnings("JavadocMethod")
@VisibleForTesting
public static Config loadConfig(CommandLine cmd, TopologyAPI.Topology topology) {
String cluster = cmd.getOptionValue("cluster");
String role = cmd.getOptionValue("role");
String environ = cmd.getOptionValue("environment");
String submitUser = cmd.getOptionValue("submit_user");
String heronHome = cmd.getOptionValue("heron_home");
String configPath = cmd.getOptionValue("config_path");
String overrideConfigFile = cmd.getOptionValue("override_config_file");
String releaseFile = cmd.getOptionValue("release_file");
String topologyPackage = cmd.getOptionValue("topology_package");
String topologyDefnFile = cmd.getOptionValue("topology_defn");
String topologyBinaryFile = cmd.getOptionValue("topology_bin");
Boolean dryRun = false;
if (cmd.hasOption("u")) {
dryRun = true;
}
// Default dry-run output format type
DryRunFormatType dryRunFormat = DryRunFormatType.TABLE;
if (dryRun && cmd.hasOption("t")) {
String format = cmd.getOptionValue("dry_run_format");
dryRunFormat = DryRunFormatType.getDryRunFormatType(format);
LOG.fine(String.format("Running dry-run mode using format %s", format));
}
// first load the defaults, then the config from files to override it
// next add config parameters from the command line
// load the topology configs
// build the final config by expanding all the variables
return Config.toLocalMode(Config.newBuilder()
.putAll(ConfigLoader.loadConfig(heronHome, configPath, releaseFile, overrideConfigFile))
.putAll(commandLineConfigs(cluster, role, environ, submitUser, dryRun,
dryRunFormat, isVerbose(cmd)))
.putAll(SubmitterUtils.topologyConfigs(topologyPackage, topologyBinaryFile,
topologyDefnFile, topology))
.build());
}
public static void main(String[] args) throws Exception {
Options options = constructOptions();
Options helpOptions = constructHelpOptions();
CommandLineParser parser = new DefaultParser();
// parse the help options first.
CommandLine cmd = parser.parse(helpOptions, args, true);
if (cmd.hasOption("h")) {
usage(options);
return;
}
try {
// Now parse the required options
cmd = parser.parse(options, args);
} catch (ParseException e) {
usage(options);
throw new RuntimeException("Error parsing command line options: ", e);
}
Level logLevel = Level.INFO;
if (isVerbose(cmd)) {
logLevel = Level.ALL;
}
// init log
LoggingHelper.loggerInit(logLevel, false);
// load the topology definition into topology proto
TopologyAPI.Topology topology = TopologyUtils.getTopology(cmd.getOptionValue("topology_defn"));
Config config = loadConfig(cmd, topology);
LOG.fine("Static config loaded successfully");
LOG.fine(config.toString());
SubmitterMain submitterMain = new SubmitterMain(config, topology);
/* Meaning of exit status code:
- status code = 0:
program exits without error
- 0 < status code < 100:
program fails to execute before program execution. For example,
JVM cannot find or load main class
- 100 <= status code < 200:
program fails to launch after program execution. For example,
topology definition file fails to be loaded
- status code >= 200
program sends out dry-run response */
try {
submitterMain.submitTopology();
} catch (SubmitDryRunResponse response) {
LOG.log(Level.FINE, "Sending out dry-run response");
// Output may contain UTF-8 characters, so we should print using UTF-8 encoding
PrintStream out = new PrintStream(System.out, true, StandardCharsets.UTF_8.name());
out.print(DryRunRenders.render(response, Context.dryRunFormatType(config)));
// Exit with status code 200 to indicate dry-run response is sent out
// SUPPRESS CHECKSTYLE RegexpSinglelineJava
System.exit(200);
// SUPPRESS CHECKSTYLE IllegalCatch
} catch (Exception e) {
/* Since only stderr is used (by logging), we use stdout here to
propagate error message back to Python's executor.py (invoke site). */
LOG.log(Level.FINE, "Exception when submitting topology", e);
System.out.println(e.getMessage());
// Exit with status code 100 to indicate that error has happened on user-land
// SUPPRESS CHECKSTYLE RegexpSinglelineJava
System.exit(100);
}
LOG.log(Level.FINE, "Topology {0} submitted successfully", topology.getName());
}
// holds all the config read
private final Config config;
// topology definition
private final TopologyAPI.Topology topology;
public SubmitterMain(Config config, TopologyAPI.Topology topology) {
// initialize the options
this.config = config;
this.topology = topology;
}
/**
* Submit a topology
* 1. Instantiate necessary resources
* 2. Valid whether it is legal to submit a topology
* 3. Call LauncherRunner
*
*/
public void submitTopology() throws TopologySubmissionException {
// build primary runtime config first
Config primaryRuntime = Config.newBuilder()
.putAll(LauncherUtils.getInstance().createPrimaryRuntime(topology)).build();
// call launcher directly here if in dry-run mode
if (Context.dryRun(config)) {
callLauncherRunner(primaryRuntime);
return;
}
// 1. Do prepare work
// create an instance of state manager
String statemgrClass = Context.stateManagerClass(config);
IStateManager statemgr;
// Create an instance of the launcher class
String launcherClass = Context.launcherClass(config);
ILauncher launcher;
// create an instance of the uploader class
String uploaderClass = Context.uploaderClass(config);
IUploader uploader;
// create an instance of state manager
try {
statemgr = ReflectionUtils.newInstance(statemgrClass);
} catch (IllegalAccessException | InstantiationException | ClassNotFoundException e) {
throw new TopologySubmissionException(
String.format("Failed to instantiate state manager class '%s'", statemgrClass), e);
}
// create an instance of launcher
try {
launcher = ReflectionUtils.newInstance(launcherClass);
} catch (IllegalAccessException | InstantiationException | ClassNotFoundException e) {
throw new LauncherException(
String.format("Failed to instantiate launcher class '%s'", launcherClass), e);
}
// create an instance of uploader
try {
uploader = ReflectionUtils.newInstance(uploaderClass);
} catch (IllegalAccessException | InstantiationException | ClassNotFoundException e) {
throw new UploaderException(
String.format("Failed to instantiate uploader class '%s'", uploaderClass), e);
}
// Put it in a try block so that we can always clean resources
try {
// initialize the state manager
statemgr.initialize(config);
// initialize the uploader
uploader.initialize(config);
// TODO(mfu): timeout should read from config
SchedulerStateManagerAdaptor adaptor = new SchedulerStateManagerAdaptor(statemgr, 5000);
// Check if topology is already running
validateSubmit(adaptor, topology.getName());
LOG.log(Level.FINE, "Topology {0} to be submitted", topology.getName());
Config runtimeWithoutPackageURI = Config.newBuilder()
.putAll(primaryRuntime)
.putAll(LauncherUtils.getInstance().createAdaptorRuntime(adaptor))
.put(Key.LAUNCHER_CLASS_INSTANCE, launcher)
.build();
PackingPlan packingPlan = LauncherUtils.getInstance()
.createPackingPlan(config, runtimeWithoutPackageURI);
// The packing plan might call for a number of containers different than the config
// settings. If that's the case we need to modify the configs to match.
runtimeWithoutPackageURI =
updateNumContainersIfNeeded(runtimeWithoutPackageURI, topology, packingPlan);
// If the packing plan is valid we will upload necessary packages
URI packageURI = uploadPackage(uploader);
// Update the runtime config with the packageURI
Config runtimeAll = Config.newBuilder()
.putAll(runtimeWithoutPackageURI)
.put(Key.TOPOLOGY_PACKAGE_URI, packageURI)
.build();
callLauncherRunner(runtimeAll);
} catch (LauncherException | PackingException e) {
// we undo uploading of topology package only if launcher fails to
// launch topology, which will throw LauncherException or PackingException
uploader.undo();
throw e;
} finally {
SysUtils.closeIgnoringExceptions(uploader);
SysUtils.closeIgnoringExceptions(launcher);
SysUtils.closeIgnoringExceptions(statemgr);
}
}
/**
* Checks that the number of containers specified in the topology matches the number of containers
* called for in the packing plan. If they are different, returns a new config with settings
* updated to align with the packing plan. The new config will include an updated
* Key.TOPOLOGY_DEFINITION containing a cloned Topology with it's settings also updated.
*
* @param initialConfig initial config to clone and update (if necessary)
* @param initialTopology topology to check and clone/update (if necessary)
* @param packingPlan packing plan to compare settings with
* @return a new Config cloned from initialConfig and modified as needed to align with packedPlan
*/
@VisibleForTesting
Config updateNumContainersIfNeeded(Config initialConfig,
TopologyAPI.Topology initialTopology,
PackingPlan packingPlan) {
int configNumStreamManagers = TopologyUtils.getNumContainers(initialTopology);
int packingNumStreamManagers = packingPlan.getContainers().size();
if (configNumStreamManagers == packingNumStreamManagers) {
return initialConfig;
}
Config.Builder newConfigBuilder = Config.newBuilder()
.putAll(initialConfig)
.put(Key.NUM_CONTAINERS, packingNumStreamManagers + 1)
.put(Key.TOPOLOGY_DEFINITION,
cloneWithNewNumContainers(initialTopology, packingNumStreamManagers));
String packingClass = Context.packingClass(config);
LOG.warning(String.format("The packing plan (generated by %s) calls for a different number of "
+ "containers (%d) than what was explicitly set in the topology configs (%d). "
+ "Overriding the configs to specify %d containers. When using %s do not explicitly "
+ "call config.setNumStmgrs(..) or config.setNumWorkers(..).",
packingClass, packingNumStreamManagers, configNumStreamManagers,
packingNumStreamManagers, packingClass));
return newConfigBuilder.build();
}
private TopologyAPI.Topology cloneWithNewNumContainers(TopologyAPI.Topology initialTopology,
int numStreamManagers) {
TopologyAPI.Topology.Builder topologyBuilder = TopologyAPI.Topology.newBuilder(initialTopology);
TopologyAPI.Config.Builder configBuilder = TopologyAPI.Config.newBuilder();
for (TopologyAPI.Config.KeyValue keyValue : initialTopology.getTopologyConfig().getKvsList()) {
// override TOPOLOGY_STMGRS value once we find it
if (org.apache.heron.api.Config.TOPOLOGY_STMGRS.equals(keyValue.getKey())) {
TopologyAPI.Config.KeyValue.Builder kvBuilder = TopologyAPI.Config.KeyValue.newBuilder();
kvBuilder.setKey(keyValue.getKey());
kvBuilder.setValue(Integer.toString(numStreamManagers));
configBuilder.addKvs(kvBuilder.build());
} else {
configBuilder.addKvs(keyValue);
}
}
return topologyBuilder.setTopologyConfig(configBuilder).build();
}
protected void validateSubmit(SchedulerStateManagerAdaptor adaptor, String topologyName)
throws TopologySubmissionException {
// Check whether the topology has already been running
// TODO(rli): anti-pattern is too nested on this path to be refactored
Boolean isTopologyRunning = adaptor.isTopologyRunning(topologyName);
if (isTopologyRunning != null && isTopologyRunning.equals(Boolean.TRUE)) {
throw new TopologySubmissionException(
String.format("Topology '%s' already exists", topologyName));
}
}
protected URI uploadPackage(IUploader uploader) throws UploaderException {
// upload the topology package to the storage
return uploader.uploadPackage();
}
protected void callLauncherRunner(Config runtime)
throws LauncherException, PackingException, SubmitDryRunResponse {
// using launch runner, launch the topology
LaunchRunner launchRunner = new LaunchRunner(config, runtime);
launchRunner.call();
}
}
| Change log level to be severe when exception happens during submission (#3250)
| heron/scheduler-core/src/java/org/apache/heron/scheduler/SubmitterMain.java | Change log level to be severe when exception happens during submission (#3250) |
|
Java | apache-2.0 | 5a22f09d3e328d34d1daa688a75f8592790e64e6 | 0 | gosu-lang/gosu-lang,gosu-lang/gosu-lang,gosu-lang/gosu-lang,gosu-lang/gosu-lang | /*
* Copyright 2014 Guidewire Software, Inc.
*/
package gw.lang.reflect;
import gw.lang.reflect.java.IJavaClassMethod;
import gw.lang.reflect.java.IJavaType;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class PropertyInfoBuilder {
private boolean _isStatic;
private String _name;
private IPropertyAccessor _accessor;
private boolean _readable = true;
private boolean _writable = true;
private IType _type;
private String _description;
private String _deprecated;
private String _javaGetterMethodName;
private List<IAnnotationInfo> _annotations = Collections.emptyList();
private ILocationInfo _locationInfo;
public PropertyInfoBuilder withName(String name) {
_name = name;
return this;
}
public PropertyInfoBuilder withType(IType type) {
_type = type;
return this;
}
public PropertyInfoBuilder withType(Class returnType) {
return withType(TypeSystem.get(returnType));
}
public PropertyInfoBuilder withStatic() {
return withStatic(true);
}
public PropertyInfoBuilder withStatic(boolean isStatic) {
_isStatic = isStatic;
return this;
}
public PropertyInfoBuilder withAccessor(IPropertyAccessor accessor) {
_accessor = accessor;
return this;
}
public PropertyInfoBuilder withGetter(String javaGetterMethodName) {
_javaGetterMethodName = javaGetterMethodName;
return this;
}
public PropertyInfoBuilder withReadable(boolean readable) {
_readable = readable;
return this;
}
public PropertyInfoBuilder withWritable(boolean writable) {
_writable = writable;
return this;
}
public PropertyInfoBuilder withDescription(String description) {
_description = description;
return this;
}
public PropertyInfoBuilder withDeprecated(String deprecated) {
_deprecated = deprecated;
return this;
}
public IPropertyInfo build(IFeatureInfo container) {
return new BuiltPropertyInfo(this, container);
}
public PropertyInfoBuilder withAnnotations( IAnnotationInfo... annotations ) {
_annotations = Arrays.asList(annotations);
return this;
}
public PropertyInfoBuilder like( IPropertyInfo prop ) {
_isStatic = prop.isStatic();
_name = prop.getName();
_accessor = prop.getAccessor();
_readable = prop.isReadable();
_writable = prop.isWritable();
_type = prop.getFeatureType();
_description = prop.getDescription();
if ( prop.isDeprecated() ) {
_deprecated = prop.getDeprecatedReason() == null ? "" : prop.getDeprecatedReason();
}
else {
_deprecated = null;
}
_annotations = prop.getAnnotations(); // todo dlank - any need to step through annotations and recreate 1-by-1?
_locationInfo = prop.getLocationInfo();
return this;
}
public PropertyInfoBuilder withLocation( ILocationInfo locationInfo ) {
_locationInfo = locationInfo;
return this;
}
public static class BuiltPropertyInfo extends BaseFeatureInfo implements IPropertyInfo {
private final boolean _isStatic;
private final String _name;
private final String _javaGetterMethodName;
private IPropertyAccessor _accessor;
private boolean _readable = true; // default to true
private final boolean _writable;
private IType _type;
private final String _description;
private final String _deprecated;
private List<IAnnotationInfo> _annotations = Collections.emptyList();
private final ILocationInfo _locationInfo;
public BuiltPropertyInfo(PropertyInfoBuilder builder, IFeatureInfo container) {
super(container);
assert container != null;
_isStatic = builder._isStatic;
_name = builder._name;
_accessor = builder._accessor;
_javaGetterMethodName = builder._javaGetterMethodName;
_readable = builder._readable;
_writable = builder._writable;
_type = builder._type;
_description = builder._description;
_deprecated = builder._deprecated;
_annotations = builder._annotations;
_locationInfo = builder._locationInfo == null ? ILocationInfo.EMPTY : builder._locationInfo;
inferAccessorAndTypeFromName();
assert _accessor != null;
assert _type != null;
}
public String getJavaMethodName()
{
return _javaGetterMethodName;
}
private void inferAccessorAndTypeFromName()
{
if( _accessor == null && (_type == null || _type instanceof IJavaType) )
{
final IType ownerType = getOwnersType();
if( ownerType instanceof IJavaType )
{
IJavaType propertyType = (IJavaType)_type;
IJavaClassMethod getter;
if( _javaGetterMethodName != null )
{
try
{
getter = ((IJavaType)ownerType).getBackingClassInfo().getMethod( _javaGetterMethodName );
}
catch( NoSuchMethodException e )
{
throw new RuntimeException( e );
}
}
else
{
try
{
getter = ((IJavaType)ownerType).getBackingClassInfo().getMethod( "get" + _name );
}
catch( NoSuchMethodException e )
{
try
{
getter = ((IJavaType)ownerType).getBackingClassInfo().getMethod( "is" + _name );
}
catch( NoSuchMethodException e1 )
{
throw new RuntimeException( e1 );
}
}
}
if( propertyType == null )
{
_type = propertyType = (IJavaType) getter.getReturnType();
}
IJavaClassMethod setter = null;
if( _writable )
{
try
{
setter = ((IJavaType)ownerType).getBackingClassInfo().getMethod( "set" + _name, propertyType.getBackingClassInfo() );
}
catch( NoSuchMethodException e )
{
throw new RuntimeException( e );
}
}
final String getterName = getter.getName();
final String setterName = setter.getName();
_accessor =
new IPropertyAccessor()
{
Method _getMethod = null;
Method _setMethod = null;
public Object getValue( Object ctx )
{
try
{
if( _getMethod == null )
{
_getMethod = ((IJavaType)ownerType).getBackingClass().getMethod( getterName );
}
return _getMethod.invoke( ctx );
}
catch( Exception e )
{
throw new RuntimeException( e );
}
}
public void setValue( Object ctx, Object value )
{
try
{
if( _setMethod == null )
{
_setMethod = ((IJavaType)ownerType).getBackingClass().getMethod( setterName, ((IJavaType)_type).getBackingClass() );
}
_setMethod.invoke( ctx, value );
}
catch( Exception e )
{
throw new RuntimeException( e );
}
}
};
}
}
}
public List<IAnnotationInfo> getDeclaredAnnotations() {
return _annotations;
}
public boolean isStatic() {
return _isStatic;
}
public String getName() {
return _name;
}
public boolean isReadable() {
return _readable;
}
public boolean isWritable(IType whosAskin) {
return _writable;
}
public boolean isWritable() {
return isWritable(null);
}
public IPropertyAccessor getAccessor() {
return _accessor;
}
public IPresentationInfo getPresentationInfo() {
return IPresentationInfo.Default.GET;
}
public IType getFeatureType() {
return _type;
}
public String getDescription() {
return _description;
}
public boolean isDeprecated() {
return _deprecated != null;
}
public String getDeprecatedReason() {
return _deprecated;
}
public String toString() {
return _name;
}
@Override
public ILocationInfo getLocationInfo() {
return _locationInfo;
}
}
}
| gosu-core-api/src/main/java/gw/lang/reflect/PropertyInfoBuilder.java | /*
* Copyright 2014 Guidewire Software, Inc.
*/
package gw.lang.reflect;
import gw.lang.reflect.java.IJavaClassMethod;
import gw.lang.reflect.java.IJavaType;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class PropertyInfoBuilder {
private boolean _isStatic;
private String _name;
private IPropertyAccessor _accessor;
private boolean _readable = true;
private boolean _writable = true;
private IType _type;
private String _description;
private String _deprecated;
private String _javaGetterMethodName;
private List<IAnnotationInfo> _annotations = Collections.emptyList();
private ILocationInfo _locationInfo;
public PropertyInfoBuilder withName(String name) {
_name = name;
return this;
}
public PropertyInfoBuilder withType(IType type) {
_type = type;
return this;
}
public PropertyInfoBuilder withType(Class returnType) {
return withType(TypeSystem.get(returnType));
}
public PropertyInfoBuilder withStatic() {
return withStatic(true);
}
public PropertyInfoBuilder withStatic(boolean isStatic) {
_isStatic = isStatic;
return this;
}
public PropertyInfoBuilder withAccessor(IPropertyAccessor accessor) {
_accessor = accessor;
return this;
}
public PropertyInfoBuilder withGetter(String javaGetterMethodName) {
_javaGetterMethodName = javaGetterMethodName;
return this;
}
public PropertyInfoBuilder withReadable(boolean readable) {
_readable = readable;
return this;
}
public PropertyInfoBuilder withWritable(boolean writable) {
_writable = writable;
return this;
}
public PropertyInfoBuilder withDescription(String description) {
_description = description;
return this;
}
public PropertyInfoBuilder withDeprecated(String deprecated) {
_deprecated = deprecated;
return this;
}
public IPropertyInfo build(IFeatureInfo container) {
return new BuiltPropertyInfo(this, container);
}
public PropertyInfoBuilder withAnnotations( IAnnotationInfo... annotations ) {
_annotations = Arrays.asList(annotations);
return this;
}
public PropertyInfoBuilder like( IPropertyInfo prop ) {
_isStatic = prop.isStatic();
_name = prop.getName();
_accessor = prop.getAccessor();
_readable = prop.isReadable();
_writable = prop.isWritable();
_type = prop.getFeatureType();
_description = prop.getDescription();
if ( prop.isDeprecated() ) {
_deprecated = prop.getDeprecatedReason() == null ? "" : prop.getDeprecatedReason();
}
else {
_deprecated = null;
}
_annotations = prop.getAnnotations(); // todo dlank - any need to step through annotations and recreate 1-by-1?
_locationInfo = prop.getLocationInfo();
return this;
}
public PropertyInfoBuilder withLocation( ILocationInfo locationInfo ) {
_locationInfo = locationInfo;
return this;
}
public static class BuiltPropertyInfo extends BaseFeatureInfo implements IPropertyInfo {
private final boolean _isStatic;
private final String _name;
private final String _javaGetterMethodName;
private IPropertyAccessor _accessor;
private boolean _readable = true; // default to true
private final boolean _writable;
private IType _type;
private final String _description;
private final String _deprecated;
private List<IAnnotationInfo> _annotations = Collections.emptyList();
private final ILocationInfo _locationInfo;
public BuiltPropertyInfo(PropertyInfoBuilder builder, IFeatureInfo container) {
super(container);
assert container != null;
_isStatic = builder._isStatic;
_name = builder._name;
_accessor = builder._accessor;
_javaGetterMethodName = builder._javaGetterMethodName;
_readable = builder._readable;
_writable = builder._writable;
_type = builder._type;
_description = builder._description;
_deprecated = builder._deprecated;
_annotations = builder._annotations;
_locationInfo = builder._locationInfo == null ? ILocationInfo.EMPTY : builder._locationInfo;
inferAccessorAndTypeFromName();
assert _accessor != null;
assert _type != null;
}
public String getJavaMethodName()
{
return _javaGetterMethodName;
}
private void inferAccessorAndTypeFromName()
{
if( _accessor == null && (_type == null || _type instanceof IJavaType) )
{
IType ownerType = getOwnersType();
if( ownerType instanceof IJavaType )
{
IJavaType propertyType = (IJavaType)_type;
Method runtimeGetter;
IJavaClassMethod compiletimeGetter;
if( _javaGetterMethodName != null )
{
try
{
runtimeGetter = ((IJavaType)ownerType).getBackingClass().getMethod( _javaGetterMethodName );
compiletimeGetter = ((IJavaType)ownerType).getBackingClassInfo().getMethod( _javaGetterMethodName );
}
catch( NoSuchMethodException e )
{
throw new RuntimeException( e );
}
}
else
{
try
{
runtimeGetter = ((IJavaType)ownerType).getBackingClass().getMethod( "get" + _name );
compiletimeGetter = ((IJavaType)ownerType).getBackingClassInfo().getMethod( "get" + _name );
}
catch( NoSuchMethodException e )
{
try
{
runtimeGetter = ((IJavaType)ownerType).getBackingClass().getMethod( "is" + _name );
compiletimeGetter = ((IJavaType)ownerType).getBackingClassInfo().getMethod( "is" + _name );
}
catch( NoSuchMethodException e1 )
{
throw new RuntimeException( e1 );
}
}
}
if( propertyType == null )
{
_type = propertyType = (IJavaType) compiletimeGetter.getReturnType();
}
Method setter = null;
if( _writable )
{
try
{
setter = ((IJavaType)ownerType).getBackingClass().getMethod( "set" + _name, propertyType.getIntrinsicClass() );
}
catch( NoSuchMethodException e )
{
throw new RuntimeException( e );
}
}
final Method getter1 = runtimeGetter;
final Method setter1 = setter;
_accessor =
new IPropertyAccessor()
{
public Object getValue( Object ctx )
{
try
{
return getter1.invoke( ctx );
}
catch( IllegalAccessException e )
{
throw new RuntimeException( e );
}
catch( InvocationTargetException e )
{
throw new RuntimeException( e );
}
}
public void setValue( Object ctx, Object value )
{
try
{
setter1.invoke( ctx, value );
}
catch( IllegalAccessException e )
{
throw new RuntimeException( e );
}
catch( InvocationTargetException e )
{
throw new RuntimeException( e );
}
}
};
}
}
}
public List<IAnnotationInfo> getDeclaredAnnotations() {
return _annotations;
}
public boolean isStatic() {
return _isStatic;
}
public String getName() {
return _name;
}
public boolean isReadable() {
return _readable;
}
public boolean isWritable(IType whosAskin) {
return _writable;
}
public boolean isWritable() {
return isWritable(null);
}
public IPropertyAccessor getAccessor() {
return _accessor;
}
public IPresentationInfo getPresentationInfo() {
return IPresentationInfo.Default.GET;
}
public IType getFeatureType() {
return _type;
}
public String getDescription() {
return _description;
}
public boolean isDeprecated() {
return _deprecated != null;
}
public String getDeprecatedReason() {
return _deprecated;
}
public String toString() {
return _name;
}
@Override
public ILocationInfo getLocationInfo() {
return _locationInfo;
}
}
}
| replace getBackingClass() with more compile-time friendly getBackingClassInfo()
| gosu-core-api/src/main/java/gw/lang/reflect/PropertyInfoBuilder.java | replace getBackingClass() with more compile-time friendly getBackingClassInfo() |
|
Java | apache-2.0 | 8660518dd756a101e6271c00f3278c2e685b5728 | 0 | CodeIntelligenceTesting/jazzer,CodeIntelligenceTesting/jazzer,CodeIntelligenceTesting/jazzer,CodeIntelligenceTesting/jazzer,CodeIntelligenceTesting/jazzer | /*
* Copyright 2022 Code Intelligence GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.code_intelligence.jazzer.driver;
import static java.lang.System.err;
import static java.lang.System.exit;
import static java.lang.System.out;
import static java.util.stream.Collectors.joining;
import com.code_intelligence.jazzer.agent.AgentInstaller;
import com.code_intelligence.jazzer.api.FuzzedDataProvider;
import com.code_intelligence.jazzer.autofuzz.FuzzTarget;
import com.code_intelligence.jazzer.instrumentor.CoverageRecorder;
import com.code_intelligence.jazzer.runtime.FuzzTargetRunnerNatives;
import com.code_intelligence.jazzer.runtime.JazzerInternal;
import com.code_intelligence.jazzer.utils.UnsafeProvider;
import java.io.IOException;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.function.Predicate;
import sun.misc.Unsafe;
/**
* Executes a fuzz target and reports findings.
*
* <p>This class maintains global state (both native and non-native) and thus cannot be used
* concurrently.
*/
public final class FuzzTargetRunner {
static {
AgentInstaller.install(Opt.hooks);
}
private static final String OPENTEST4J_TEST_ABORTED_EXCEPTION =
"org.opentest4j.TestAbortedException";
private static final Unsafe UNSAFE = UnsafeProvider.getUnsafe();
private static final long BYTE_ARRAY_OFFSET = UNSAFE.arrayBaseOffset(byte[].class);
// Default value of the libFuzzer -error_exitcode flag.
private static final int LIBFUZZER_ERROR_EXIT_CODE = 77;
// Possible return values for the libFuzzer callback runOne.
private static final int LIBFUZZER_CONTINUE = 0;
private static final int LIBFUZZER_RETURN_FROM_DRIVER = -2;
private static final Set<Long> ignoredTokens = new HashSet<>(Opt.ignore);
private static final FuzzedDataProviderImpl fuzzedDataProvider =
FuzzedDataProviderImpl.withNativeData();
private static final Class<?> fuzzTargetClass;
private static final MethodHandle fuzzTargetMethod;
private static final boolean useFuzzedDataProvider;
// Reused in every iteration analogous to JUnit's PER_CLASS lifecycle.
private static final Object fuzzTargetInstance;
private static final Method fuzzerTearDown;
private static final ReproducerTemplate reproducerTemplate;
private static Predicate<Throwable> findingHandler;
static {
String targetClassName = FuzzTargetFinder.findFuzzTargetClassName();
if (targetClassName == null) {
err.println("Missing argument --target_class=<fuzz_target_class>");
exit(1);
throw new IllegalStateException("Not reached");
}
try {
FuzzTargetRunner.class.getClassLoader().setDefaultAssertionStatus(true);
fuzzTargetClass =
Class.forName(targetClassName, false, FuzzTargetRunner.class.getClassLoader());
} catch (ClassNotFoundException e) {
err.printf(
"ERROR: '%s' not found on classpath:%n%n%s%n%nAll required classes must be on the classpath specified via --cp.%n",
targetClassName, System.getProperty("java.class.path"));
exit(1);
throw new IllegalStateException("Not reached");
}
// Inform the agent about the fuzz target class. Important note: This has to be done *before*
// the class is initialized so that hooks can enable themselves in time for the fuzz target's
// static initializer.
JazzerInternal.onFuzzTargetReady(targetClassName);
FuzzTargetFinder.FuzzTarget fuzzTarget;
try {
fuzzTarget = FuzzTargetFinder.findFuzzTarget(fuzzTargetClass);
} catch (IllegalArgumentException e) {
err.printf("ERROR: %s%n", e.getMessage());
exit(1);
throw new IllegalStateException("Not reached");
}
try {
fuzzTargetMethod = MethodHandles.lookup().unreflect(fuzzTarget.method);
} catch (IllegalAccessException e) {
// Should have been made accessible in FuzzTargetFinder.
throw new IllegalStateException(e);
}
useFuzzedDataProvider = fuzzTarget.useFuzzedDataProvider;
fuzzerTearDown = fuzzTarget.tearDown.orElse(null);
reproducerTemplate = new ReproducerTemplate(fuzzTargetClass.getName(), useFuzzedDataProvider);
try {
fuzzTargetInstance = fuzzTarget.newInstance.call();
} catch (Throwable e) {
err.print("== Java Exception during initialization: ");
e.printStackTrace(err);
exit(1);
throw new IllegalStateException("Not reached");
}
if (Opt.hooks) {
// libFuzzer will clear the coverage map after this method returns and keeps no record of the
// coverage accumulated so far (e.g. by static initializers). We record it here to keep it
// around for JaCoCo coverage reports.
CoverageRecorder.updateCoveredIdsWithCoverageMap();
}
Runtime.getRuntime().addShutdownHook(new Thread(FuzzTargetRunner::shutdown));
}
/**
* A test-only convenience wrapper around {@link #runOne(long, int)}.
*/
static int runOne(byte[] data) {
long dataPtr = UNSAFE.allocateMemory(data.length);
UNSAFE.copyMemory(data, BYTE_ARRAY_OFFSET, null, dataPtr, data.length);
try {
return runOne(dataPtr, data.length);
} finally {
UNSAFE.freeMemory(dataPtr);
}
}
/**
* Executes the user-provided fuzz target once.
*
* @param dataPtr a native pointer to beginning of the input provided by the fuzzer for this
* execution
* @param dataLength length of the fuzzer input
* @return the value that the native LLVMFuzzerTestOneInput function should return. Currently,
* this is always 0. The function may exit the process instead of returning.
*/
private static int runOne(long dataPtr, int dataLength) {
Throwable finding = null;
byte[] data;
Object argument;
if (useFuzzedDataProvider) {
fuzzedDataProvider.setNativeData(dataPtr, dataLength);
data = null;
argument = fuzzedDataProvider;
} else {
data = copyToArray(dataPtr, dataLength);
argument = data;
}
try {
if (fuzzTargetInstance == null) {
fuzzTargetMethod.invoke(argument);
} else {
fuzzTargetMethod.invoke(fuzzTargetInstance, argument);
}
} catch (Throwable uncaughtFinding) {
finding = uncaughtFinding;
}
// When using libFuzzer's -merge flag, only the coverage of the current input is relevant, not
// whether it is crashing. Since every crash would cause a restart of the process and thus the
// JVM, we can optimize this case by not crashing.
//
// Incidentally, this makes the behavior of fuzz targets relying on global states more
// consistent: Rather than resetting the global state after every crashing input and thus
// dependent on the particular ordering of the inputs, we never reset it.
if (Opt.mergeInner) {
return LIBFUZZER_CONTINUE;
}
// Explicitly reported findings take precedence over uncaught exceptions.
if (JazzerInternal.lastFinding != null) {
finding = JazzerInternal.lastFinding;
JazzerInternal.lastFinding = null;
}
// Allow skipping invalid inputs in fuzz tests by using e.g. JUnit's assumeTrue.
if (finding == null || finding.getClass().getName().equals(OPENTEST4J_TEST_ABORTED_EXCEPTION)) {
return LIBFUZZER_CONTINUE;
}
if (Opt.hooks) {
finding = ExceptionUtils.preprocessThrowable(finding);
}
long dedupToken = Opt.dedup ? ExceptionUtils.computeDedupToken(finding) : 0;
if (Opt.dedup && !ignoredTokens.add(dedupToken)) {
return LIBFUZZER_CONTINUE;
}
if (findingHandler != null) {
// We still print the libFuzzer crashing input information, which also dumps the crashing
// input as a side effect.
printCrashingInput();
if (findingHandler.test(finding)) {
return LIBFUZZER_CONTINUE;
} else {
return LIBFUZZER_RETURN_FROM_DRIVER;
}
}
// The user-provided fuzz target method has returned. Any further exits are on us and should not
// result in a "fuzz target exited" warning being printed by libFuzzer.
temporarilyDisableLibfuzzerExitHook();
err.println();
err.print("== Java Exception: ");
finding.printStackTrace(err);
if (Opt.dedup) {
// Has to be printed to stdout as it is parsed by libFuzzer when minimizing a crash. It does
// not necessarily have to appear at the beginning of a line.
// https://github.com/llvm/llvm-project/blob/4c106c93eb68f8f9f201202677cd31e326c16823/compiler-rt/lib/fuzzer/FuzzerDriver.cpp#L342
out.printf(Locale.ROOT, "DEDUP_TOKEN: %016x%n", dedupToken);
}
err.println("== libFuzzer crashing input ==");
printCrashingInput();
// dumpReproducer needs to be called after libFuzzer printed its final stats as otherwise it
// would report incorrect coverage - the reproducer generation involved rerunning the fuzz
// target.
// It doesn't support @FuzzTest fuzz targets, but these come with an integrated regression test
// that satisfies the same purpose.
if (fuzzTargetInstance == null) {
dumpReproducer(data);
}
if (Long.compareUnsigned(ignoredTokens.size(), Opt.keepGoing) >= 0) {
// Reached the maximum amount of findings to keep going for, crash after shutdown. We use
// _Exit rather than System.exit to not trigger libFuzzer's exit handlers.
if (!Opt.autofuzz.isEmpty() && Opt.dedup) {
System.err.printf(
"%nNote: To continue fuzzing past this particular finding, rerun with the following additional argument:"
+ "%n%n --ignore=%s%n%n"
+ "To ignore all findings of this kind, rerun with the following additional argument:"
+ "%n%n --autofuzz_ignore=%s%n",
ignoredTokens.stream()
.map(token -> Long.toUnsignedString(token, 16))
.collect(joining(",")),
finding.getClass().getName());
}
System.exit(LIBFUZZER_ERROR_EXIT_CODE);
throw new IllegalStateException("Not reached");
}
return LIBFUZZER_CONTINUE;
}
/*
* Starts libFuzzer via LLVMFuzzerRunDriver.
*
* Note: Must be public rather than package-private as it is loaded in a different class loader
* than Driver.
*/
public static int startLibFuzzer(List<String> args) {
SignalHandler.initialize();
return startLibFuzzer(Utils.toNativeArgs(args));
}
/**
* Registers a custom handler for findings.
*
* @param findingHandler a consumer for the finding that returns true if the fuzzer should
* continue fuzzing and false
* if it should return from {@link FuzzTargetRunner#startLibFuzzer(List)}.
*/
public static void registerFindingHandler(Predicate<Throwable> findingHandler) {
FuzzTargetRunner.findingHandler = findingHandler;
}
private static void shutdown() {
if (!Opt.coverageDump.isEmpty() || !Opt.coverageReport.isEmpty()) {
if (!Opt.coverageDump.isEmpty()) {
CoverageRecorder.dumpJacocoCoverage(Opt.coverageDump);
}
if (!Opt.coverageReport.isEmpty()) {
CoverageRecorder.dumpCoverageReport(Opt.coverageReport);
}
}
if (fuzzerTearDown == null) {
return;
}
err.println("calling fuzzerTearDown function");
try {
fuzzerTearDown.invoke(null);
} catch (InvocationTargetException e) {
// An exception in fuzzerTearDown is a regular finding.
err.print("== Java Exception in fuzzerTearDown: ");
e.getCause().printStackTrace(err);
System.exit(LIBFUZZER_ERROR_EXIT_CODE);
} catch (Throwable t) {
// Any other exception is an error.
t.printStackTrace(err);
System.exit(1);
}
}
private static void dumpReproducer(byte[] data) {
if (data == null) {
assert useFuzzedDataProvider;
fuzzedDataProvider.reset();
data = fuzzedDataProvider.consumeRemainingAsBytes();
}
MessageDigest digest;
try {
digest = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("SHA-1 not available", e);
}
String dataSha1 = toHexString(digest.digest(data));
if (!Opt.autofuzz.isEmpty()) {
fuzzedDataProvider.reset();
FuzzTarget.dumpReproducer(fuzzedDataProvider, Opt.reproducerPath, dataSha1);
return;
}
String base64Data;
if (useFuzzedDataProvider) {
fuzzedDataProvider.reset();
FuzzedDataProvider recordingFuzzedDataProvider =
RecordingFuzzedDataProvider.makeFuzzedDataProviderProxy(fuzzedDataProvider);
try {
fuzzTargetMethod.invokeExact(recordingFuzzedDataProvider);
if (JazzerInternal.lastFinding == null) {
err.println("Failed to reproduce crash when rerunning with recorder");
}
} catch (Throwable ignored) {
// Expected.
}
try {
base64Data = RecordingFuzzedDataProvider.serializeFuzzedDataProviderProxy(
recordingFuzzedDataProvider);
} catch (IOException e) {
err.print("ERROR: Failed to create reproducer: ");
e.printStackTrace(err);
// Don't let libFuzzer print a native stack trace.
System.exit(1);
throw new IllegalStateException("Not reached");
}
} else {
base64Data = Base64.getEncoder().encodeToString(data);
}
reproducerTemplate.dumpReproducer(base64Data, dataSha1);
}
/**
* Convert a byte array to a lower-case hex string.
*
* <p>The returned hex string always has {@code 2 * bytes.length} characters.
*
* @param bytes the bytes to convert
* @return a lower-case hex string representing the bytes
*/
private static String toHexString(byte[] bytes) {
String unpadded = new BigInteger(1, bytes).toString(16);
int numLeadingZeroes = 2 * bytes.length - unpadded.length();
return String.join("", Collections.nCopies(numLeadingZeroes, "0")) + unpadded;
}
// Accessed by fuzz_target_runner.cpp.
@SuppressWarnings("unused")
private static void dumpAllStackTraces() {
ExceptionUtils.dumpAllStackTraces();
}
private static byte[] copyToArray(long ptr, int length) {
// TODO: Use Unsafe.allocateUninitializedArray instead once Java 9 is the base.
byte[] array = new byte[length];
UNSAFE.copyMemory(null, ptr, array, BYTE_ARRAY_OFFSET, length);
return array;
}
/**
* Starts libFuzzer via LLVMFuzzerRunDriver.
*
* @param args command-line arguments encoded in UTF-8 (not null-terminated)
* @return the return value of LLVMFuzzerRunDriver
*/
private static int startLibFuzzer(byte[][] args) {
return FuzzTargetRunnerNatives.startLibFuzzer(args, FuzzTargetRunner.class);
}
/**
* Causes libFuzzer to write the current input to disk as a crashing input and emit some
* information about it to stderr.
*/
private static void printCrashingInput() {
FuzzTargetRunnerNatives.printCrashingInput();
}
/**
* Disables libFuzzer's fuzz target exit detection until the next call to {@link #runOne}.
*
* <p>Calling {@link System#exit} after having called this method will not trigger libFuzzer's
* exit hook that would otherwise print the "fuzz target exited" error message. This method should
* thus only be called after control has returned from the user-provided fuzz target.
*/
private static void temporarilyDisableLibfuzzerExitHook() {
FuzzTargetRunnerNatives.temporarilyDisableLibfuzzerExitHook();
}
}
| driver/src/main/java/com/code_intelligence/jazzer/driver/FuzzTargetRunner.java | /*
* Copyright 2022 Code Intelligence GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.code_intelligence.jazzer.driver;
import static java.lang.System.err;
import static java.lang.System.exit;
import static java.lang.System.out;
import static java.util.stream.Collectors.joining;
import com.code_intelligence.jazzer.agent.AgentInstaller;
import com.code_intelligence.jazzer.api.FuzzedDataProvider;
import com.code_intelligence.jazzer.autofuzz.FuzzTarget;
import com.code_intelligence.jazzer.instrumentor.CoverageRecorder;
import com.code_intelligence.jazzer.runtime.FuzzTargetRunnerNatives;
import com.code_intelligence.jazzer.runtime.JazzerInternal;
import com.code_intelligence.jazzer.utils.UnsafeProvider;
import java.io.IOException;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.function.Predicate;
import sun.misc.Unsafe;
/**
* Executes a fuzz target and reports findings.
*
* <p>This class maintains global state (both native and non-native) and thus cannot be used
* concurrently.
*/
public final class FuzzTargetRunner {
static {
AgentInstaller.install(Opt.hooks);
}
private static final String OPENTEST4J_TEST_ABORTED_EXCEPTION =
"org.opentest4j.TestAbortedException";
private static final Unsafe UNSAFE = UnsafeProvider.getUnsafe();
private static final long BYTE_ARRAY_OFFSET = UNSAFE.arrayBaseOffset(byte[].class);
// Default value of the libFuzzer -error_exitcode flag.
private static final int LIBFUZZER_ERROR_EXIT_CODE = 77;
// Possible return values for the libFuzzer callback runOne.
private static final int LIBFUZZER_CONTINUE = 0;
private static final int LIBFUZZER_RETURN_FROM_DRIVER = -2;
private static final Set<Long> ignoredTokens = new HashSet<>(Opt.ignore);
private static final FuzzedDataProviderImpl fuzzedDataProvider =
FuzzedDataProviderImpl.withNativeData();
private static final Class<?> fuzzTargetClass;
private static final MethodHandle fuzzTargetMethod;
private static final boolean useFuzzedDataProvider;
// Reused in every iteration analogous to JUnit's PER_CLASS lifecycle.
private static final Object fuzzTargetInstance;
private static final Method fuzzerTearDown;
private static final ReproducerTemplate reproducerTemplate;
private static Predicate<Throwable> findingHandler;
static {
String targetClassName = FuzzTargetFinder.findFuzzTargetClassName();
if (targetClassName == null) {
err.println("Missing argument --target_class=<fuzz_target_class>");
exit(1);
throw new IllegalStateException("Not reached");
}
try {
FuzzTargetRunner.class.getClassLoader().setDefaultAssertionStatus(true);
fuzzTargetClass =
Class.forName(targetClassName, false, FuzzTargetRunner.class.getClassLoader());
} catch (ClassNotFoundException e) {
err.printf(
"ERROR: '%s' not found on classpath:%n%n%s%n%nAll required classes must be on the classpath specified via --cp.",
targetClassName, System.getProperty("java.class.path"));
exit(1);
throw new IllegalStateException("Not reached");
}
// Inform the agent about the fuzz target class. Important note: This has to be done *before*
// the class is initialized so that hooks can enable themselves in time for the fuzz target's
// static initializer.
JazzerInternal.onFuzzTargetReady(targetClassName);
FuzzTargetFinder.FuzzTarget fuzzTarget;
try {
fuzzTarget = FuzzTargetFinder.findFuzzTarget(fuzzTargetClass);
} catch (IllegalArgumentException e) {
err.printf("ERROR: %s%n", e.getMessage());
exit(1);
throw new IllegalStateException("Not reached");
}
try {
fuzzTargetMethod = MethodHandles.lookup().unreflect(fuzzTarget.method);
} catch (IllegalAccessException e) {
// Should have been made accessible in FuzzTargetFinder.
throw new IllegalStateException(e);
}
useFuzzedDataProvider = fuzzTarget.useFuzzedDataProvider;
fuzzerTearDown = fuzzTarget.tearDown.orElse(null);
reproducerTemplate = new ReproducerTemplate(fuzzTargetClass.getName(), useFuzzedDataProvider);
try {
fuzzTargetInstance = fuzzTarget.newInstance.call();
} catch (Throwable e) {
err.print("== Java Exception during initialization: ");
e.printStackTrace(err);
exit(1);
throw new IllegalStateException("Not reached");
}
if (Opt.hooks) {
// libFuzzer will clear the coverage map after this method returns and keeps no record of the
// coverage accumulated so far (e.g. by static initializers). We record it here to keep it
// around for JaCoCo coverage reports.
CoverageRecorder.updateCoveredIdsWithCoverageMap();
}
Runtime.getRuntime().addShutdownHook(new Thread(FuzzTargetRunner::shutdown));
}
/**
* A test-only convenience wrapper around {@link #runOne(long, int)}.
*/
static int runOne(byte[] data) {
long dataPtr = UNSAFE.allocateMemory(data.length);
UNSAFE.copyMemory(data, BYTE_ARRAY_OFFSET, null, dataPtr, data.length);
try {
return runOne(dataPtr, data.length);
} finally {
UNSAFE.freeMemory(dataPtr);
}
}
/**
* Executes the user-provided fuzz target once.
*
* @param dataPtr a native pointer to beginning of the input provided by the fuzzer for this
* execution
* @param dataLength length of the fuzzer input
* @return the value that the native LLVMFuzzerTestOneInput function should return. Currently,
* this is always 0. The function may exit the process instead of returning.
*/
private static int runOne(long dataPtr, int dataLength) {
Throwable finding = null;
byte[] data;
Object argument;
if (useFuzzedDataProvider) {
fuzzedDataProvider.setNativeData(dataPtr, dataLength);
data = null;
argument = fuzzedDataProvider;
} else {
data = copyToArray(dataPtr, dataLength);
argument = data;
}
try {
if (fuzzTargetInstance == null) {
fuzzTargetMethod.invoke(argument);
} else {
fuzzTargetMethod.invoke(fuzzTargetInstance, argument);
}
} catch (Throwable uncaughtFinding) {
finding = uncaughtFinding;
}
// When using libFuzzer's -merge flag, only the coverage of the current input is relevant, not
// whether it is crashing. Since every crash would cause a restart of the process and thus the
// JVM, we can optimize this case by not crashing.
//
// Incidentally, this makes the behavior of fuzz targets relying on global states more
// consistent: Rather than resetting the global state after every crashing input and thus
// dependent on the particular ordering of the inputs, we never reset it.
if (Opt.mergeInner) {
return LIBFUZZER_CONTINUE;
}
// Explicitly reported findings take precedence over uncaught exceptions.
if (JazzerInternal.lastFinding != null) {
finding = JazzerInternal.lastFinding;
JazzerInternal.lastFinding = null;
}
// Allow skipping invalid inputs in fuzz tests by using e.g. JUnit's assumeTrue.
if (finding == null || finding.getClass().getName().equals(OPENTEST4J_TEST_ABORTED_EXCEPTION)) {
return LIBFUZZER_CONTINUE;
}
if (Opt.hooks) {
finding = ExceptionUtils.preprocessThrowable(finding);
}
long dedupToken = Opt.dedup ? ExceptionUtils.computeDedupToken(finding) : 0;
if (Opt.dedup && !ignoredTokens.add(dedupToken)) {
return LIBFUZZER_CONTINUE;
}
if (findingHandler != null) {
// We still print the libFuzzer crashing input information, which also dumps the crashing
// input as a side effect.
printCrashingInput();
if (findingHandler.test(finding)) {
return LIBFUZZER_CONTINUE;
} else {
return LIBFUZZER_RETURN_FROM_DRIVER;
}
}
// The user-provided fuzz target method has returned. Any further exits are on us and should not
// result in a "fuzz target exited" warning being printed by libFuzzer.
temporarilyDisableLibfuzzerExitHook();
err.println();
err.print("== Java Exception: ");
finding.printStackTrace(err);
if (Opt.dedup) {
// Has to be printed to stdout as it is parsed by libFuzzer when minimizing a crash. It does
// not necessarily have to appear at the beginning of a line.
// https://github.com/llvm/llvm-project/blob/4c106c93eb68f8f9f201202677cd31e326c16823/compiler-rt/lib/fuzzer/FuzzerDriver.cpp#L342
out.printf(Locale.ROOT, "DEDUP_TOKEN: %016x%n", dedupToken);
}
err.println("== libFuzzer crashing input ==");
printCrashingInput();
// dumpReproducer needs to be called after libFuzzer printed its final stats as otherwise it
// would report incorrect coverage - the reproducer generation involved rerunning the fuzz
// target.
// It doesn't support @FuzzTest fuzz targets, but these come with an integrated regression test
// that satisfies the same purpose.
if (fuzzTargetInstance == null) {
dumpReproducer(data);
}
if (Long.compareUnsigned(ignoredTokens.size(), Opt.keepGoing) >= 0) {
// Reached the maximum amount of findings to keep going for, crash after shutdown. We use
// _Exit rather than System.exit to not trigger libFuzzer's exit handlers.
if (!Opt.autofuzz.isEmpty() && Opt.dedup) {
System.err.printf(
"%nNote: To continue fuzzing past this particular finding, rerun with the following additional argument:"
+ "%n%n --ignore=%s%n%n"
+ "To ignore all findings of this kind, rerun with the following additional argument:"
+ "%n%n --autofuzz_ignore=%s%n",
ignoredTokens.stream()
.map(token -> Long.toUnsignedString(token, 16))
.collect(joining(",")),
finding.getClass().getName());
}
System.exit(LIBFUZZER_ERROR_EXIT_CODE);
throw new IllegalStateException("Not reached");
}
return LIBFUZZER_CONTINUE;
}
/*
* Starts libFuzzer via LLVMFuzzerRunDriver.
*
* Note: Must be public rather than package-private as it is loaded in a different class loader
* than Driver.
*/
public static int startLibFuzzer(List<String> args) {
SignalHandler.initialize();
return startLibFuzzer(Utils.toNativeArgs(args));
}
/**
* Registers a custom handler for findings.
*
* @param findingHandler a consumer for the finding that returns true if the fuzzer should
* continue fuzzing and false
* if it should return from {@link FuzzTargetRunner#startLibFuzzer(List)}.
*/
public static void registerFindingHandler(Predicate<Throwable> findingHandler) {
FuzzTargetRunner.findingHandler = findingHandler;
}
private static void shutdown() {
if (!Opt.coverageDump.isEmpty() || !Opt.coverageReport.isEmpty()) {
if (!Opt.coverageDump.isEmpty()) {
CoverageRecorder.dumpJacocoCoverage(Opt.coverageDump);
}
if (!Opt.coverageReport.isEmpty()) {
CoverageRecorder.dumpCoverageReport(Opt.coverageReport);
}
}
if (fuzzerTearDown == null) {
return;
}
err.println("calling fuzzerTearDown function");
try {
fuzzerTearDown.invoke(null);
} catch (InvocationTargetException e) {
// An exception in fuzzerTearDown is a regular finding.
err.print("== Java Exception in fuzzerTearDown: ");
e.getCause().printStackTrace(err);
System.exit(LIBFUZZER_ERROR_EXIT_CODE);
} catch (Throwable t) {
// Any other exception is an error.
t.printStackTrace(err);
System.exit(1);
}
}
private static void dumpReproducer(byte[] data) {
if (data == null) {
assert useFuzzedDataProvider;
fuzzedDataProvider.reset();
data = fuzzedDataProvider.consumeRemainingAsBytes();
}
MessageDigest digest;
try {
digest = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("SHA-1 not available", e);
}
String dataSha1 = toHexString(digest.digest(data));
if (!Opt.autofuzz.isEmpty()) {
fuzzedDataProvider.reset();
FuzzTarget.dumpReproducer(fuzzedDataProvider, Opt.reproducerPath, dataSha1);
return;
}
String base64Data;
if (useFuzzedDataProvider) {
fuzzedDataProvider.reset();
FuzzedDataProvider recordingFuzzedDataProvider =
RecordingFuzzedDataProvider.makeFuzzedDataProviderProxy(fuzzedDataProvider);
try {
fuzzTargetMethod.invokeExact(recordingFuzzedDataProvider);
if (JazzerInternal.lastFinding == null) {
err.println("Failed to reproduce crash when rerunning with recorder");
}
} catch (Throwable ignored) {
// Expected.
}
try {
base64Data = RecordingFuzzedDataProvider.serializeFuzzedDataProviderProxy(
recordingFuzzedDataProvider);
} catch (IOException e) {
err.print("ERROR: Failed to create reproducer: ");
e.printStackTrace(err);
// Don't let libFuzzer print a native stack trace.
System.exit(1);
throw new IllegalStateException("Not reached");
}
} else {
base64Data = Base64.getEncoder().encodeToString(data);
}
reproducerTemplate.dumpReproducer(base64Data, dataSha1);
}
/**
* Convert a byte array to a lower-case hex string.
*
* <p>The returned hex string always has {@code 2 * bytes.length} characters.
*
* @param bytes the bytes to convert
* @return a lower-case hex string representing the bytes
*/
private static String toHexString(byte[] bytes) {
String unpadded = new BigInteger(1, bytes).toString(16);
int numLeadingZeroes = 2 * bytes.length - unpadded.length();
return String.join("", Collections.nCopies(numLeadingZeroes, "0")) + unpadded;
}
// Accessed by fuzz_target_runner.cpp.
@SuppressWarnings("unused")
private static void dumpAllStackTraces() {
ExceptionUtils.dumpAllStackTraces();
}
private static byte[] copyToArray(long ptr, int length) {
// TODO: Use Unsafe.allocateUninitializedArray instead once Java 9 is the base.
byte[] array = new byte[length];
UNSAFE.copyMemory(null, ptr, array, BYTE_ARRAY_OFFSET, length);
return array;
}
/**
* Starts libFuzzer via LLVMFuzzerRunDriver.
*
* @param args command-line arguments encoded in UTF-8 (not null-terminated)
* @return the return value of LLVMFuzzerRunDriver
*/
private static int startLibFuzzer(byte[][] args) {
return FuzzTargetRunnerNatives.startLibFuzzer(args, FuzzTargetRunner.class);
}
/**
* Causes libFuzzer to write the current input to disk as a crashing input and emit some
* information about it to stderr.
*/
private static void printCrashingInput() {
FuzzTargetRunnerNatives.printCrashingInput();
}
/**
* Disables libFuzzer's fuzz target exit detection until the next call to {@link #runOne}.
*
* <p>Calling {@link System#exit} after having called this method will not trigger libFuzzer's
* exit hook that would otherwise print the "fuzz target exited" error message. This method should
* thus only be called after control has returned from the user-provided fuzz target.
*/
private static void temporarilyDisableLibfuzzerExitHook() {
FuzzTargetRunnerNatives.temporarilyDisableLibfuzzerExitHook();
}
}
| driver: Add missing newline to error message
| driver/src/main/java/com/code_intelligence/jazzer/driver/FuzzTargetRunner.java | driver: Add missing newline to error message |
|
Java | apache-2.0 | 7c43bfb2b7b5a8a3ce327b0586b1f079ae2c0233 | 0 | greeun/plankton | package com.withwiz.plankton.network;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* Network address helper class<BR/>
* Created by uni4love on 2010. 05. 27..
*/
public class AddressHelper
{
/**
* logger
*/
private Logger log = LoggerFactory.getLogger(AddressHelper.class);
/**
* return localhost IP address.<BR/>
*
* @return IP address
*/
public static StringBuffer getLocalhostAddress()
{
InetAddress iaLocalAddress = null;
try
{
iaLocalAddress = InetAddress.getLocalHost();
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
if (iaLocalAddress == null)
{
return null;
}
return getIp(iaLocalAddress);
}
/**
* return IP address(xxx.xxx.xxx.xxx)<BR/>
*
* @param ia
* InetAddress instance
* @return IP address(xxx.xxx.xxx.xxx)
*/
public static StringBuffer getIp(InetAddress ia)
{
byte[] address = ia.getAddress();
StringBuffer sb = new StringBuffer();
// filtering IP
for (int i = 0; i < address.length; i++)
{
int unsignedByte = address[i] < 0 ? address[i] + 256 : address[i];
sb.append(unsignedByte);
if ((address.length - i) != 1)
sb.append(".");
}
return sb;
}
/**
* return port of the socket.<BR/>
*
* @param socket
* Socket instance
* @return port number
*/
public static int getPort(Socket socket)
{
return socket.getPort();
}
/**
* return address(IP:PORT) of remote client from socket.<BR/>
*
* @param socket
* Socket instance
* @return address
*/
public static StringBuffer getTargetAddress(Socket socket)
{
return getIp(socket.getInetAddress()).append(":")
.append(getPort(socket));
}
/**
* return IP addresses from domain name.<BR/>
*
* @param domainName
* domain name
* @return IP address array
*/
public static String[] getDomain2Ip(String domainName)
{
// A domain can have multiple IP.
InetAddress[] ip;
String[] ipAddress = null;
try
{
ip = InetAddress.getAllByName(domainName);
ipAddress = new String[ip.length];
for (int i = 0; i < ip.length; i++)
{
ipAddress[i] = ip[i].getHostAddress();
}
}
catch (Exception ex)
{
System.out.println(">>> Error : " + ex.toString());
ex.printStackTrace();
}
return ipAddress;
}
/**
* return IP addresses from domain name.<BR/>
*
* @param domainName
* domain name
* @return IP address array
*/
public static String[] nslookup(String domainName)
{
return getDomain2Ip(domainName);
}
/**
* test main
*
* @param args
*/
public static void main(String args[])
{
AddressHelper test = new AddressHelper();
System.out.println("Localhost InetAddress : "
+ AddressHelper.getLocalhostAddress());
String domain = "www.yahoo.com";
System.out.println("> Your computer's IP address is "
+ AddressHelper.getLocalhostAddress());
for (int temp = 0; temp < AddressHelper
.getDomain2Ip(domain).length; temp++)
{
System.out.println(new StringBuffer().append("> \"").append(domain)
.append("\" domain IP address No.").append(temp + 1)
.append(" is ").append(getDomain2Ip(domain)[temp]));
}
for (int temp = 0; temp < AddressHelper.nslookup(domain).length; temp++)
{
System.out.println(new StringBuffer().append("> \"").append(domain)
.append("\" nslookup result No.").append(temp + 1)
.append(" is ")
.append(AddressHelper.nslookup(domain)[temp]));
}
}
}
| src/main/java/com/withwiz/plankton/network/AddressHelper.java | package com.withwiz.plankton.network;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* Network address helper class<BR/>
* Created by uni4love on 2010. 05. 27..
*/
public class AddressHelper
{
/**
* logger
*/
private Logger log = LoggerFactory.getLogger(AddressHelper.class);
/**
* return localhost IP address.<BR/>
*
* @return IP address
*/
public static StringBuffer getLocalhostAddress()
{
InetAddress iaLocalAddress = null;
try
{
iaLocalAddress = InetAddress.getLocalHost();
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
if (iaLocalAddress == null)
{
return null;
}
return getIP(iaLocalAddress);
}
/**
* return IP address(xxx.xxx.xxx.xxx)<BR/>
*
* @param ia
* InetAddress instance
* @return IP address(xxx.xxx.xxx.xxx)
*/
public static StringBuffer getIP(InetAddress ia)
{
byte[] address = ia.getAddress();
StringBuffer sb = new StringBuffer();
// filtering IP
for (int i = 0; i < address.length; i++)
{
int unsignedByte = address[i] < 0 ? address[i] + 256 : address[i];
sb.append(unsignedByte);
if ((address.length - i) != 1)
sb.append(".");
}
return sb;
}
/**
* return port of the socket.<BR/>
*
* @param socket
* Socket instance
* @return port number
*/
public static int getPORT(Socket socket)
{
return socket.getPort();
}
/**
* return address(IP:PORT) of remote client from socket.<BR/>
*
* @param socket
* Socket instance
* @return address
*/
public static StringBuffer getTargetAddress(Socket socket)
{
return getIP(socket.getInetAddress()).append(":")
.append(getPORT(socket));
}
/**
* return IP addresses from domain name.<BR/>
*
* @param domainName
* domain name
* @return IP address array
*/
public static String[] getDomain2IP(String domainName)
{
// A domain can have multiple IP.
InetAddress[] ip;
String[] ipAddress = null;
try
{
ip = InetAddress.getAllByName(domainName);
ipAddress = new String[ip.length];
for (int i = 0; i < ip.length; i++)
{
ipAddress[i] = ip[i].getHostAddress();
}
}
catch (Exception ex)
{
System.out.println(">>> Error : " + ex.toString());
ex.printStackTrace();
}
return ipAddress;
}
/**
* return IP addresses from domain name.<BR/>
*
* @param domainName
* domain name
* @return IP address array
*/
public static String[] nslookup(String domainName)
{
return getDomain2IP(domainName);
}
/**
* test main
*
* @param args
*/
public static void main(String args[])
{
AddressHelper test = new AddressHelper();
System.out.println("Localhost InetAddress : "
+ AddressHelper.getLocalhostAddress());
String domain = "www.yahoo.com";
System.out.println("> Your computer's IP address is "
+ AddressHelper.getLocalhostAddress());
for (int temp = 0; temp < AddressHelper
.getDomain2IP(domain).length; temp++)
{
System.out.println(new StringBuffer().append("> \"").append(domain)
.append("\" domain IP address No.").append(temp + 1)
.append(" is ").append(getDomain2IP(domain)[temp]));
}
for (int temp = 0; temp < AddressHelper.nslookup(domain).length; temp++)
{
System.out.println(new StringBuffer().append("> \"").append(domain)
.append("\" nslookup result No.").append(temp + 1)
.append(" is ")
.append(AddressHelper.nslookup(domain)[temp]));
}
}
}
| - method name changed.
| src/main/java/com/withwiz/plankton/network/AddressHelper.java | - method name changed. |
|
Java | apache-2.0 | 3df01eb1c607f2a316810550b51b5965863a26a3 | 0 | GerritCodeReview/gerrit,WANdisco/gerrit,gerrit-review/gerrit,gerrit-review/gerrit,WANdisco/gerrit,qtproject/qtqa-gerrit,qtproject/qtqa-gerrit,GerritCodeReview/gerrit,qtproject/qtqa-gerrit,gerrit-review/gerrit,WANdisco/gerrit,qtproject/qtqa-gerrit,GerritCodeReview/gerrit,WANdisco/gerrit,WANdisco/gerrit,qtproject/qtqa-gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,gerrit-review/gerrit,qtproject/qtqa-gerrit,GerritCodeReview/gerrit,qtproject/qtqa-gerrit,gerrit-review/gerrit,GerritCodeReview/gerrit,WANdisco/gerrit,gerrit-review/gerrit,WANdisco/gerrit,gerrit-review/gerrit,GerritCodeReview/gerrit | // Copyright (C) 2013 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.lucene;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.primitives.Ints;
import com.google.gerrit.extensions.events.LifecycleListener;
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.gerrit.server.config.SitePaths;
import com.google.gerrit.server.index.Index;
import com.google.gerrit.server.index.IndexCollection;
import com.google.gerrit.server.index.IndexDefinition;
import com.google.gerrit.server.index.IndexDefinition.IndexFactory;
import com.google.gerrit.server.index.OnlineReindexer;
import com.google.gerrit.server.index.Schema;
import com.google.inject.Inject;
import com.google.inject.ProvisionException;
import com.google.inject.Singleton;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
@Singleton
public class LuceneVersionManager implements LifecycleListener {
private static final Logger log = LoggerFactory
.getLogger(LuceneVersionManager.class);
static final String CHANGES_PREFIX = "changes_";
private static class Version<V> {
private final Schema<V> schema;
private final int version;
private final boolean exists;
private final boolean ready;
private Version(Schema<V> schema, int version, boolean exists,
boolean ready) {
checkArgument(schema == null || schema.getVersion() == version);
this.schema = schema;
this.version = version;
this.exists = exists;
this.ready = ready;
}
}
static Path getDir(SitePaths sitePaths, String prefix, Schema<?> schema) {
return sitePaths.index_dir.resolve(String.format("%s%04d",
prefix, schema.getVersion()));
}
private final SitePaths sitePaths;
private final Map<String, IndexDefinition<?, ?, ?>> defs;
private final Map<String, OnlineReindexer<?, ?, ?>> reindexers;
private final boolean onlineUpgrade;
private final String runReindexMsg;
@Inject
LuceneVersionManager(
@GerritServerConfig Config cfg,
SitePaths sitePaths,
Collection<IndexDefinition<?, ?, ?>> defs) {
this.sitePaths = sitePaths;
this.defs = Maps.newHashMapWithExpectedSize(defs.size());
for (IndexDefinition<?, ?, ?> def : defs) {
this.defs.put(def.getName(), def);
}
reindexers = Maps.newHashMapWithExpectedSize(defs.size());
onlineUpgrade = cfg.getBoolean("index", null, "onlineUpgrade", true);
runReindexMsg =
"No index versions ready; run java -jar " +
sitePaths.gerrit_war.toAbsolutePath() +
" reindex";
}
@Override
public void start() {
GerritIndexStatus cfg;
try {
cfg = new GerritIndexStatus(sitePaths);
} catch (ConfigInvalidException | IOException e) {
throw fail(e);
}
if (!Files.exists(sitePaths.index_dir)) {
throw new ProvisionException(runReindexMsg);
} else if (!Files.exists(sitePaths.index_dir)) {
log.warn("Not a directory: %s", sitePaths.index_dir.toAbsolutePath());
throw new ProvisionException(runReindexMsg);
}
for (IndexDefinition<?, ?, ?> def : defs.values()) {
initIndex(def, cfg);
}
}
private <K, V, I extends Index<K, V>> void initIndex(
IndexDefinition<K, V, I> def, GerritIndexStatus cfg) {
TreeMap<Integer, Version<V>> versions = scanVersions(def, cfg);
// Search from the most recent ready version.
// Write to the most recent ready version and the most recent version.
Version<V> search = null;
List<Version<V>> write = Lists.newArrayListWithCapacity(2);
for (Version<V> v : versions.descendingMap().values()) {
if (v.schema == null) {
continue;
}
if (write.isEmpty() && onlineUpgrade) {
write.add(v);
}
if (v.ready) {
search = v;
if (!write.contains(v)) {
write.add(v);
}
break;
}
}
if (search == null) {
throw new ProvisionException(runReindexMsg);
}
IndexFactory<K, V, I> factory = def.getIndexFactory();
I searchIndex = factory.create(search.schema);
IndexCollection<K, V, I> indexes = def.getIndexCollection();
indexes.setSearchIndex(searchIndex);
for (Version<V> v : write) {
if (v.schema != null) {
if (v.version != search.version) {
indexes.addWriteIndex(factory.create(v.schema));
} else {
indexes.addWriteIndex(searchIndex);
}
}
}
markNotReady(cfg, def.getName(), versions.values(), write);
int latest = write.get(0).version;
OnlineReindexer<K, V, I> reindexer = new OnlineReindexer<>(def, latest);
synchronized (this) {
if (!reindexers.containsKey(def.getName())) {
reindexers.put(def.getName(), reindexer);
if (onlineUpgrade && latest != search.version) {
reindexer.start();
}
}
}
}
/**
* Start the online reindexer if the current index is not already the latest.
*
* @param force start re-index
* @return true if started, otherwise false.
* @throws ReindexerAlreadyRunningException
*/
public synchronized boolean startReindexer(String name, boolean force)
throws ReindexerAlreadyRunningException {
OnlineReindexer<?, ?, ?> reindexer = reindexers.get(name);
validateReindexerNotRunning(reindexer);
if (force || !isCurrentIndexVersionLatest(name, reindexer)) {
reindexer.start();
return true;
}
return false;
}
/**
* Activate the latest index if the current index is not already the latest.
*
* @return true if index was activate, otherwise false.
* @throws ReindexerAlreadyRunningException
*/
public synchronized boolean activateLatestIndex(String name)
throws ReindexerAlreadyRunningException {
OnlineReindexer<?, ?, ?> reindexer = reindexers.get(name);
validateReindexerNotRunning(reindexer);
if (!isCurrentIndexVersionLatest(name, reindexer)) {
reindexer.activateIndex();
return true;
}
return false;
}
private boolean isCurrentIndexVersionLatest(
String name, OnlineReindexer<?, ?, ?> reindexer) {
int readVersion = defs.get(name).getIndexCollection().getSearchIndex()
.getSchema().getVersion();
return reindexer == null
|| reindexer.getVersion() == readVersion;
}
private static void validateReindexerNotRunning(
OnlineReindexer<?, ?, ?> reindexer)
throws ReindexerAlreadyRunningException {
if (reindexer != null && reindexer.isRunning()) {
throw new ReindexerAlreadyRunningException();
}
}
private <K, V, I extends Index<K, V>> TreeMap<Integer, Version<V>>
scanVersions(IndexDefinition<K, V, I> def, GerritIndexStatus cfg) {
TreeMap<Integer, Version<V>> versions = new TreeMap<>();
for (Schema<V> schema : def.getSchemas().values()) {
// This part is Lucene-specific.
Path p = getDir(sitePaths, def.getName(), schema);
boolean isDir = Files.isDirectory(p);
if (Files.exists(p) && !isDir) {
log.warn("Not a directory: %s", p.toAbsolutePath());
}
int v = schema.getVersion();
versions.put(v, new Version<>(
schema, v, isDir, cfg.getReady(def.getName(), v)));
}
String prefix = def.getName() + "_";
try (DirectoryStream<Path> paths =
Files.newDirectoryStream(sitePaths.index_dir)) {
for (Path p : paths) {
String n = p.getFileName().toString();
if (!n.startsWith(prefix)) {
continue;
}
String versionStr = n.substring(prefix.length());
Integer v = Ints.tryParse(versionStr);
if (v == null || versionStr.length() != 4) {
log.warn("Unrecognized version in index directory: {}",
p.toAbsolutePath());
continue;
}
if (!versions.containsKey(v)) {
versions.put(v, new Version<V>(
null, v, true, cfg.getReady(def.getName(), v)));
}
}
} catch (IOException e) {
log.error("Error scanning index directory: " + sitePaths.index_dir, e);
}
return versions;
}
private <V> void markNotReady(GerritIndexStatus cfg, String name,
Iterable<Version<V>> versions, Collection<Version<V>> inUse) {
boolean dirty = false;
for (Version<V> v : versions) {
if (!inUse.contains(v) && v.exists) {
cfg.setReady(name, v.version, false);
dirty = true;
}
}
if (dirty) {
try {
cfg.save();
} catch (IOException e) {
throw fail(e);
}
}
}
private ProvisionException fail(Throwable t) {
ProvisionException e = new ProvisionException("Error scanning indexes");
e.initCause(t);
throw e;
}
@Override
public void stop() {
// Do nothing; indexes are closed on demand by IndexCollection.
}
}
| gerrit-lucene/src/main/java/com/google/gerrit/lucene/LuceneVersionManager.java | // Copyright (C) 2013 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.lucene;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.primitives.Ints;
import com.google.gerrit.extensions.events.LifecycleListener;
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.gerrit.server.config.SitePaths;
import com.google.gerrit.server.index.Index;
import com.google.gerrit.server.index.IndexCollection;
import com.google.gerrit.server.index.IndexDefinition;
import com.google.gerrit.server.index.IndexDefinition.IndexFactory;
import com.google.gerrit.server.index.OnlineReindexer;
import com.google.gerrit.server.index.Schema;
import com.google.inject.Inject;
import com.google.inject.ProvisionException;
import com.google.inject.Singleton;
import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.lib.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
@Singleton
public class LuceneVersionManager implements LifecycleListener {
private static final Logger log = LoggerFactory
.getLogger(LuceneVersionManager.class);
static final String CHANGES_PREFIX = "changes_";
private static class Version<V> {
private final Schema<V> schema;
private final int version;
private final boolean exists;
private final boolean ready;
private Version(Schema<V> schema, int version, boolean exists,
boolean ready) {
checkArgument(schema == null || schema.getVersion() == version);
this.schema = schema;
this.version = version;
this.exists = exists;
this.ready = ready;
}
}
static Path getDir(SitePaths sitePaths, String prefix, Schema<?> schema) {
return sitePaths.index_dir.resolve(String.format("%s%04d",
prefix, schema.getVersion()));
}
private final SitePaths sitePaths;
private final Map<String, IndexDefinition<?, ?, ?>> defs;
private final Map<String, OnlineReindexer<?, ?, ?>> reindexers;
private final boolean onlineUpgrade;
private final String runReindexMsg;
@Inject
LuceneVersionManager(
@GerritServerConfig Config cfg,
SitePaths sitePaths,
Collection<IndexDefinition<?, ?, ?>> defs) {
this.sitePaths = sitePaths;
this.defs = Maps.newHashMapWithExpectedSize(defs.size());
for (IndexDefinition<?, ?, ?> def : defs) {
this.defs.put(def.getName(), def);
}
reindexers = Maps.newHashMapWithExpectedSize(defs.size());
onlineUpgrade = cfg.getBoolean("index", null, "onlineUpgrade", true);
runReindexMsg =
"No index versions ready; run java -jar " +
sitePaths.gerrit_war.toAbsolutePath() +
" reindex";
}
@Override
public void start() {
GerritIndexStatus cfg;
try {
cfg = new GerritIndexStatus(sitePaths);
} catch (ConfigInvalidException | IOException e) {
throw fail(e);
}
if (!Files.exists(sitePaths.index_dir)) {
throw new ProvisionException(runReindexMsg);
} else if (!Files.exists(sitePaths.index_dir)) {
log.warn("Not a directory: %s", sitePaths.index_dir.toAbsolutePath());
throw new ProvisionException(runReindexMsg);
}
for (IndexDefinition<?, ?, ?> def : defs.values()) {
initIndex(def, cfg);
}
}
private <K, V, I extends Index<K, V>> void initIndex(
IndexDefinition<K, V, I> def, GerritIndexStatus cfg) {
TreeMap<Integer, Version<V>> versions = scanVersions(def, cfg);
// Search from the most recent ready version.
// Write to the most recent ready version and the most recent version.
Version<V> search = null;
List<Version<V>> write = Lists.newArrayListWithCapacity(2);
for (Version<V> v : versions.descendingMap().values()) {
if (v.schema == null) {
continue;
}
if (write.isEmpty() && onlineUpgrade) {
write.add(v);
}
if (v.ready) {
search = v;
if (!write.contains(v)) {
write.add(v);
}
break;
}
}
if (search == null) {
throw new ProvisionException(runReindexMsg);
}
IndexFactory<K, V, I> factory = def.getIndexFactory();
I searchIndex = factory.create(search.schema);
IndexCollection<K, V, I> indexes = def.getIndexCollection();
indexes.setSearchIndex(searchIndex);
for (Version<V> v : write) {
if (v.schema != null) {
if (v.version != search.version) {
indexes.addWriteIndex(factory.create(v.schema));
} else {
indexes.addWriteIndex(searchIndex);
}
}
}
markNotReady(cfg, def.getName(), versions.values(), write);
int latest = write.get(0).version;
OnlineReindexer<K, V, I> reindexer = new OnlineReindexer<>(def, latest);
reindexers.put(def.getName(), reindexer);
if (onlineUpgrade && latest != search.version) {
synchronized (this) {
if (!reindexers.containsKey(def.getName())) {
reindexer.start();
}
}
}
}
/**
* Start the online reindexer if the current index is not already the latest.
*
* @param force start re-index
* @return true if started, otherwise false.
* @throws ReindexerAlreadyRunningException
*/
public synchronized boolean startReindexer(String name, boolean force)
throws ReindexerAlreadyRunningException {
OnlineReindexer<?, ?, ?> reindexer = reindexers.get(name);
validateReindexerNotRunning(reindexer);
if (force || !isCurrentIndexVersionLatest(name, reindexer)) {
reindexer.start();
return true;
}
return false;
}
/**
* Activate the latest index if the current index is not already the latest.
*
* @return true if index was activate, otherwise false.
* @throws ReindexerAlreadyRunningException
*/
public synchronized boolean activateLatestIndex(String name)
throws ReindexerAlreadyRunningException {
OnlineReindexer<?, ?, ?> reindexer = reindexers.get(name);
validateReindexerNotRunning(reindexer);
if (!isCurrentIndexVersionLatest(name, reindexer)) {
reindexer.activateIndex();
return true;
}
return false;
}
private boolean isCurrentIndexVersionLatest(
String name, OnlineReindexer<?, ?, ?> reindexer) {
int readVersion = defs.get(name).getIndexCollection().getSearchIndex()
.getSchema().getVersion();
return reindexer == null
|| reindexer.getVersion() == readVersion;
}
private static void validateReindexerNotRunning(
OnlineReindexer<?, ?, ?> reindexer)
throws ReindexerAlreadyRunningException {
if (reindexer != null && reindexer.isRunning()) {
throw new ReindexerAlreadyRunningException();
}
}
private <K, V, I extends Index<K, V>> TreeMap<Integer, Version<V>>
scanVersions(IndexDefinition<K, V, I> def, GerritIndexStatus cfg) {
TreeMap<Integer, Version<V>> versions = new TreeMap<>();
for (Schema<V> schema : def.getSchemas().values()) {
// This part is Lucene-specific.
Path p = getDir(sitePaths, def.getName(), schema);
boolean isDir = Files.isDirectory(p);
if (Files.exists(p) && !isDir) {
log.warn("Not a directory: %s", p.toAbsolutePath());
}
int v = schema.getVersion();
versions.put(v, new Version<>(
schema, v, isDir, cfg.getReady(def.getName(), v)));
}
String prefix = def.getName() + "_";
try (DirectoryStream<Path> paths =
Files.newDirectoryStream(sitePaths.index_dir)) {
for (Path p : paths) {
String n = p.getFileName().toString();
if (!n.startsWith(prefix)) {
continue;
}
String versionStr = n.substring(prefix.length());
Integer v = Ints.tryParse(versionStr);
if (v == null || versionStr.length() != 4) {
log.warn("Unrecognized version in index directory: {}",
p.toAbsolutePath());
continue;
}
if (!versions.containsKey(v)) {
versions.put(v, new Version<V>(
null, v, true, cfg.getReady(def.getName(), v)));
}
}
} catch (IOException e) {
log.error("Error scanning index directory: " + sitePaths.index_dir, e);
}
return versions;
}
private <V> void markNotReady(GerritIndexStatus cfg, String name,
Iterable<Version<V>> versions, Collection<Version<V>> inUse) {
boolean dirty = false;
for (Version<V> v : versions) {
if (!inUse.contains(v) && v.exists) {
cfg.setReady(name, v.version, false);
dirty = true;
}
}
if (dirty) {
try {
cfg.save();
} catch (IOException e) {
throw fail(e);
}
}
}
private ProvisionException fail(Throwable t) {
ProvisionException e = new ProvisionException("Error scanning indexes");
e.initCause(t);
throw e;
}
@Override
public void stop() {
// Do nothing; indexes are closed on demand by IndexCollection.
}
}
| Fix online reindexer not starting
Since Ie88b7effd, the online reindexer was no longer starting
automatically.
Before that change, the OnlineReindexer was only created if index
version was not the latest. The intention of that change was to always
create the OnlineReindexer for the latest index version to allow
forcing a reindex using the ssh command.
The problem is that the way it was implemented, the OnlineReindexer was
created but never started.
Fix this by always creating the OnlineReindexer and starting it if index
version is not latest.
Change-Id: I34c99c041d4665a3dbe76aaeb70e5e759f827ceb
| gerrit-lucene/src/main/java/com/google/gerrit/lucene/LuceneVersionManager.java | Fix online reindexer not starting |
|
Java | apache-2.0 | afcbcd34f5b60c4267d75dbd88a65195ddb2bd35 | 0 | apache/geronimo,apache/geronimo,apache/geronimo,apache/geronimo | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.persistence.builder;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.jar.JarFile;
import javax.xml.namespace.QName;
import org.apache.geronimo.common.DeploymentException;
import org.apache.geronimo.deployment.ClassPathList;
import org.apache.geronimo.deployment.ModuleIDBuilder;
import org.apache.geronimo.deployment.service.EnvironmentBuilder;
import org.apache.geronimo.deployment.xmlbeans.XmlBeansUtil;
import org.apache.geronimo.gbean.AbstractName;
import org.apache.geronimo.gbean.AbstractNameQuery;
import org.apache.geronimo.gbean.GBeanData;
import org.apache.geronimo.gbean.GBeanInfo;
import org.apache.geronimo.gbean.GBeanInfoBuilder;
import org.apache.geronimo.j2ee.deployment.EARContext;
import org.apache.geronimo.j2ee.deployment.Module;
import org.apache.geronimo.j2ee.deployment.ModuleBuilderExtension;
import org.apache.geronimo.j2ee.j2eeobjectnames.NameFactory;
import org.apache.geronimo.kernel.GBeanAlreadyExistsException;
import org.apache.geronimo.kernel.GBeanNotFoundException;
import org.apache.geronimo.kernel.Naming;
import org.apache.geronimo.kernel.config.ConfigurationStore;
import org.apache.geronimo.kernel.repository.Environment;
import org.apache.geronimo.persistence.PersistenceUnitGBean;
import org.apache.geronimo.xbeans.persistence.PersistenceDocument;
import org.apache.xbean.finder.ResourceFinder;
import org.apache.xmlbeans.QNameSet;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlObject;
/**
* @version $Rev$ $Date$
*/
public class PersistenceUnitBuilder implements ModuleBuilderExtension {
private static final QName PERSISTENCE_QNAME = PersistenceDocument.type.getDocumentElementName();
private final Environment defaultEnvironment;
private final String defaultPersistenceProviderClassName;
private final Properties defaultPersistenceUnitProperties;
private final AbstractNameQuery defaultJtaDataSourceName;
private final AbstractNameQuery defaultNonJtaDataSourceName;
private final AbstractNameQuery extendedEntityManagerRegistryName;
private static final String ANON_PU_NAME = "AnonymousPersistenceUnit";
public PersistenceUnitBuilder(Environment defaultEnvironment,
String defaultPersistenceProviderClassName,
String defaultJtaDataSourceName,
String defaultNonJtaDataSourceName,
AbstractNameQuery extendedEntityManagerRegistryName, Properties defaultPersistenceUnitProperties) throws URISyntaxException {
this.defaultEnvironment = defaultEnvironment;
this.defaultPersistenceProviderClassName = defaultPersistenceProviderClassName;
this.defaultJtaDataSourceName = defaultJtaDataSourceName == null ? null : getAbstractNameQuery(defaultJtaDataSourceName);
this.defaultNonJtaDataSourceName = defaultNonJtaDataSourceName == null ? null : getAbstractNameQuery(defaultNonJtaDataSourceName);
this.extendedEntityManagerRegistryName = extendedEntityManagerRegistryName;
this.defaultPersistenceUnitProperties = defaultPersistenceUnitProperties == null ? new Properties() : defaultPersistenceUnitProperties;
}
public void createModule(Module module, Object plan, JarFile moduleFile, String targetPath, URL specDDUrl, Environment environment, Object moduleContextInfo, AbstractName earName, Naming naming, ModuleIDBuilder idBuilder) throws DeploymentException {
}
public void installModule(JarFile earFile, EARContext earContext, Module module, Collection configurationStores, ConfigurationStore targetConfigurationStore, Collection repository) throws DeploymentException {
}
public void initContext(EARContext earContext, Module module, ClassLoader cl) throws DeploymentException {
XmlObject container = module.getVendorDD();
EARContext moduleContext = module.getEarContext();
XmlObject[] raws = container.selectChildren(PERSISTENCE_QNAME);
Map<String, PersistenceDocument.Persistence.PersistenceUnit> overrides = new HashMap<String, PersistenceDocument.Persistence.PersistenceUnit>();
for (XmlObject raw : raws) {
PersistenceDocument.Persistence persistence = (PersistenceDocument.Persistence) raw.copy().changeType(PersistenceDocument.Persistence.type);
for (PersistenceDocument.Persistence.PersistenceUnit unit : persistence.getPersistenceUnitArray()) {
overrides.put(unit.getName().trim(), unit);
}
// buildPersistenceUnits(persistence, module, module.getTargetPath());
}
try {
File rootBaseFile = module.getRootEarContext().getConfiguration().getConfigurationDir();
String rootBase = rootBaseFile.toURI().normalize().toString();
URI moduleBaseURI = moduleContext.getBaseDir().toURI();
Map rootGeneralData = module.getRootEarContext().getGeneralData();
ClassPathList manifestcp = (ClassPathList) module.getEarContext().getGeneralData().get(ClassPathList.class);
if (manifestcp == null) {
manifestcp = new ClassPathList();
manifestcp.add(module.getTargetPath());
}
URL[] urls = new URL[manifestcp.size()];
int i = 0;
for (String path : manifestcp) {
URL url = moduleBaseURI.resolve(path).toURL();
urls[i++] = url;
}
ResourceFinder finder = new ResourceFinder("", null, urls);
List<URL> knownPersistenceUrls = (List<URL>) rootGeneralData.get(PersistenceUnitBuilder.class.getName());
if (knownPersistenceUrls == null) {
knownPersistenceUrls = new ArrayList<URL>();
rootGeneralData.put(PersistenceUnitBuilder.class.getName(), knownPersistenceUrls);
}
List<URL> persistenceUrls = finder.findAll("META-INF/persistence.xml");
persistenceUrls.removeAll(knownPersistenceUrls);
if (raws.length > 0 || persistenceUrls.size() > 0) {
EnvironmentBuilder.mergeEnvironments(module.getEnvironment(), defaultEnvironment);
}
for (URL persistenceUrl : persistenceUrls) {
String persistenceLocation;
try {
persistenceLocation = persistenceUrl.toURI().toString();
} catch (URISyntaxException e) {
//????
continue;
}
int pos = persistenceLocation.indexOf(rootBase);
if (pos < 0) {
//not in the ear
continue;
}
int endPos = persistenceLocation.lastIndexOf("!/");
if (endPos < 0) {
// if unable to find the '!/' marker, try to see if this is
// a war file with the persistence.xml directly embeded - no ejb-jar
endPos = persistenceLocation.lastIndexOf("META-INF");
}
if (endPos >= 0) {
//path relative to ear base uri
String relative = persistenceLocation.substring(pos + rootBase.length(), endPos);
//find path relative to module base uri
relative = module.getRelativePath(relative);
PersistenceDocument persistenceDocument;
try {
XmlObject xmlObject = XmlBeansUtil.parse(persistenceUrl, moduleContext.getClassLoader());
persistenceDocument = (PersistenceDocument) xmlObject.changeType(PersistenceDocument.type);
} catch (XmlException e) {
throw new DeploymentException("Could not parse persistence.xml file: " + persistenceUrl, e);
}
PersistenceDocument.Persistence persistence = persistenceDocument.getPersistence();
buildPersistenceUnits(persistence, overrides, module, relative);
knownPersistenceUrls.add(persistenceUrl);
} else {
throw new DeploymentException("Could not find persistence.xml file: " + persistenceUrl);
}
}
} catch (IOException e) {
throw new DeploymentException("Could not look for META-INF/persistence.xml files", e);
}
for (PersistenceDocument.Persistence.PersistenceUnit persistenceUnit : overrides.values()) {
GBeanData data = installPersistenceUnitGBean(persistenceUnit, module, module.getTargetPath());
respectExcludeUnlistedClasses(data);
}
}
public void addGBeans(EARContext earContext, Module module, ClassLoader cl, Collection repository) throws DeploymentException {
try {
//make sure the PersistenceUnitGBean is started before the Module GBean
if (earContext.findGBeans(new AbstractNameQuery(earContext.getConfigID(), Collections.EMPTY_MAP, PersistenceUnitGBean.class.getName())).size() > 0) {
GBeanData moduleGBeanData = earContext.getGBeanInstance(module.getModuleName());
moduleGBeanData.addDependency(new AbstractNameQuery(earContext.getConfigID(), Collections.EMPTY_MAP, PersistenceUnitGBean.class.getName()));
}
} catch (GBeanNotFoundException e) {
//Module GBean not found, do nothing
}
}
private void buildPersistenceUnits(PersistenceDocument.Persistence persistence, Map<String, PersistenceDocument.Persistence.PersistenceUnit> overrides, Module module, String persistenceModulePath) throws DeploymentException {
PersistenceDocument.Persistence.PersistenceUnit[] persistenceUnits = persistence.getPersistenceUnitArray();
for (PersistenceDocument.Persistence.PersistenceUnit persistenceUnit : persistenceUnits) {
GBeanData data = installPersistenceUnitGBean(persistenceUnit, module, persistenceModulePath);
String unitName = persistenceUnit.getName().trim();
if (overrides.get(unitName) != null) {
setOverrideableProperties(overrides.remove(unitName), data);
}
respectExcludeUnlistedClasses(data);
}
}
private GBeanData installPersistenceUnitGBean(PersistenceDocument.Persistence.PersistenceUnit persistenceUnit, Module module, String persistenceModulePath) throws DeploymentException {
EARContext moduleContext = module.getEarContext();
String persistenceUnitName = persistenceUnit.getName().trim();
if (persistenceUnitName.length() == 0) {
persistenceUnitName = ANON_PU_NAME;
}
AbstractName abstractName;
if (persistenceModulePath == null || persistenceModulePath.length() == 0) {
abstractName = moduleContext.getNaming().createChildName(module.getModuleName(), persistenceUnitName, PersistenceUnitGBean.GBEAN_INFO.getJ2eeType());
} else {
abstractName = moduleContext.getNaming().createChildName(module.getModuleName(), persistenceModulePath, NameFactory.PERSISTENCE_UNIT_MODULE);
abstractName = moduleContext.getNaming().createChildName(abstractName, persistenceUnitName, PersistenceUnitGBean.GBEAN_INFO.getJ2eeType());
}
GBeanData gbeanData = new GBeanData(abstractName, PersistenceUnitGBean.GBEAN_INFO);
try {
moduleContext.addGBean(gbeanData);
} catch (GBeanAlreadyExistsException e) {
throw new DeploymentException("Duplicate persistenceUnit name " + persistenceUnitName, e);
}
gbeanData.setAttribute("persistenceUnitName", persistenceUnitName);
gbeanData.setAttribute("persistenceUnitRoot", persistenceModulePath);
//set defaults:
gbeanData.setAttribute("persistenceProviderClassName", defaultPersistenceProviderClassName);
//spec 6.2.1.2 the default is JTA
gbeanData.setAttribute("persistenceUnitTransactionType", "JTA");
if (defaultJtaDataSourceName != null) {
gbeanData.setReferencePattern("JtaDataSourceWrapper", defaultJtaDataSourceName);
}
if (defaultNonJtaDataSourceName != null) {
gbeanData.setReferencePattern("NonJtaDataSourceWrapper", defaultNonJtaDataSourceName);
}
gbeanData.setAttribute("mappingFileNames", new ArrayList<String>());
gbeanData.setAttribute("excludeUnlistedClasses", false);
gbeanData.setAttribute("managedClassNames", new ArrayList<String>());
gbeanData.setAttribute("jarFileUrls", new ArrayList<String>());
Properties properties = new Properties();
gbeanData.setAttribute("properties", properties);
properties.putAll(defaultPersistenceUnitProperties);
AbstractNameQuery transactionManagerName = moduleContext.getTransactionManagerName();
gbeanData.setReferencePattern("TransactionManager", transactionManagerName);
gbeanData.setReferencePattern("EntityManagerRegistry", extendedEntityManagerRegistryName);
setOverrideableProperties(persistenceUnit, gbeanData);
return gbeanData;
}
private void setOverrideableProperties(PersistenceDocument.Persistence.PersistenceUnit persistenceUnit, GBeanData gbeanData) throws DeploymentException {
if (persistenceUnit.isSetProvider()) {
gbeanData.setAttribute("persistenceProviderClassName", persistenceUnit.getProvider().trim());
}
if (persistenceUnit.isSetTransactionType()) {
gbeanData.setAttribute("persistenceUnitTransactionType", persistenceUnit.getTransactionType().toString());
}
if (persistenceUnit.isSetJtaDataSource()) {
String jtaDataSourceString = persistenceUnit.getJtaDataSource().trim();
try {
AbstractNameQuery jtaDataSourceNameQuery = getAbstractNameQuery(jtaDataSourceString);
gbeanData.setReferencePattern("JtaDataSourceWrapper", jtaDataSourceNameQuery);
} catch (URISyntaxException e) {
throw new DeploymentException("Could not create jta-data-source AbstractNameQuery from string: " + jtaDataSourceString, e);
}
}
if (persistenceUnit.isSetNonJtaDataSource()) {
String nonJtaDataSourceString = persistenceUnit.getNonJtaDataSource().trim();
try {
AbstractNameQuery nonJtaDataSourceNameQuery = getAbstractNameQuery(nonJtaDataSourceString);
gbeanData.setReferencePattern("NonJtaDataSourceWrapper", nonJtaDataSourceNameQuery);
} catch (URISyntaxException e) {
throw new DeploymentException("Could not create non-jta-data-source AbstractNameQuery from string: " + nonJtaDataSourceString, e);
}
}
List<String> mappingFileNames = (List<String>) gbeanData.getAttribute("mappingFileNames");
String[] mappingFileNameStrings = persistenceUnit.getMappingFileArray();
for (String mappingFileNameString : mappingFileNameStrings) {
mappingFileNames.add(mappingFileNameString.trim());
}
if (persistenceUnit.isSetExcludeUnlistedClasses()) {
gbeanData.setAttribute("excludeUnlistedClasses", persistenceUnit.getExcludeUnlistedClasses());
}
String[] managedClassNameStrings = persistenceUnit.getClass1Array();
List<String> managedClassNames = (List<String>) gbeanData.getAttribute("managedClassNames");
for (String managedClassNameString : managedClassNameStrings) {
managedClassNames.add(managedClassNameString.trim());
}
List<String> jarFileUrls = (List<String>) gbeanData.getAttribute("jarFileUrls");
//add the specified locations in the ear
String[] jarFileUrlStrings = persistenceUnit.getJarFileArray();
for (String jarFileUrlString : jarFileUrlStrings) {
jarFileUrls.add(jarFileUrlString.trim());
}
if (persistenceUnit.isSetProperties()) {
Properties properties = (Properties) gbeanData.getAttribute("properties");
PersistenceDocument.Persistence.PersistenceUnit.Properties.Property[] propertyObjects = persistenceUnit.getProperties().getPropertyArray();
for (PersistenceDocument.Persistence.PersistenceUnit.Properties.Property propertyObject : propertyObjects) {
String key = propertyObject.getName().trim();
String value = propertyObject.getValue().trim();
properties.setProperty(key, value);
}
}
}
private void respectExcludeUnlistedClasses(GBeanData gbeanData) {
boolean excludeUnlistedClasses = (Boolean) gbeanData.getAttribute("excludeUnlistedClasses");
if (excludeUnlistedClasses) {
gbeanData.clearAttribute("jarFileUrls");
} else {
gbeanData.clearAttribute("managedClassNames");
}
}
private AbstractNameQuery getAbstractNameQuery(String dataSourceString) throws URISyntaxException {
if (dataSourceString.indexOf('=') == -1) {
dataSourceString = "?name=" + dataSourceString;
}
AbstractNameQuery dataSourceNameQuery = new AbstractNameQuery(new URI(dataSourceString + "#org.apache.geronimo.connector.outbound.ConnectionFactorySource"));
return dataSourceNameQuery;
}
public QNameSet getSpecQNameSet() {
return QNameSet.EMPTY;
}
public QNameSet getPlanQNameSet() {
return QNameSet.singleton(PERSISTENCE_QNAME);
}
public static final GBeanInfo GBEAN_INFO;
static {
GBeanInfoBuilder infoBuilder = GBeanInfoBuilder.createStatic(PersistenceUnitBuilder.class, NameFactory.MODULE_BUILDER);
infoBuilder.addAttribute("defaultEnvironment", Environment.class, true, true);
infoBuilder.addAttribute("defaultPersistenceProviderClassName", String.class, true, true);
infoBuilder.addAttribute("defaultJtaDataSourceName", String.class, true, true);
infoBuilder.addAttribute("defaultNonJtaDataSourceName", String.class, true, true);
infoBuilder.addAttribute("extendedEntityManagerRegistryName", AbstractNameQuery.class, true, true);
infoBuilder.addAttribute("defaultPersistenceUnitProperties", Properties.class, true, true);
infoBuilder.setConstructor(new String[]{
"defaultEnvironment",
"defaultPersistenceProviderClassName",
"defaultJtaDataSourceName",
"defaultNonJtaDataSourceName",
"extendedEntityManagerRegistryName",
"defaultPersistenceUnitProperties"
});
GBEAN_INFO = infoBuilder.getBeanInfo();
}
public static GBeanInfo getGBeanInfo() {
return GBEAN_INFO;
}
}
| modules/geronimo-persistence-jpa10-builder/src/main/java/org/apache/geronimo/persistence/builder/PersistenceUnitBuilder.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.geronimo.persistence.builder;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.jar.JarFile;
import javax.xml.namespace.QName;
import org.apache.geronimo.common.DeploymentException;
import org.apache.geronimo.deployment.ClassPathList;
import org.apache.geronimo.deployment.ModuleIDBuilder;
import org.apache.geronimo.deployment.service.EnvironmentBuilder;
import org.apache.geronimo.deployment.xmlbeans.XmlBeansUtil;
import org.apache.geronimo.gbean.AbstractName;
import org.apache.geronimo.gbean.AbstractNameQuery;
import org.apache.geronimo.gbean.GBeanData;
import org.apache.geronimo.gbean.GBeanInfo;
import org.apache.geronimo.gbean.GBeanInfoBuilder;
import org.apache.geronimo.j2ee.deployment.EARContext;
import org.apache.geronimo.j2ee.deployment.Module;
import org.apache.geronimo.j2ee.deployment.ModuleBuilderExtension;
import org.apache.geronimo.j2ee.j2eeobjectnames.NameFactory;
import org.apache.geronimo.kernel.GBeanAlreadyExistsException;
import org.apache.geronimo.kernel.Naming;
import org.apache.geronimo.kernel.config.ConfigurationStore;
import org.apache.geronimo.kernel.repository.Environment;
import org.apache.geronimo.persistence.PersistenceUnitGBean;
import org.apache.geronimo.xbeans.persistence.PersistenceDocument;
import org.apache.xbean.finder.ResourceFinder;
import org.apache.xmlbeans.QNameSet;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlObject;
/**
* @version $Rev$ $Date$
*/
public class PersistenceUnitBuilder implements ModuleBuilderExtension {
private static final QName PERSISTENCE_QNAME = PersistenceDocument.type.getDocumentElementName();
private final Environment defaultEnvironment;
private final String defaultPersistenceProviderClassName;
private final Properties defaultPersistenceUnitProperties;
private final AbstractNameQuery defaultJtaDataSourceName;
private final AbstractNameQuery defaultNonJtaDataSourceName;
private final AbstractNameQuery extendedEntityManagerRegistryName;
private static final String ANON_PU_NAME = "AnonymousPersistenceUnit";
public PersistenceUnitBuilder(Environment defaultEnvironment,
String defaultPersistenceProviderClassName,
String defaultJtaDataSourceName,
String defaultNonJtaDataSourceName,
AbstractNameQuery extendedEntityManagerRegistryName, Properties defaultPersistenceUnitProperties) throws URISyntaxException {
this.defaultEnvironment = defaultEnvironment;
this.defaultPersistenceProviderClassName = defaultPersistenceProviderClassName;
this.defaultJtaDataSourceName = defaultJtaDataSourceName == null ? null : getAbstractNameQuery(defaultJtaDataSourceName);
this.defaultNonJtaDataSourceName = defaultNonJtaDataSourceName == null ? null : getAbstractNameQuery(defaultNonJtaDataSourceName);
this.extendedEntityManagerRegistryName = extendedEntityManagerRegistryName;
this.defaultPersistenceUnitProperties = defaultPersistenceUnitProperties == null ? new Properties() : defaultPersistenceUnitProperties;
}
public void createModule(Module module, Object plan, JarFile moduleFile, String targetPath, URL specDDUrl, Environment environment, Object moduleContextInfo, AbstractName earName, Naming naming, ModuleIDBuilder idBuilder) throws DeploymentException {
}
public void installModule(JarFile earFile, EARContext earContext, Module module, Collection configurationStores, ConfigurationStore targetConfigurationStore, Collection repository) throws DeploymentException {
}
public void initContext(EARContext earContext, Module module, ClassLoader cl) throws DeploymentException {
XmlObject container = module.getVendorDD();
EARContext moduleContext = module.getEarContext();
XmlObject[] raws = container.selectChildren(PERSISTENCE_QNAME);
Map<String, PersistenceDocument.Persistence.PersistenceUnit> overrides = new HashMap<String, PersistenceDocument.Persistence.PersistenceUnit>();
for (XmlObject raw : raws) {
PersistenceDocument.Persistence persistence = (PersistenceDocument.Persistence) raw.copy().changeType(PersistenceDocument.Persistence.type);
for (PersistenceDocument.Persistence.PersistenceUnit unit : persistence.getPersistenceUnitArray()) {
overrides.put(unit.getName().trim(), unit);
}
// buildPersistenceUnits(persistence, module, module.getTargetPath());
}
try {
File rootBaseFile = module.getRootEarContext().getConfiguration().getConfigurationDir();
String rootBase = rootBaseFile.toURI().normalize().toString();
URI moduleBaseURI = moduleContext.getBaseDir().toURI();
Map rootGeneralData = module.getRootEarContext().getGeneralData();
ClassPathList manifestcp = (ClassPathList) module.getEarContext().getGeneralData().get(ClassPathList.class);
if (manifestcp == null) {
manifestcp = new ClassPathList();
manifestcp.add(module.getTargetPath());
}
URL[] urls = new URL[manifestcp.size()];
int i = 0;
for (String path : manifestcp) {
URL url = moduleBaseURI.resolve(path).toURL();
urls[i++] = url;
}
ResourceFinder finder = new ResourceFinder("", null, urls);
List<URL> knownPersistenceUrls = (List<URL>) rootGeneralData.get(PersistenceUnitBuilder.class.getName());
if (knownPersistenceUrls == null) {
knownPersistenceUrls = new ArrayList<URL>();
rootGeneralData.put(PersistenceUnitBuilder.class.getName(), knownPersistenceUrls);
}
List<URL> persistenceUrls = finder.findAll("META-INF/persistence.xml");
persistenceUrls.removeAll(knownPersistenceUrls);
if (raws.length > 0 || persistenceUrls.size() > 0) {
EnvironmentBuilder.mergeEnvironments(module.getEnvironment(), defaultEnvironment);
}
for (URL persistenceUrl : persistenceUrls) {
String persistenceLocation;
try {
persistenceLocation = persistenceUrl.toURI().toString();
} catch (URISyntaxException e) {
//????
continue;
}
int pos = persistenceLocation.indexOf(rootBase);
if (pos < 0) {
//not in the ear
continue;
}
int endPos = persistenceLocation.lastIndexOf("!/");
if (endPos < 0) {
// if unable to find the '!/' marker, try to see if this is
// a war file with the persistence.xml directly embeded - no ejb-jar
endPos = persistenceLocation.lastIndexOf("META-INF");
}
if (endPos >= 0) {
//path relative to ear base uri
String relative = persistenceLocation.substring(pos + rootBase.length(), endPos);
//find path relative to module base uri
relative = module.getRelativePath(relative);
PersistenceDocument persistenceDocument;
try {
XmlObject xmlObject = XmlBeansUtil.parse(persistenceUrl, moduleContext.getClassLoader());
persistenceDocument = (PersistenceDocument) xmlObject.changeType(PersistenceDocument.type);
} catch (XmlException e) {
throw new DeploymentException("Could not parse persistence.xml file: " + persistenceUrl, e);
}
PersistenceDocument.Persistence persistence = persistenceDocument.getPersistence();
buildPersistenceUnits(persistence, overrides, module, relative);
knownPersistenceUrls.add(persistenceUrl);
} else {
throw new DeploymentException("Could not find persistence.xml file: " + persistenceUrl);
}
}
} catch (IOException e) {
throw new DeploymentException("Could not look for META-INF/persistence.xml files", e);
}
for (PersistenceDocument.Persistence.PersistenceUnit persistenceUnit : overrides.values()) {
GBeanData data = installPersistenceUnitGBean(persistenceUnit, module, module.getTargetPath());
respectExcludeUnlistedClasses(data);
}
}
public void addGBeans(EARContext earContext, Module module, ClassLoader cl, Collection repository) throws DeploymentException {
}
private void buildPersistenceUnits(PersistenceDocument.Persistence persistence, Map<String, PersistenceDocument.Persistence.PersistenceUnit> overrides, Module module, String persistenceModulePath) throws DeploymentException {
PersistenceDocument.Persistence.PersistenceUnit[] persistenceUnits = persistence.getPersistenceUnitArray();
for (PersistenceDocument.Persistence.PersistenceUnit persistenceUnit : persistenceUnits) {
GBeanData data = installPersistenceUnitGBean(persistenceUnit, module, persistenceModulePath);
String unitName = persistenceUnit.getName().trim();
if (overrides.get(unitName) != null) {
setOverrideableProperties(overrides.remove(unitName), data);
}
respectExcludeUnlistedClasses(data);
}
}
private GBeanData installPersistenceUnitGBean(PersistenceDocument.Persistence.PersistenceUnit persistenceUnit, Module module, String persistenceModulePath) throws DeploymentException {
EARContext moduleContext = module.getEarContext();
String persistenceUnitName = persistenceUnit.getName().trim();
if (persistenceUnitName.length() == 0) {
persistenceUnitName = ANON_PU_NAME;
}
AbstractName abstractName;
if (persistenceModulePath == null || persistenceModulePath.length() == 0) {
abstractName = moduleContext.getNaming().createChildName(module.getModuleName(), persistenceUnitName, PersistenceUnitGBean.GBEAN_INFO.getJ2eeType());
} else {
abstractName = moduleContext.getNaming().createChildName(module.getModuleName(), persistenceModulePath, NameFactory.PERSISTENCE_UNIT_MODULE);
abstractName = moduleContext.getNaming().createChildName(abstractName, persistenceUnitName, PersistenceUnitGBean.GBEAN_INFO.getJ2eeType());
}
GBeanData gbeanData = new GBeanData(abstractName, PersistenceUnitGBean.GBEAN_INFO);
try {
moduleContext.addGBean(gbeanData);
} catch (GBeanAlreadyExistsException e) {
throw new DeploymentException("Duplicate persistenceUnit name " + persistenceUnitName, e);
}
gbeanData.setAttribute("persistenceUnitName", persistenceUnitName);
gbeanData.setAttribute("persistenceUnitRoot", persistenceModulePath);
//set defaults:
gbeanData.setAttribute("persistenceProviderClassName", defaultPersistenceProviderClassName);
//spec 6.2.1.2 the default is JTA
gbeanData.setAttribute("persistenceUnitTransactionType", "JTA");
if (defaultJtaDataSourceName != null) {
gbeanData.setReferencePattern("JtaDataSourceWrapper", defaultJtaDataSourceName);
}
if (defaultNonJtaDataSourceName != null) {
gbeanData.setReferencePattern("NonJtaDataSourceWrapper", defaultNonJtaDataSourceName);
}
gbeanData.setAttribute("mappingFileNames", new ArrayList<String>());
gbeanData.setAttribute("excludeUnlistedClasses", false);
gbeanData.setAttribute("managedClassNames", new ArrayList<String>());
gbeanData.setAttribute("jarFileUrls", new ArrayList<String>());
Properties properties = new Properties();
gbeanData.setAttribute("properties", properties);
properties.putAll(defaultPersistenceUnitProperties);
AbstractNameQuery transactionManagerName = moduleContext.getTransactionManagerName();
gbeanData.setReferencePattern("TransactionManager", transactionManagerName);
gbeanData.setReferencePattern("EntityManagerRegistry", extendedEntityManagerRegistryName);
setOverrideableProperties(persistenceUnit, gbeanData);
return gbeanData;
}
private void setOverrideableProperties(PersistenceDocument.Persistence.PersistenceUnit persistenceUnit, GBeanData gbeanData) throws DeploymentException {
if (persistenceUnit.isSetProvider()) {
gbeanData.setAttribute("persistenceProviderClassName", persistenceUnit.getProvider().trim());
}
if (persistenceUnit.isSetTransactionType()) {
gbeanData.setAttribute("persistenceUnitTransactionType", persistenceUnit.getTransactionType().toString());
}
if (persistenceUnit.isSetJtaDataSource()) {
String jtaDataSourceString = persistenceUnit.getJtaDataSource().trim();
try {
AbstractNameQuery jtaDataSourceNameQuery = getAbstractNameQuery(jtaDataSourceString);
gbeanData.setReferencePattern("JtaDataSourceWrapper", jtaDataSourceNameQuery);
} catch (URISyntaxException e) {
throw new DeploymentException("Could not create jta-data-source AbstractNameQuery from string: " + jtaDataSourceString, e);
}
}
if (persistenceUnit.isSetNonJtaDataSource()) {
String nonJtaDataSourceString = persistenceUnit.getNonJtaDataSource().trim();
try {
AbstractNameQuery nonJtaDataSourceNameQuery = getAbstractNameQuery(nonJtaDataSourceString);
gbeanData.setReferencePattern("NonJtaDataSourceWrapper", nonJtaDataSourceNameQuery);
} catch (URISyntaxException e) {
throw new DeploymentException("Could not create non-jta-data-source AbstractNameQuery from string: " + nonJtaDataSourceString, e);
}
}
List<String> mappingFileNames = (List<String>) gbeanData.getAttribute("mappingFileNames");
String[] mappingFileNameStrings = persistenceUnit.getMappingFileArray();
for (String mappingFileNameString : mappingFileNameStrings) {
mappingFileNames.add(mappingFileNameString.trim());
}
if (persistenceUnit.isSetExcludeUnlistedClasses()) {
gbeanData.setAttribute("excludeUnlistedClasses", persistenceUnit.getExcludeUnlistedClasses());
}
String[] managedClassNameStrings = persistenceUnit.getClass1Array();
List<String> managedClassNames = (List<String>) gbeanData.getAttribute("managedClassNames");
for (String managedClassNameString : managedClassNameStrings) {
managedClassNames.add(managedClassNameString.trim());
}
List<String> jarFileUrls = (List<String>) gbeanData.getAttribute("jarFileUrls");
//add the specified locations in the ear
String[] jarFileUrlStrings = persistenceUnit.getJarFileArray();
for (String jarFileUrlString : jarFileUrlStrings) {
jarFileUrls.add(jarFileUrlString.trim());
}
if (persistenceUnit.isSetProperties()) {
Properties properties = (Properties) gbeanData.getAttribute("properties");
PersistenceDocument.Persistence.PersistenceUnit.Properties.Property[] propertyObjects = persistenceUnit.getProperties().getPropertyArray();
for (PersistenceDocument.Persistence.PersistenceUnit.Properties.Property propertyObject : propertyObjects) {
String key = propertyObject.getName().trim();
String value = propertyObject.getValue().trim();
properties.setProperty(key, value);
}
}
}
private void respectExcludeUnlistedClasses(GBeanData gbeanData) {
boolean excludeUnlistedClasses = (Boolean) gbeanData.getAttribute("excludeUnlistedClasses");
if (excludeUnlistedClasses) {
gbeanData.clearAttribute("jarFileUrls");
} else {
gbeanData.clearAttribute("managedClassNames");
}
}
private AbstractNameQuery getAbstractNameQuery(String dataSourceString) throws URISyntaxException {
if (dataSourceString.indexOf('=') == -1) {
dataSourceString = "?name=" + dataSourceString;
}
AbstractNameQuery dataSourceNameQuery = new AbstractNameQuery(new URI(dataSourceString + "#org.apache.geronimo.connector.outbound.ConnectionFactorySource"));
return dataSourceNameQuery;
}
public QNameSet getSpecQNameSet() {
return QNameSet.EMPTY;
}
public QNameSet getPlanQNameSet() {
return QNameSet.singleton(PERSISTENCE_QNAME);
}
public static final GBeanInfo GBEAN_INFO;
static {
GBeanInfoBuilder infoBuilder = GBeanInfoBuilder.createStatic(PersistenceUnitBuilder.class, NameFactory.MODULE_BUILDER);
infoBuilder.addAttribute("defaultEnvironment", Environment.class, true, true);
infoBuilder.addAttribute("defaultPersistenceProviderClassName", String.class, true, true);
infoBuilder.addAttribute("defaultJtaDataSourceName", String.class, true, true);
infoBuilder.addAttribute("defaultNonJtaDataSourceName", String.class, true, true);
infoBuilder.addAttribute("extendedEntityManagerRegistryName", AbstractNameQuery.class, true, true);
infoBuilder.addAttribute("defaultPersistenceUnitProperties", Properties.class, true, true);
infoBuilder.setConstructor(new String[]{
"defaultEnvironment",
"defaultPersistenceProviderClassName",
"defaultJtaDataSourceName",
"defaultNonJtaDataSourceName",
"extendedEntityManagerRegistryName",
"defaultPersistenceUnitProperties"
});
GBEAN_INFO = infoBuilder.getBeanInfo();
}
public static GBeanInfo getGBeanInfo() {
return GBEAN_INFO;
}
}
| GERONIMO-3317 Sets PersistenceUnitGBean as the dependence of Module GBean to make sure the ClassTransformer is installed before EjbModuleImplGBean. Song, thanks for the patch.
git-svn-id: 0d16bf2c240b8111500ec482b35765e5042f5526@557004 13f79535-47bb-0310-9956-ffa450edef68
| modules/geronimo-persistence-jpa10-builder/src/main/java/org/apache/geronimo/persistence/builder/PersistenceUnitBuilder.java | GERONIMO-3317 Sets PersistenceUnitGBean as the dependence of Module GBean to make sure the ClassTransformer is installed before EjbModuleImplGBean. Song, thanks for the patch. |
|
Java | apache-2.0 | a17125ae3179752670f2f5bc96ea337b76837236 | 0 | naver/ngrinder,naver/ngrinder,naver/ngrinder,naver/ngrinder,naver/ngrinder | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ngrinder.common.service;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.ngrinder.infra.spring.SpringContext;
import org.ngrinder.model.BaseModel;
import org.ngrinder.model.User;
import org.ngrinder.user.repository.UserRepository;
import org.ngrinder.user.service.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import static org.ngrinder.user.repository.UserSpecification.idEqual;
/**
* Aspect to inject the created/modified user and date to the model.
*
* @author Liu Zhifei
* @author JunHo Yoon
* @since 3.0
*/
@Aspect
@Service
public class ModelAspect {
public static final String EXECUTION_SAVE = "execution(* org.ngrinder.**.*Service.save*(..))";
@Autowired
private UserContext userContext;
@Autowired
private SpringContext springContext;
@Autowired
private UserRepository userRepository;
/**
* Inject the created/modified user and date to the model. It's only applied
* in the servlet context.
*
* @param joinPoint joint point
*/
@Before(EXECUTION_SAVE)
public void beforeSave(JoinPoint joinPoint) {
for (Object object : joinPoint.getArgs()) {
// If the object is base model and it's on the servlet
// context, It's not executed by task scheduling.
SpringContext springContext = getSpringContext();
if (object instanceof BaseModel
&& (springContext.isServletRequestContext() || springContext.isUnitTestContext())) {
BaseModel<?> model = (BaseModel<?>) object;
Date lastModifiedDate = new Date();
model.setLastModifiedDate(lastModifiedDate);
User currentUser = userContext.getCurrentUser();
long currentUserId = currentUser.getId();
model.setLastModifiedUser(userRepository.findOne(idEqual(currentUserId))
.orElseThrow(() -> new IllegalArgumentException("No user found with id : " + currentUserId)));
if (!model.exist() || model.getCreatedUser() == null) {
long factualUserId = currentUser.getFactualUser().getId();
model.setCreatedDate(lastModifiedDate);
model.setCreatedUser(userRepository.findOne(idEqual(factualUserId))
.orElseThrow(() -> new IllegalArgumentException("No user found with id : " + factualUserId)));
}
}
}
}
public SpringContext getSpringContext() {
return springContext;
}
public void setSpringContext(SpringContext springContext) {
this.springContext = springContext;
}
}
| ngrinder-controller/src/main/java/org/ngrinder/common/service/ModelAspect.java | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.ngrinder.common.service;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.ngrinder.infra.spring.SpringContext;
import org.ngrinder.model.BaseModel;
import org.ngrinder.model.User;
import org.ngrinder.user.repository.UserRepository;
import org.ngrinder.user.service.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import static org.ngrinder.user.repository.UserSpecification.idEqual;
/**
* Aspect to inject the created/modified user and date to the model.
*
* @author Liu Zhifei
* @author JunHo Yoon
* @since 3.0
*/
@Aspect
@Service
public class ModelAspect {
public static final String EXECUTION_SAVE = "execution(* org.ngrinder.**.*Service.save*(..))";
@Autowired
private UserContext userContext;
@Autowired
private SpringContext springContext;
@Autowired
private UserRepository userRepository;
/**
* Inject the created/modified user and date to the model. It's only applied
* in the servlet context.
*
* @param joinPoint joint point
*/
@Before(EXECUTION_SAVE)
public void beforeSave(JoinPoint joinPoint) {
for (Object object : joinPoint.getArgs()) {
// If the object is base model and it's on the servlet
// context, It's not executed by task scheduling.
SpringContext springContext = getSpringContext();
if (object instanceof BaseModel
&& (springContext.isServletRequestContext() || springContext.isUnitTestContext())) {
BaseModel<?> model = (BaseModel<?>) object;
Date lastModifiedDate = new Date();
model.setLastModifiedDate(lastModifiedDate);
User currentUser = userContext.getCurrentUser();
Long currentUserId = currentUser.getId();
model.setLastModifiedUser(userRepository.findOne(idEqual(currentUserId))
.orElseThrow(() -> new IllegalArgumentException("No user found with id : " + currentUserId)));
if (!model.exist() || model.getCreatedUser() == null) {
model.setCreatedDate(lastModifiedDate);
model.setCreatedUser(userRepository.findOne(idEqual(currentUserId))
.orElseThrow(() -> new IllegalArgumentException("No user found with id : " + currentUserId)));
}
}
}
}
public SpringContext getSpringContext() {
return springContext;
}
public void setSpringContext(SpringContext springContext) {
this.springContext = springContext;
}
}
| Set factual user as created user before saving perftest
| ngrinder-controller/src/main/java/org/ngrinder/common/service/ModelAspect.java | Set factual user as created user before saving perftest |
|
Java | apache-2.0 | 92cbcc71f7b4a8918bb781c477fb631738ed769f | 0 | MER-GROUP/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,fitermay/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,samthor/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,petteyg/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,retomerz/intellij-community,semonte/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,semonte/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,caot/intellij-community,clumsy/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,apixandru/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,tmpgit/intellij-community,allotria/intellij-community,fitermay/intellij-community,asedunov/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,caot/intellij-community,supersven/intellij-community,blademainer/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,ftomassetti/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,ibinti/intellij-community,Lekanich/intellij-community,semonte/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,semonte/intellij-community,fnouama/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,fengbaicanhe/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,vladmm/intellij-community,clumsy/intellij-community,caot/intellij-community,caot/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,akosyakov/intellij-community,kool79/intellij-community,ibinti/intellij-community,fitermay/intellij-community,robovm/robovm-studio,jagguli/intellij-community,apixandru/intellij-community,caot/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,supersven/intellij-community,holmes/intellij-community,semonte/intellij-community,semonte/intellij-community,amith01994/intellij-community,da1z/intellij-community,ryano144/intellij-community,hurricup/intellij-community,da1z/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,signed/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,amith01994/intellij-community,slisson/intellij-community,akosyakov/intellij-community,signed/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,kdwink/intellij-community,apixandru/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,da1z/intellij-community,fnouama/intellij-community,amith01994/intellij-community,holmes/intellij-community,clumsy/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,samthor/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,semonte/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,ibinti/intellij-community,caot/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,Lekanich/intellij-community,supersven/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,robovm/robovm-studio,kool79/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,kool79/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,kool79/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,samthor/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,caot/intellij-community,samthor/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,hurricup/intellij-community,adedayo/intellij-community,jagguli/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,FHannes/intellij-community,samthor/intellij-community,hurricup/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,kool79/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,dslomov/intellij-community,supersven/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,nicolargo/intellij-community,samthor/intellij-community,ibinti/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,youdonghai/intellij-community,supersven/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,adedayo/intellij-community,dslomov/intellij-community,FHannes/intellij-community,petteyg/intellij-community,allotria/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,holmes/intellij-community,dslomov/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,allotria/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,jagguli/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,amith01994/intellij-community,retomerz/intellij-community,asedunov/intellij-community,jagguli/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,da1z/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,asedunov/intellij-community,petteyg/intellij-community,holmes/intellij-community,fitermay/intellij-community,nicolargo/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,ahb0327/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,jagguli/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,ryano144/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,kdwink/intellij-community,supersven/intellij-community,vladmm/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,FHannes/intellij-community,MichaelNedzelsky/intellij-community,alphafoobar/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,izonder/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,asedunov/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,samthor/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,signed/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,retomerz/intellij-community,da1z/intellij-community,suncycheng/intellij-community,kool79/intellij-community,suncycheng/intellij-community,samthor/intellij-community,slisson/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,jagguli/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,hurricup/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,ryano144/intellij-community,samthor/intellij-community,blademainer/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,amith01994/intellij-community,FHannes/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,izonder/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,robovm/robovm-studio,supersven/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,jagguli/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,holmes/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,amith01994/intellij-community,samthor/intellij-community,clumsy/intellij-community,FHannes/intellij-community,signed/intellij-community,kdwink/intellij-community,dslomov/intellij-community,retomerz/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,kdwink/intellij-community,vladmm/intellij-community,semonte/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,ryano144/intellij-community,da1z/intellij-community,vvv1559/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,vladmm/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,kool79/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,FHannes/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,holmes/intellij-community,caot/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,fnouama/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,vvv1559/intellij-community,caot/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,Distrotech/intellij-community,signed/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,dslomov/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,blademainer/intellij-community,blademainer/intellij-community,ibinti/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,jagguli/intellij-community,kool79/intellij-community,caot/intellij-community,nicolargo/intellij-community,Distrotech/intellij-community,hurricup/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,signed/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,lucafavatella/intellij-community,dslomov/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,fengbaicanhe/intellij-community,asedunov/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,Lekanich/intellij-community,TangHao1987/intellij-community,signed/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,samthor/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,diorcety/intellij-community,caot/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,da1z/intellij-community,Distrotech/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,ibinti/intellij-community,ryano144/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,asedunov/intellij-community,vladmm/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community | package com.intellij.refactoring;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiField;
import com.intellij.psi.PsiType;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.refactoring.typeMigration.TypeMigrationProcessor;
import com.intellij.refactoring.typeMigration.TypeMigrationRules;
import com.intellij.usageView.UsageInfo;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
/**
* @author anna
* Date: 30-Apr-2008
*/
public abstract class TypeMigrationTestBase extends MultiFileTestCase {
@Override
protected String getTestDataPath() {
return PathManager.getHomePath() + "/plugins/typeMigration/testData";
}
protected void doTestFieldType(@NonNls String fieldName, PsiType fromType, PsiType toType) throws Exception {
doTestFieldType(fieldName, "Test", fromType, toType);
}
protected void doTestFieldType(@NonNls final String fieldName, String className, final PsiType rootType, final PsiType migrationType) throws Exception {
final RulesProvider provider = new RulesProvider() {
@Override
public TypeMigrationRules provide() throws Exception {
final TypeMigrationRules rules = new TypeMigrationRules(rootType);
rules.setBoundScope(GlobalSearchScope.projectScope(getProject()));
rules.setMigrationRootType(migrationType);
return rules;
}
@Override
public PsiElement victims(PsiClass aClass) {
final PsiField field = aClass.findFieldByName(fieldName, false);
assert field != null : fieldName + " not found in " + aClass;
return field;
}
};
start(provider, className);
}
protected void doTestMethodType(@NonNls final String methodName, final PsiType rootType, final PsiType migrationType) throws Exception {
doTestMethodType(methodName, "Test", rootType, migrationType);
}
protected void doTestMethodType(@NonNls final String methodName, @NonNls String className, final PsiType rootType, final PsiType migrationType) throws Exception {
final RulesProvider provider = new RulesProvider() {
@Override
public TypeMigrationRules provide() throws Exception {
final TypeMigrationRules rules = new TypeMigrationRules(rootType);
rules.setBoundScope(GlobalSearchScope.projectScope(getProject()));
rules.setMigrationRootType(migrationType);
return rules;
}
@Override
public PsiElement victims(PsiClass aClass) {
return aClass.findMethodsByName(methodName, false)[0];
}
};
start(provider, className);
}
protected void doTestFirstParamType(@NonNls final String methodName, final PsiType rootType, final PsiType migrationType) throws Exception {
doTestFirstParamType(methodName, "Test", rootType, migrationType);
}
protected void doTestFirstParamType(@NonNls final String methodName, String className, final PsiType rootType, final PsiType migrationType) throws Exception {
final RulesProvider provider = new RulesProvider() {
@Override
public TypeMigrationRules provide() throws Exception {
final TypeMigrationRules rules = new TypeMigrationRules(rootType);
rules.setBoundScope(GlobalSearchScope.projectScope(getProject()));
rules.setMigrationRootType(migrationType);
return rules;
}
@Override
public PsiElement victims(PsiClass aClass) {
return aClass.findMethodsByName(methodName, false)[0].getParameterList().getParameters()[0];
}
};
start(provider, className);
}
public void start(final RulesProvider provider) throws Exception {
start(provider, "Test");
}
public void start(final RulesProvider provider, final String className) throws Exception {
doTest(new PerformAction() {
@Override
public void performAction(VirtualFile rootDir, VirtualFile rootAfter) throws Exception {
TypeMigrationTestBase.this.performAction(className, rootDir.getName(), provider);
}
});
}
private void performAction(String className, String rootDir, RulesProvider provider) throws Exception {
PsiClass aClass = myJavaFacade.findClass(className, GlobalSearchScope.allScope(getProject()));
assertNotNull("Class " + className + " not found", aClass);
final TestTypeMigrationProcessor pr = new TestTypeMigrationProcessor(getProject(), provider.victims(aClass), provider.provide());
final UsageInfo[] usages = pr.findUsages();
final String report = pr.getLabeler().getMigrationReport();
WriteCommandAction.runWriteCommandAction(new Runnable() {
public void run() {
pr.performRefactoring(usages);
}
});
String itemName = className + ".items";
String patternName = getTestDataPath() + getTestRoot() + getTestName(true) + "/after/" + itemName;
File patternFile = new File(patternName);
if (!patternFile.exists()) {
PrintWriter writer = new PrintWriter(new FileOutputStream(patternFile));
try {
writer.print(report);
writer.close();
}
finally {
writer.close();
}
System.out.println("Pattern not found, file " + patternName + " created.");
LocalFileSystem.getInstance().refreshAndFindFileByIoFile(patternFile);
}
File graFile = new File(FileUtil.getTempDirectory() + File.separator + rootDir + File.separator + itemName);
PrintWriter writer = new PrintWriter(new FileOutputStream(graFile));
try {
writer.print(report);
writer.close();
}
finally {
writer.close();
}
LocalFileSystem.getInstance().refreshAndFindFileByIoFile(graFile);
FileDocumentManager.getInstance().saveAllDocuments();
}
interface RulesProvider {
TypeMigrationRules provide() throws Exception;
PsiElement victims(PsiClass aClass);
}
private static class TestTypeMigrationProcessor extends TypeMigrationProcessor {
public TestTypeMigrationProcessor(final Project project, final PsiElement root, final TypeMigrationRules rules) {
super(project, root, rules);
}
@NotNull
@Override
public UsageInfo[] findUsages() {
return super.findUsages();
}
@Override
public void performRefactoring(final UsageInfo[] usages) {
super.performRefactoring(usages);
}
}
} | plugins/typeMigration/test/com/intellij/refactoring/TypeMigrationTestBase.java | package com.intellij.refactoring;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiField;
import com.intellij.psi.PsiType;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.refactoring.typeMigration.TypeMigrationProcessor;
import com.intellij.refactoring.typeMigration.TypeMigrationRules;
import com.intellij.usageView.UsageInfo;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
/**
* @author anna
* Date: 30-Apr-2008
*/
public abstract class TypeMigrationTestBase extends MultiFileTestCase {
@Override
protected String getTestDataPath() {
return PathManager.getHomePath() + "/plugins/typeMigration/testData";
}
protected void doTestFieldType(@NonNls String fieldName, PsiType fromType, PsiType toType) throws Exception {
doTestFieldType(fieldName, "Test", fromType, toType);
}
protected void doTestFieldType(@NonNls final String fieldName, String className, final PsiType rootType, final PsiType migrationType) throws Exception {
final RulesProvider provider = new RulesProvider() {
@Override
public TypeMigrationRules provide() throws Exception {
final TypeMigrationRules rules = new TypeMigrationRules(rootType);
rules.setBoundScope(GlobalSearchScope.projectScope(getProject()));
rules.setMigrationRootType(migrationType);
return rules;
}
@Override
public PsiElement victims(PsiClass aClass) {
final PsiField field = aClass.findFieldByName(fieldName, false);
assert field != null : fieldName + " not found in " + aClass;
return field;
}
};
start(provider, className);
}
protected void doTestMethodType(@NonNls final String methodName, final PsiType rootType, final PsiType migrationType) throws Exception {
doTestMethodType(methodName, "Test", rootType, migrationType);
}
protected void doTestMethodType(@NonNls final String methodName, @NonNls String className, final PsiType rootType, final PsiType migrationType) throws Exception {
final RulesProvider provider = new RulesProvider() {
@Override
public TypeMigrationRules provide() throws Exception {
final TypeMigrationRules rules = new TypeMigrationRules(rootType);
rules.setBoundScope(GlobalSearchScope.projectScope(getProject()));
rules.setMigrationRootType(migrationType);
return rules;
}
@Override
public PsiElement victims(PsiClass aClass) {
return aClass.findMethodsByName(methodName, false)[0];
}
};
start(provider, className);
}
protected void doTestFirstParamType(@NonNls final String methodName, final PsiType rootType, final PsiType migrationType) throws Exception {
doTestFirstParamType(methodName, "Test", rootType, migrationType);
}
protected void doTestFirstParamType(@NonNls final String methodName, String className, final PsiType rootType, final PsiType migrationType) throws Exception {
final RulesProvider provider = new RulesProvider() {
@Override
public TypeMigrationRules provide() throws Exception {
final TypeMigrationRules rules = new TypeMigrationRules(rootType);
rules.setBoundScope(GlobalSearchScope.projectScope(getProject()));
rules.setMigrationRootType(migrationType);
return rules;
}
@Override
public PsiElement victims(PsiClass aClass) {
return aClass.findMethodsByName(methodName, false)[0].getParameterList().getParameters()[0];
}
};
start(provider, className);
}
public void start(final RulesProvider provider) throws Exception {
start(provider, "Test");
}
public void start(final RulesProvider provider, final String className) throws Exception {
doTest(new PerformAction() {
@Override
public void performAction(VirtualFile rootDir, VirtualFile rootAfter) throws Exception {
TypeMigrationTestBase.this.performAction(className, rootDir.getName(), provider);
}
});
}
private void performAction(String className, String rootDir, RulesProvider provider) throws Exception {
PsiClass aClass = myJavaFacade.findClass(className, GlobalSearchScope.allScope(getProject()));
assertNotNull("Class " + className + " not found", aClass);
final TestTypeMigrationProcessor pr = new TestTypeMigrationProcessor(getProject(), provider.victims(aClass), provider.provide());
final UsageInfo[] usages = pr.findUsages();
final String report = pr.getLabeler().getMigrationReport();
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
pr.performRefactoring(usages);
}
});
String itemName = className + ".items";
String patternName = getTestDataPath() + getTestRoot() + getTestName(true) + "/after/" + itemName;
File patternFile = new File(patternName);
if (!patternFile.exists()) {
PrintWriter writer = new PrintWriter(new FileOutputStream(patternFile));
try {
writer.print(report);
writer.close();
}
finally {
writer.close();
}
System.out.println("Pattern not found, file " + patternName + " created.");
LocalFileSystem.getInstance().refreshAndFindFileByIoFile(patternFile);
}
File graFile = new File(FileUtil.getTempDirectory() + File.separator + rootDir + File.separator + itemName);
PrintWriter writer = new PrintWriter(new FileOutputStream(graFile));
try {
writer.print(report);
writer.close();
}
finally {
writer.close();
}
LocalFileSystem.getInstance().refreshAndFindFileByIoFile(graFile);
FileDocumentManager.getInstance().saveAllDocuments();
}
interface RulesProvider {
TypeMigrationRules provide() throws Exception;
PsiElement victims(PsiClass aClass);
}
private static class TestTypeMigrationProcessor extends TypeMigrationProcessor {
public TestTypeMigrationProcessor(final Project project, final PsiElement root, final TypeMigrationRules rules) {
super(project, root, rules);
}
@NotNull
@Override
public UsageInfo[] findUsages() {
return super.findUsages();
}
@Override
public void performRefactoring(final UsageInfo[] usages) {
super.performRefactoring(usages);
}
}
} | a couple of tests fixed to avoid assertion of document modification outside command
| plugins/typeMigration/test/com/intellij/refactoring/TypeMigrationTestBase.java | a couple of tests fixed to avoid assertion of document modification outside command |
|
Java | apache-2.0 | d1eb0b01e1a3db8437e390bf92e7f15fd22ebb2a | 0 | KuaiFaMaster/Apktool,Klozz/Apktool,jasonzhong/Apktool,pandazheng/Apktool,zhanwei/android-apktool,akhirasip/Apktool,Klozz/Apktool,zdzhjx/android-apktool,draekko/Apktool,Yaeger/Apktool,kesuki/Apktool,blaquee/Apktool,dankoman30/Apktool,kuter007/android-apktool,androidmchen/Apktool,yunemr/Apktool,kesuki/Apktool,zdzhjx/android-apktool,PiR43/Apktool,guiyu/android-apktool,pwelyn/Apktool,blaquee/Apktool,fabiand93/Apktool,phhusson/Apktool,zhanwei/android-apktool,harish123400/Apktool,desword/android-apktool,youleyu/android-apktool,sawrus/Apktool,Yaeger/Apktool,lczgywzyy/Apktool,berkus/android-apktool,pwelyn/Apktool,iBotPeaches/Apktool,fromsatellite/Apktool,ccgreen13/Apktool,asolfre/android-apktool,Benjamin-Dobell/Apktool,lovely3x/Apktool,guiyu/android-apktool,nitinverma/Apktool,alipov/Apktool,chenrui2014/Apktool,youleyu/android-apktool,kaneawk/Apktool,fabiand93/Apktool,hongnguyenpro/Apktool,PiR43/Apktool,androidmchen/Apktool,jasonzhong/Apktool,asolfre/android-apktool,370829592/android-apktool,fromsatellite/Apktool,tmpgit/Apktool,jianglibo/Apktool,lnln1111/android-apktool,dankoman30/Apktool,valery-barysok/Apktool,draekko/Apktool,HackerTool/Apktool,virustotalop/Apktool,lovely3x/Apktool,Benjamin-Dobell/Apktool,jianglibo/Apktool,digshock/android-apktool,zhic5352/Apktool,desword/android-apktool,tmpgit/Apktool,bingshi/android-apktool,harish123400/Apktool,iBotPeaches/Apktool,rover12421/Apktool,hongnguyenpro/Apktool,zhakui/Apktool,sawrus/Apktool,CheungSKei/Apktool,CheungSKei/Apktool,zhakui/Apktool,akhirasip/Apktool,lczgywzyy/Apktool,simtel12/Apktool,valery-barysok/Apktool,berkus/android-apktool,alipov/Apktool,phhusson/Apktool,pandazheng/Apktool,zhic5352/Apktool,rover12421/Apktool,yunemr/Apktool,kaneawk/Apktool,admin-zhx/Apktool,lnln1111/android-apktool,virustotalop/Apktool,chenrui2014/Apktool,nitinverma/Apktool,ccgreen13/Apktool,simtel12/Apktool,370829592/android-apktool,kuter007/android-apktool,bingshi/android-apktool,yujokang/Apktool,KuaiFaMaster/Apktool,HackerTool/Apktool,admin-zhx/Apktool,digshock/android-apktool,yujokang/Apktool | /**
* Copyright 2011 Ryszard Wiśniewski <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package brut.androlib;
import brut.androlib.res.util.ExtFile;
import brut.common.BrutException;
import brut.util.OS;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.File;
import java.util.logging.Logger;
import static org.junit.Assert.assertTrue;
/**
* @author Connor Tumbleson <[email protected]>
*/
public class BuildAndDecodeJarTest {
@BeforeClass
public static void beforeClass() throws Exception, BrutException {
sTmpDir = new ExtFile(OS.createTempDirectory());
sTestOrigDir = new ExtFile(sTmpDir, "testjar-orig");
sTestNewDir = new ExtFile(sTmpDir, "testjar-new");
LOGGER.info("Unpacking testjar...");
TestUtils.copyResourceDir(BuildAndDecodeJarTest.class, "brut/apktool/testjar/", sTestOrigDir);
LOGGER.info("Building testjar.apk...");
File testJar = new File(sTmpDir, "testjar.jar");
new Androlib().build(sTestOrigDir, testJar, TestUtils.returnStockHashMap(),"");
LOGGER.info("Decoding testjar.jar...");
ApkDecoder apkDecoder = new ApkDecoder(testJar);
apkDecoder.setOutDir(sTestNewDir);
apkDecoder.decode();
}
@AfterClass
public static void afterClass() throws BrutException {
OS.rmdir(sTmpDir);
}
@Test
public void buildAndDecodeTest() throws BrutException {
assertTrue(sTestNewDir.isDirectory());
}
private static ExtFile sTmpDir;
private static ExtFile sTestOrigDir;
private static ExtFile sTestNewDir;
private final static Logger LOGGER = Logger.getLogger(BuildAndDecodeJarTest.class.getName());
}
| brut.apktool/apktool-lib/src/test/java/brut/androlib/BuildAndDecodeJarTest.java | /**
* Copyright 2011 Ryszard Wiśniewski <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package brut.androlib;
import brut.androlib.res.util.ExtFile;
import brut.common.BrutException;
import brut.util.OS;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.File;
import java.util.logging.Logger;
import static org.junit.Assert.assertTrue;
/**
* @author Connor Tumbleson <[email protected]>
*/
public class BuildAndDecodeJarTest {
@BeforeClass
public static void beforeClass() throws Exception, BrutException {
sTmpDir = new ExtFile(OS.createTempDirectory());
sTestOrigDir = new ExtFile(sTmpDir, "testjar-orig");
sTestNewDir = new ExtFile(sTmpDir, "testjar-new");
LOGGER.info("Unpacking testjar...");
TestUtils.copyResourceDir(BuildAndDecodeJarTest.class, "brut/apktool/testjar/", sTestOrigDir);
LOGGER.info("Building testjar.apk...");
File testJar = new File(sTmpDir, "testjar.jar");
new Androlib().build(sTestOrigDir, testJar, TestUtils.returnStockHashMap(),"");
LOGGER.info("Decoding testjar.jar...");
ApkDecoder apkDecoder = new ApkDecoder(testJar);
apkDecoder.setOutDir(sTestNewDir);
apkDecoder.decode();
}
@AfterClass
public static void afterClass() throws BrutException {
OS.rmdir(sTmpDir);
}
@Test
public void buildAndDecodeTest() throws BrutException {
assertTrue(sTestNewDir.isDirectory());
}
private static ExtFile sTmpDir;
private static ExtFile sTestOrigDir;
private static ExtFile sTestNewDir;
private final static Logger LOGGER = Logger.getLogger(BuildAndDecodeTest.class.getName());
}
| [skip] fixed bad logger name
| brut.apktool/apktool-lib/src/test/java/brut/androlib/BuildAndDecodeJarTest.java | [skip] fixed bad logger name |
|
Java | apache-2.0 | b38110592684acd3765858a74bd0b4ecd1ec60c5 | 0 | galderz/Aeron,oleksiyp/Aeron,UIKit0/Aeron,RussellWilby/Aeron,EvilMcJerkface/Aeron,strangelydim/Aeron,gkamal/Aeron,jerrinot/Aeron,oleksiyp/Aeron,galderz/Aeron,gkamal/Aeron,real-logic/Aeron,rlankenau/Aeron,galderz/Aeron,real-logic/Aeron,lennartj/Aeron,mikeb01/Aeron,buybackoff/Aeron,lennartj/Aeron,galderz/Aeron,oleksiyp/Aeron,mikeb01/Aeron,EvilMcJerkface/Aeron,buybackoff/Aeron,strangelydim/Aeron,mikeb01/Aeron,jerrinot/Aeron,strangelydim/Aeron,buybackoff/Aeron,tbrooks8/Aeron,UIKit0/Aeron,EvilMcJerkface/Aeron,EvilMcJerkface/Aeron,gkamal/Aeron,real-logic/Aeron,mikeb01/Aeron,rlankenau/Aeron,jerrinot/Aeron,tbrooks8/Aeron,UIKit0/Aeron,lennartj/Aeron,real-logic/Aeron,tbrooks8/Aeron,rlankenau/Aeron,RussellWilby/Aeron,RussellWilby/Aeron | /*
* Copyright 2014 - 2015 Real Logic Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.real_logic.aeron.driver;
import uk.co.real_logic.aeron.common.Flyweight;
import uk.co.real_logic.aeron.common.command.CorrelatedMessageFlyweight;
import uk.co.real_logic.aeron.common.command.PublicationMessageFlyweight;
import uk.co.real_logic.aeron.common.command.RemoveMessageFlyweight;
import uk.co.real_logic.aeron.common.command.SubscriptionMessageFlyweight;
import uk.co.real_logic.aeron.common.concurrent.logbuffer.LogBufferDescriptor;
import uk.co.real_logic.aeron.common.event.EventCode;
import uk.co.real_logic.aeron.common.event.EventLogger;
import uk.co.real_logic.aeron.common.protocol.DataHeaderFlyweight;
import uk.co.real_logic.aeron.driver.buffer.RawLog;
import uk.co.real_logic.aeron.driver.buffer.RawLogFactory;
import uk.co.real_logic.aeron.driver.cmd.DriverConductorCmd;
import uk.co.real_logic.aeron.driver.exceptions.ControlProtocolException;
import uk.co.real_logic.agrona.BitUtil;
import uk.co.real_logic.agrona.MutableDirectBuffer;
import uk.co.real_logic.agrona.TimerWheel;
import uk.co.real_logic.agrona.collections.Long2ObjectHashMap;
import uk.co.real_logic.agrona.concurrent.*;
import uk.co.real_logic.agrona.concurrent.ringbuffer.RingBuffer;
import uk.co.real_logic.agrona.concurrent.status.Position;
import uk.co.real_logic.agrona.concurrent.status.UnsafeBufferPosition;
import java.net.InetSocketAddress;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Supplier;
import static java.util.stream.Collectors.toList;
import static uk.co.real_logic.aeron.common.ErrorCode.*;
import static uk.co.real_logic.aeron.common.command.ControlProtocolEvents.*;
import static uk.co.real_logic.aeron.common.event.EventConfiguration.EVENT_READER_FRAME_LIMIT;
import static uk.co.real_logic.aeron.driver.Configuration.*;
import static uk.co.real_logic.aeron.driver.MediaDriver.Context;
/**
* Driver Conductor to take commands from publishers and subscribers as well as handle NAKs and retransmissions
*/
public class DriverConductor implements Agent
{
private final long dataLossSeed;
private final long controlLossSeed;
private final double dataLossRate;
private final double controlLossRate;
private final int mtuLength;
private final int termBufferLength;
private final int initialWindowLength;
private final RawLogFactory rawLogFactory;
private final ReceiverProxy receiverProxy;
private final SenderProxy senderProxy;
private final ClientProxy clientProxy;
private final DriverConductorProxy conductorProxy;
private final RingBuffer toDriverCommands;
private final RingBuffer toEventReader;
private final OneToOneConcurrentArrayQueue<DriverConductorCmd> driverConductorCmdQueue;
private final Supplier<FlowControl> unicastFlowControl;
private final Supplier<FlowControl> multicastFlowControl;
private final HashMap<String, SendChannelEndpoint> sendChannelEndpointByChannelMap = new HashMap<>();
private final HashMap<String, ReceiveChannelEndpoint> receiveChannelEndpointByChannelMap = new HashMap<>();
private final Long2ObjectHashMap<PublicationRegistration> publicationRegistrations = new Long2ObjectHashMap<>();
private final ArrayList<NetworkPublication> publications = new ArrayList<>();
private final ArrayList<DriverSubscription> subscriptions = new ArrayList<>();
private final ArrayList<NetworkConnection> connections = new ArrayList<>();
private final ArrayList<AeronClient> clients = new ArrayList<>();
private final PublicationMessageFlyweight publicationMsgFlyweight = new PublicationMessageFlyweight();
private final SubscriptionMessageFlyweight subscriptionMsgFlyweight = new SubscriptionMessageFlyweight();
private final CorrelatedMessageFlyweight correlatedMsgFlyweight = new CorrelatedMessageFlyweight();
private final RemoveMessageFlyweight removeMsgFlyweight = new RemoveMessageFlyweight();
private final NanoClock clock;
private final TimerWheel timerWheel;
private final TimerWheel.Timer checkTimeoutTimer;
private final SystemCounters systemCounters;
private final UnsafeBuffer countersBuffer;
private final CountersManager countersManager;
private final EventLogger logger;
private final Consumer<DriverConductorCmd> onDriverConductorCmdFunc = this::onDriverConductorCmd;
private final MessageHandler onClientCommandFunc = this::onClientCommand;
private final MessageHandler onEventFunc;
public DriverConductor(final Context ctx)
{
driverConductorCmdQueue = ctx.conductorCommandQueue();
receiverProxy = ctx.receiverProxy();
senderProxy = ctx.senderProxy();
rawLogFactory = ctx.rawLogBuffersFactory();
mtuLength = ctx.mtuLength();
initialWindowLength = ctx.initialWindowLength();
termBufferLength = ctx.termBufferLength();
unicastFlowControl = ctx.unicastSenderFlowControl();
multicastFlowControl = ctx.multicastSenderFlowControl();
countersManager = ctx.countersManager();
countersBuffer = ctx.countersBuffer();
timerWheel = ctx.conductorTimerWheel();
clock = timerWheel.clock();
toDriverCommands = ctx.toDriverCommands();
toEventReader = ctx.toEventReader();
clientProxy = ctx.clientProxy();
conductorProxy = ctx.driverConductorProxy();
logger = ctx.eventLogger();
dataLossRate = ctx.dataLossRate();
dataLossSeed = ctx.dataLossSeed();
controlLossRate = ctx.controlLossRate();
controlLossSeed = ctx.controlLossSeed();
systemCounters = ctx.systemCounters();
checkTimeoutTimer = timerWheel.newTimeout(HEARTBEAT_TIMEOUT_MS, TimeUnit.MILLISECONDS, this::onHeartbeatCheckTimeouts);
final Consumer<String> eventConsumer = ctx.eventConsumer();
onEventFunc =
(typeId, buffer, offset, length) -> eventConsumer.accept(EventCode.get(typeId).decode(buffer, offset, length));
final AtomicBuffer buffer = toDriverCommands.buffer();
publicationMsgFlyweight.wrap(buffer, 0);
subscriptionMsgFlyweight.wrap(buffer, 0);
correlatedMsgFlyweight.wrap(buffer, 0);
removeMsgFlyweight.wrap(buffer, 0);
toDriverCommands.consumerHeartbeatTimeNs(clock.time());
}
private static AeronClient findClient(final ArrayList<AeronClient> clients, final long clientId)
{
AeronClient aeronClient = null;
for (int i = 0, size = clients.size(); i < size; i++)
{
final AeronClient client = clients.get(i);
if (client.clientId() == clientId)
{
aeronClient = client;
break;
}
}
return aeronClient;
}
private static String generateSourceInfo(final InetSocketAddress address)
{
return String.format("%s:%d", address.getHostString(), address.getPort());
}
private static DriverSubscription removeSubscription(
final ArrayList<DriverSubscription> subscriptions, final long registrationId)
{
DriverSubscription subscription = null;
for (int i = 0, size = subscriptions.size(); i < size; i++)
{
subscription = subscriptions.get(i);
if (subscription.registrationId() == registrationId)
{
subscriptions.remove(i);
break;
}
}
return subscription;
}
public void onClose()
{
rawLogFactory.close();
publications.forEach(NetworkPublication::close);
connections.forEach(NetworkConnection::close);
sendChannelEndpointByChannelMap.values().forEach(SendChannelEndpoint::close);
receiveChannelEndpointByChannelMap.values().forEach(ReceiveChannelEndpoint::close);
}
public String roleName()
{
return "driver-conductor";
}
public SendChannelEndpoint senderChannelEndpoint(final UdpChannel channel)
{
return sendChannelEndpointByChannelMap.get(channel.canonicalForm());
}
public ReceiveChannelEndpoint receiverChannelEndpoint(final UdpChannel channel)
{
return receiveChannelEndpointByChannelMap.get(channel.canonicalForm());
}
public int doWork() throws Exception
{
int workCount = 0;
workCount += toDriverCommands.read(onClientCommandFunc);
workCount += driverConductorCmdQueue.drain(onDriverConductorCmdFunc);
workCount += toEventReader.read(onEventFunc, EVENT_READER_FRAME_LIMIT);
workCount += processTimers();
final ArrayList<NetworkConnection> connections = this.connections;
for (int i = 0, size = connections.size(); i < size; i++)
{
final NetworkConnection connection = connections.get(i);
workCount += connection.trackRebuild();
}
final ArrayList<NetworkPublication> publications = this.publications;
for (int i = 0, size = publications.size(); i < size; i++)
{
final NetworkPublication publication = publications.get(i);
workCount += publication.updatePublishersLimit() + publication.cleanLogBuffer();
}
return workCount;
}
private void onHeartbeatCheckTimeouts()
{
final long now = clock.time();
toDriverCommands.consumerHeartbeatTimeNs(now);
onCheckClients(now);
onCheckPublications(now);
onCheckPublicationRegistrations(now);
onCheckSubscriptions(now);
onCheckConnections(now);
timerWheel.rescheduleTimeout(HEARTBEAT_TIMEOUT_MS, TimeUnit.MILLISECONDS, checkTimeoutTimer);
}
public void onCreateConnection(
final int sessionId,
final int streamId,
final int initialTermId,
final int activeTermId,
final int initialTermOffset,
final int termBufferLength,
final int senderMtuLength,
final InetSocketAddress controlAddress,
final InetSocketAddress sourceAddress,
final ReceiveChannelEndpoint channelEndpoint)
{
channelEndpoint.validateSenderMtuLength(senderMtuLength);
channelEndpoint.validateWindowMaxLength(initialWindowLength);
final UdpChannel udpChannel = channelEndpoint.udpChannel();
final String channel = udpChannel.originalUriString();
final long correlationId = generateCreationCorrelationId();
final long joiningPosition = LogBufferDescriptor.computePosition(
activeTermId, initialTermOffset, Integer.numberOfTrailingZeros(termBufferLength), initialTermId);
final List<SubscriberPosition> subscriberPositions = listSubscriberPositions(
sessionId, streamId, channelEndpoint, channel, joiningPosition);
final RawLog rawLog = rawLogFactory.newConnection(
udpChannel.canonicalForm(), sessionId, streamId, correlationId, termBufferLength);
final NetworkConnection connection = new NetworkConnection(
correlationId,
channelEndpoint,
controlAddress,
sessionId,
streamId,
initialTermId,
activeTermId,
initialTermOffset,
initialWindowLength,
rawLog,
timerWheel,
udpChannel.isMulticast() ? NAK_MULTICAST_DELAY_GENERATOR : NAK_UNICAST_DELAY_GENERATOR,
subscriberPositions.stream().map(SubscriberPosition::position).collect(toList()),
newPosition("receiver hwm", channel, sessionId, streamId, correlationId),
clock,
systemCounters,
sourceAddress,
logger);
subscriberPositions.forEach(
(subscriberPosition) -> subscriberPosition.subscription().addConnection(connection, subscriberPosition.position()));
connections.add(connection);
receiverProxy.newConnection(channelEndpoint, connection);
clientProxy.onConnectionReady(
channel,
streamId,
sessionId,
joiningPosition,
rawLog,
correlationId,
subscriberPositions,
generateSourceInfo(sourceAddress));
}
public List<SubscriberPosition> listSubscriberPositions(
final int sessionId,
final int streamId,
final ReceiveChannelEndpoint channelEndpoint,
final String channel,
final long joiningPosition)
{
return subscriptions
.stream()
.filter((subscription) -> subscription.matches(channelEndpoint, streamId))
.map(
(subscription) ->
{
final Position position = newPosition(
"subscriber pos", channel, sessionId, streamId, subscription.registrationId());
position.setOrdered(joiningPosition);
return new SubscriberPosition(subscription, position);
})
.collect(toList());
}
private void onClientCommand(final int msgTypeId, final MutableDirectBuffer buffer, final int index, final int length)
{
Flyweight flyweight = null;
try
{
switch (msgTypeId)
{
case ADD_PUBLICATION:
{
logger.log(EventCode.CMD_IN_ADD_PUBLICATION, buffer, index, length);
final PublicationMessageFlyweight publicationMessageFlyweight = publicationMsgFlyweight;
publicationMessageFlyweight.offset(index);
flyweight = publicationMessageFlyweight;
onAddPublication(
publicationMessageFlyweight.channel(),
publicationMessageFlyweight.sessionId(),
publicationMessageFlyweight.streamId(),
publicationMessageFlyweight.correlationId(),
publicationMessageFlyweight.clientId());
break;
}
case REMOVE_PUBLICATION:
{
logger.log(EventCode.CMD_IN_REMOVE_PUBLICATION, buffer, index, length);
final RemoveMessageFlyweight removeMessageFlyweight = removeMsgFlyweight;
removeMessageFlyweight.offset(index);
flyweight = removeMessageFlyweight;
onRemovePublication(removeMessageFlyweight.registrationId(), removeMessageFlyweight.correlationId());
break;
}
case ADD_SUBSCRIPTION:
{
logger.log(EventCode.CMD_IN_ADD_SUBSCRIPTION, buffer, index, length);
final SubscriptionMessageFlyweight subscriptionMessageFlyweight = subscriptionMsgFlyweight;
subscriptionMessageFlyweight.offset(index);
flyweight = subscriptionMessageFlyweight;
onAddSubscription(
subscriptionMessageFlyweight.channel(),
subscriptionMessageFlyweight.streamId(),
subscriptionMessageFlyweight.correlationId(),
subscriptionMessageFlyweight.clientId());
break;
}
case REMOVE_SUBSCRIPTION:
{
logger.log(EventCode.CMD_IN_REMOVE_SUBSCRIPTION, buffer, index, length);
final RemoveMessageFlyweight removeMessageFlyweight = removeMsgFlyweight;
removeMessageFlyweight.offset(index);
flyweight = removeMessageFlyweight;
onRemoveSubscription(removeMessageFlyweight.registrationId(), removeMessageFlyweight.correlationId());
break;
}
case CLIENT_KEEPALIVE:
{
logger.log(EventCode.CMD_IN_KEEPALIVE_CLIENT, buffer, index, length);
final CorrelatedMessageFlyweight correlatedMessageFlyweight = correlatedMsgFlyweight;
correlatedMessageFlyweight.offset(index);
flyweight = correlatedMessageFlyweight;
onClientKeepalive(correlatedMessageFlyweight.clientId());
break;
}
}
}
catch (final ControlProtocolException ex)
{
clientProxy.onError(ex.errorCode(), ex.getMessage(), flyweight, length);
logger.logException(ex);
}
catch (final Exception ex)
{
clientProxy.onError(GENERIC_ERROR, ex.getMessage(), flyweight, length);
logger.logException(ex);
}
}
private int processTimers()
{
int workCount = 0;
if (timerWheel.computeDelayInMs() <= 0)
{
workCount = timerWheel.expireTimers();
}
return workCount;
}
private void onAddPublication(
final String channel, final int sessionId, final int streamId, final long correlationId, final long clientId)
{
final UdpChannel udpChannel = UdpChannel.parse(channel);
final SendChannelEndpoint channelEndpoint = getOrCreateSendChannelEndpoint(udpChannel);
NetworkPublication publication = channelEndpoint.getPublication(sessionId, streamId);
if (null == publication)
{
final int initialTermId = BitUtil.generateRandomisedId();
final FlowControl flowControl = udpChannel.isMulticast() ? multicastFlowControl.get() : unicastFlowControl.get();
publication = new NetworkPublication(
channelEndpoint,
clock,
newPublicationLog(sessionId, streamId, correlationId, udpChannel, initialTermId),
newPosition("sender pos", channel, sessionId, streamId, correlationId),
newPosition("publisher limit", channel, sessionId, streamId, correlationId),
sessionId,
streamId,
initialTermId,
mtuLength,
flowControl.initialPositionLimit(initialTermId, termBufferLength),
systemCounters);
channelEndpoint.addPublication(publication);
publications.add(publication);
senderProxy.newPublication(publication, newRetransmitHandler(publication, initialTermId), flowControl);
}
final AeronClient client = getOrAddClient(clientId);
if (null != publicationRegistrations.putIfAbsent(correlationId, new PublicationRegistration(publication, client)))
{
throw new ControlProtocolException(GENERIC_ERROR, "registration id already in use.");
}
publication.incRef();
clientProxy.onPublicationReady(
channel,
streamId,
sessionId,
publication.rawLog(),
correlationId,
publication.publisherLimitId());
}
private RetransmitHandler newRetransmitHandler(final NetworkPublication publication, final int initialTermId)
{
return new RetransmitHandler(
timerWheel,
systemCounters,
RETRANS_UNICAST_DELAY_GENERATOR,
RETRANS_UNICAST_LINGER_GENERATOR,
publication,
initialTermId,
termBufferLength);
}
private RawLog newPublicationLog(
final int sessionId, final int streamId, final long correlationId, final UdpChannel udpChannel, final int initialTermId)
{
final String canonicalForm = udpChannel.canonicalForm();
final RawLog rawLog = rawLogFactory.newPublication(canonicalForm, sessionId, streamId, correlationId);
final MutableDirectBuffer header = DataHeaderFlyweight.createDefaultHeader(sessionId, streamId, initialTermId);
final UnsafeBuffer logMetaData = rawLog.logMetaData();
LogBufferDescriptor.storeDefaultFrameHeaders(logMetaData, header);
LogBufferDescriptor.initialTermId(logMetaData, initialTermId);
LogBufferDescriptor.mtuLength(logMetaData, mtuLength);
return rawLog;
}
private SendChannelEndpoint getOrCreateSendChannelEndpoint(final UdpChannel udpChannel)
{
SendChannelEndpoint channelEndpoint = sendChannelEndpointByChannelMap.get(udpChannel.canonicalForm());
if (null == channelEndpoint)
{
logger.logChannelCreated(udpChannel.description());
channelEndpoint = new SendChannelEndpoint(
udpChannel,
logger,
Configuration.createLossGenerator(controlLossRate, controlLossSeed),
systemCounters);
channelEndpoint.validateMtuLength(mtuLength);
sendChannelEndpointByChannelMap.put(udpChannel.canonicalForm(), channelEndpoint);
senderProxy.registerSendChannelEndpoint(channelEndpoint);
}
return channelEndpoint;
}
private void onRemovePublication(final long registrationId, final long correlationId)
{
final PublicationRegistration registration = publicationRegistrations.remove(registrationId);
if (registration == null)
{
throw new ControlProtocolException(UNKNOWN_PUBLICATION, "Unknown publication: " + registrationId);
}
registration.remove();
clientProxy.operationSucceeded(correlationId);
}
private void onAddSubscription(final String channel, final int streamId, final long correlationId, final long clientId)
{
final ReceiveChannelEndpoint channelEndpoint = getOrCreateReceiveChannelEndpoint(UdpChannel.parse(channel));
channelEndpoint.incRefToStream(streamId);
receiverProxy.addSubscription(channelEndpoint, streamId);
final AeronClient client = getOrAddClient(clientId);
final DriverSubscription subscription = new DriverSubscription(correlationId, channelEndpoint, streamId, client);
subscriptions.add(subscription);
clientProxy.operationSucceeded(correlationId);
connections
.stream()
.filter((connection) -> connection.matches(channelEndpoint, streamId))
.forEach(
(connection) ->
{
final Position position = newPosition(
"subscriber pos", channel, connection.sessionId(), streamId, correlationId);
connection.addSubscriber(position);
subscription.addConnection(connection, position);
clientProxy.onConnectionReady(
channel,
streamId,
connection.sessionId(),
connection.rebuildPosition(),
connection.rawLog(),
correlationId,
Collections.singletonList(new SubscriberPosition(subscription, position)),
generateSourceInfo(connection.sourceAddress()));
});
}
private ReceiveChannelEndpoint getOrCreateReceiveChannelEndpoint(final UdpChannel udpChannel)
{
ReceiveChannelEndpoint channelEndpoint = receiveChannelEndpointByChannelMap.get(udpChannel.canonicalForm());
if (null == channelEndpoint)
{
final LossGenerator lossGenerator = Configuration.createLossGenerator(dataLossRate, dataLossSeed);
channelEndpoint = new ReceiveChannelEndpoint(
udpChannel, conductorProxy, receiverProxy.receiver(), logger, systemCounters, lossGenerator);
receiveChannelEndpointByChannelMap.put(udpChannel.canonicalForm(), channelEndpoint);
receiverProxy.registerReceiveChannelEndpoint(channelEndpoint);
}
return channelEndpoint;
}
private void onRemoveSubscription(final long registrationId, final long correlationId)
{
final DriverSubscription subscription = removeSubscription(subscriptions, registrationId);
if (null == subscription)
{
throw new ControlProtocolException(UNKNOWN_SUBSCRIPTION, "Unknown subscription: " + registrationId);
}
subscription.close();
final ReceiveChannelEndpoint channelEndpoint = subscription.channelEndpoint();
final int refCount = channelEndpoint.decRefToStream(subscription.streamId());
if (0 == refCount)
{
receiverProxy.removeSubscription(channelEndpoint, subscription.streamId());
}
if (0 == channelEndpoint.streamCount())
{
receiveChannelEndpointByChannelMap.remove(channelEndpoint.udpChannel().canonicalForm());
receiverProxy.closeReceiveChannelEndpoint(channelEndpoint);
while (!channelEndpoint.isClosed())
{
Thread.yield();
}
}
clientProxy.operationSucceeded(correlationId);
}
private void onClientKeepalive(final long clientId)
{
systemCounters.clientKeepAlives().addOrdered(1);
final AeronClient client = findClient(clients, clientId);
if (null != client)
{
client.timeOfLastKeepalive(clock.time());
}
}
private void onCheckPublicationRegistrations(final long now)
{
final Iterator<PublicationRegistration> iter = publicationRegistrations.values().iterator();
while (iter.hasNext())
{
final PublicationRegistration registration = iter.next();
if (registration.hasClientTimedOut(now))
{
iter.remove();
}
}
}
private void onCheckPublications(final long now)
{
final ArrayList<NetworkPublication> publications = this.publications;
for (int i = publications.size() - 1; i >= 0; i--)
{
final NetworkPublication publication = publications.get(i);
if (publication.isUnreferencedAndFlushed(now) && now > (publication.timeOfFlush() + PUBLICATION_LINGER_NS))
{
final SendChannelEndpoint channelEndpoint = publication.sendChannelEndpoint();
logger.logPublicationRemoval(
channelEndpoint.originalUriString(), publication.sessionId(), publication.streamId());
channelEndpoint.removePublication(publication);
publications.remove(i);
senderProxy.closePublication(publication);
if (channelEndpoint.sessionCount() == 0)
{
sendChannelEndpointByChannelMap.remove(channelEndpoint.udpChannel().canonicalForm());
senderProxy.closeSendChannelEndpoint(channelEndpoint);
}
}
}
}
private void onCheckSubscriptions(final long now)
{
final ArrayList<DriverSubscription> subscriptions = this.subscriptions;
for (int i = subscriptions.size() - 1; i >= 0; i--)
{
final DriverSubscription subscription = subscriptions.get(i);
if (now > (subscription.timeOfLastKeepaliveFromClient() + CLIENT_LIVENESS_TIMEOUT_NS))
{
final ReceiveChannelEndpoint channelEndpoint = subscription.channelEndpoint();
final int streamId = subscription.streamId();
logger.logSubscriptionRemoval(
channelEndpoint.originalUriString(), subscription.streamId(), subscription.registrationId());
subscriptions.remove(i);
subscription.close();
if (0 == channelEndpoint.decRefToStream(subscription.streamId()))
{
receiverProxy.removeSubscription(channelEndpoint, streamId);
}
if (channelEndpoint.streamCount() == 0)
{
receiveChannelEndpointByChannelMap.remove(channelEndpoint.udpChannel().canonicalForm());
receiverProxy.closeReceiveChannelEndpoint(channelEndpoint);
}
}
}
}
private void onCheckConnections(final long now)
{
final ArrayList<NetworkConnection> connections = this.connections;
for (int i = connections.size() - 1; i >= 0; i--)
{
final NetworkConnection conn = connections.get(i);
switch (conn.status())
{
case INACTIVE:
if (conn.isDrained() || now > (conn.timeOfLastStatusChange() + CONNECTION_LIVENESS_TIMEOUT_NS))
{
conn.status(NetworkConnection.Status.LINGER);
clientProxy.onInactiveConnection(
conn.correlationId(),
conn.sessionId(),
conn.streamId(),
conn.rebuildPosition(),
conn.channelUriString());
}
break;
case LINGER:
if (now > (conn.timeOfLastStatusChange() + CONNECTION_LIVENESS_TIMEOUT_NS))
{
logger.logConnectionRemoval(conn.channelUriString(), conn.sessionId(), conn.streamId());
connections.remove(i);
conn.close();
}
break;
}
}
}
private void onCheckClients(final long now)
{
for (int i = clients.size() - 1; i >= 0; i--)
{
final AeronClient client = clients.get(i);
if (now > (client.timeOfLastKeepalive() + CONNECTION_LIVENESS_TIMEOUT_NS))
{
clients.remove(i);
}
}
}
private void onDriverConductorCmd(final DriverConductorCmd cmd)
{
cmd.execute(this);
}
private AeronClient getOrAddClient(final long clientId)
{
AeronClient client = findClient(clients, clientId);
if (null == client)
{
client = new AeronClient(clientId, clock.time());
clients.add(client);
}
return client;
}
private Position newPosition(
final String name, final String channel, final int sessionId, final int streamId, final long correlationId)
{
final int positionId = allocateCounter(name, channel, sessionId, streamId, correlationId);
return new UnsafeBufferPosition(countersBuffer, positionId, countersManager);
}
private int allocateCounter(
final String type, final String channel, final int sessionId, final int streamId, final long correlationId)
{
return countersManager.allocate(String.format("%s: %s %x %x %x", type, channel, sessionId, streamId, correlationId));
}
private long generateCreationCorrelationId()
{
return toDriverCommands.nextCorrelationId();
}
}
| aeron-driver/src/main/java/uk/co/real_logic/aeron/driver/DriverConductor.java | /*
* Copyright 2014 - 2015 Real Logic Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.real_logic.aeron.driver;
import uk.co.real_logic.aeron.common.Flyweight;
import uk.co.real_logic.aeron.common.command.CorrelatedMessageFlyweight;
import uk.co.real_logic.aeron.common.command.PublicationMessageFlyweight;
import uk.co.real_logic.aeron.common.command.RemoveMessageFlyweight;
import uk.co.real_logic.aeron.common.command.SubscriptionMessageFlyweight;
import uk.co.real_logic.aeron.common.concurrent.logbuffer.LogBufferDescriptor;
import uk.co.real_logic.aeron.common.event.EventCode;
import uk.co.real_logic.aeron.common.event.EventLogger;
import uk.co.real_logic.aeron.common.protocol.DataHeaderFlyweight;
import uk.co.real_logic.aeron.driver.buffer.RawLog;
import uk.co.real_logic.aeron.driver.buffer.RawLogFactory;
import uk.co.real_logic.aeron.driver.cmd.DriverConductorCmd;
import uk.co.real_logic.aeron.driver.exceptions.ControlProtocolException;
import uk.co.real_logic.agrona.BitUtil;
import uk.co.real_logic.agrona.MutableDirectBuffer;
import uk.co.real_logic.agrona.TimerWheel;
import uk.co.real_logic.agrona.collections.Long2ObjectHashMap;
import uk.co.real_logic.agrona.concurrent.*;
import uk.co.real_logic.agrona.concurrent.ringbuffer.RingBuffer;
import uk.co.real_logic.agrona.concurrent.status.UnsafeBufferPosition;
import java.net.InetSocketAddress;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Supplier;
import static java.util.stream.Collectors.toList;
import static uk.co.real_logic.aeron.common.ErrorCode.*;
import static uk.co.real_logic.aeron.common.command.ControlProtocolEvents.*;
import static uk.co.real_logic.aeron.common.event.EventConfiguration.EVENT_READER_FRAME_LIMIT;
import static uk.co.real_logic.aeron.driver.Configuration.*;
import static uk.co.real_logic.aeron.driver.MediaDriver.Context;
/**
* Driver Conductor to take commands from publishers and subscribers as well as handle NAKs and retransmissions
*/
public class DriverConductor implements Agent
{
private final long dataLossSeed;
private final long controlLossSeed;
private final double dataLossRate;
private final double controlLossRate;
private final int mtuLength;
private final int termBufferLength;
private final int initialWindowLength;
private final RawLogFactory rawLogFactory;
private final ReceiverProxy receiverProxy;
private final SenderProxy senderProxy;
private final ClientProxy clientProxy;
private final DriverConductorProxy conductorProxy;
private final RingBuffer toDriverCommands;
private final RingBuffer toEventReader;
private final OneToOneConcurrentArrayQueue<DriverConductorCmd> driverConductorCmdQueue;
private final Supplier<FlowControl> unicastFlowControl;
private final Supplier<FlowControl> multicastFlowControl;
private final HashMap<String, SendChannelEndpoint> sendChannelEndpointByChannelMap = new HashMap<>();
private final HashMap<String, ReceiveChannelEndpoint> receiveChannelEndpointByChannelMap = new HashMap<>();
private final Long2ObjectHashMap<PublicationRegistration> publicationRegistrations = new Long2ObjectHashMap<>();
private final ArrayList<NetworkPublication> publications = new ArrayList<>();
private final ArrayList<DriverSubscription> subscriptions = new ArrayList<>();
private final ArrayList<NetworkConnection> connections = new ArrayList<>();
private final ArrayList<AeronClient> clients = new ArrayList<>();
private final PublicationMessageFlyweight publicationMsgFlyweight = new PublicationMessageFlyweight();
private final SubscriptionMessageFlyweight subscriptionMsgFlyweight = new SubscriptionMessageFlyweight();
private final CorrelatedMessageFlyweight correlatedMsgFlyweight = new CorrelatedMessageFlyweight();
private final RemoveMessageFlyweight removeMsgFlyweight = new RemoveMessageFlyweight();
private final NanoClock clock;
private final TimerWheel timerWheel;
private final TimerWheel.Timer checkTimeoutTimer;
private final SystemCounters systemCounters;
private final UnsafeBuffer countersBuffer;
private final CountersManager countersManager;
private final EventLogger logger;
private final Consumer<DriverConductorCmd> onDriverConductorCmdFunc = this::onDriverConductorCmd;
private final MessageHandler onClientCommandFunc = this::onClientCommand;
private final MessageHandler onEventFunc;
public DriverConductor(final Context ctx)
{
driverConductorCmdQueue = ctx.conductorCommandQueue();
receiverProxy = ctx.receiverProxy();
senderProxy = ctx.senderProxy();
rawLogFactory = ctx.rawLogBuffersFactory();
mtuLength = ctx.mtuLength();
initialWindowLength = ctx.initialWindowLength();
termBufferLength = ctx.termBufferLength();
unicastFlowControl = ctx.unicastSenderFlowControl();
multicastFlowControl = ctx.multicastSenderFlowControl();
countersManager = ctx.countersManager();
countersBuffer = ctx.countersBuffer();
timerWheel = ctx.conductorTimerWheel();
clock = timerWheel.clock();
toDriverCommands = ctx.toDriverCommands();
toEventReader = ctx.toEventReader();
clientProxy = ctx.clientProxy();
conductorProxy = ctx.driverConductorProxy();
logger = ctx.eventLogger();
dataLossRate = ctx.dataLossRate();
dataLossSeed = ctx.dataLossSeed();
controlLossRate = ctx.controlLossRate();
controlLossSeed = ctx.controlLossSeed();
systemCounters = ctx.systemCounters();
checkTimeoutTimer = timerWheel.newTimeout(HEARTBEAT_TIMEOUT_MS, TimeUnit.MILLISECONDS, this::onHeartbeatCheckTimeouts);
final Consumer<String> eventConsumer = ctx.eventConsumer();
onEventFunc =
(typeId, buffer, offset, length) -> eventConsumer.accept(EventCode.get(typeId).decode(buffer, offset, length));
final AtomicBuffer buffer = toDriverCommands.buffer();
publicationMsgFlyweight.wrap(buffer, 0);
subscriptionMsgFlyweight.wrap(buffer, 0);
correlatedMsgFlyweight.wrap(buffer, 0);
removeMsgFlyweight.wrap(buffer, 0);
toDriverCommands.consumerHeartbeatTimeNs(clock.time());
}
private static AeronClient findClient(final ArrayList<AeronClient> clients, final long clientId)
{
AeronClient aeronClient = null;
for (int i = 0, size = clients.size(); i < size; i++)
{
final AeronClient client = clients.get(i);
if (client.clientId() == clientId)
{
aeronClient = client;
break;
}
}
return aeronClient;
}
private static String generateSourceInfo(final InetSocketAddress address)
{
return String.format("%s:%d", address.getHostString(), address.getPort());
}
private static DriverSubscription removeSubscription(
final ArrayList<DriverSubscription> subscriptions, final long registrationId)
{
DriverSubscription subscription = null;
for (int i = 0, size = subscriptions.size(); i < size; i++)
{
subscription = subscriptions.get(i);
if (subscription.registrationId() == registrationId)
{
subscriptions.remove(i);
break;
}
}
return subscription;
}
public void onClose()
{
rawLogFactory.close();
publications.forEach(NetworkPublication::close);
connections.forEach(NetworkConnection::close);
sendChannelEndpointByChannelMap.values().forEach(SendChannelEndpoint::close);
receiveChannelEndpointByChannelMap.values().forEach(ReceiveChannelEndpoint::close);
}
public String roleName()
{
return "driver-conductor";
}
public SendChannelEndpoint senderChannelEndpoint(final UdpChannel channel)
{
return sendChannelEndpointByChannelMap.get(channel.canonicalForm());
}
public ReceiveChannelEndpoint receiverChannelEndpoint(final UdpChannel channel)
{
return receiveChannelEndpointByChannelMap.get(channel.canonicalForm());
}
public int doWork() throws Exception
{
int workCount = 0;
workCount += toDriverCommands.read(onClientCommandFunc);
workCount += driverConductorCmdQueue.drain(onDriverConductorCmdFunc);
workCount += toEventReader.read(onEventFunc, EVENT_READER_FRAME_LIMIT);
workCount += processTimers();
final ArrayList<NetworkConnection> connections = this.connections;
for (int i = 0, size = connections.size(); i < size; i++)
{
final NetworkConnection connection = connections.get(i);
workCount += connection.trackRebuild();
}
final ArrayList<NetworkPublication> publications = this.publications;
for (int i = 0, size = publications.size(); i < size; i++)
{
final NetworkPublication publication = publications.get(i);
workCount += publication.updatePublishersLimit() + publication.cleanLogBuffer();
}
return workCount;
}
private void onHeartbeatCheckTimeouts()
{
final long now = clock.time();
toDriverCommands.consumerHeartbeatTimeNs(now);
onCheckClients(now);
onCheckPublications(now);
onCheckPublicationRegistrations(now);
onCheckSubscriptions(now);
onCheckConnections(now);
timerWheel.rescheduleTimeout(HEARTBEAT_TIMEOUT_MS, TimeUnit.MILLISECONDS, checkTimeoutTimer);
}
public void onCreateConnection(
final int sessionId,
final int streamId,
final int initialTermId,
final int activeTermId,
final int initialTermOffset,
final int termBufferLength,
final int senderMtuLength,
final InetSocketAddress controlAddress,
final InetSocketAddress sourceAddress,
final ReceiveChannelEndpoint channelEndpoint)
{
channelEndpoint.validateSenderMtuLength(senderMtuLength);
channelEndpoint.validateWindowMaxLength(initialWindowLength);
final UdpChannel udpChannel = channelEndpoint.udpChannel();
final String channel = udpChannel.originalUriString();
final long correlationId = generateCreationCorrelationId();
final long joiningPosition = LogBufferDescriptor.computePosition(
activeTermId, initialTermOffset, Integer.numberOfTrailingZeros(termBufferLength), initialTermId);
final List<SubscriberPosition> subscriberPositions = listSubscriberPositions(
sessionId, streamId, channelEndpoint, channel, joiningPosition);
final int receiverHwmId = allocateCounter("receiver hwm", channel, sessionId, streamId, correlationId);
final RawLog rawLog = rawLogFactory.newConnection(
udpChannel.canonicalForm(), sessionId, streamId, correlationId, termBufferLength);
final NetworkConnection connection = new NetworkConnection(
correlationId,
channelEndpoint,
controlAddress,
sessionId,
streamId,
initialTermId,
activeTermId,
initialTermOffset,
initialWindowLength,
rawLog,
timerWheel,
udpChannel.isMulticast() ? NAK_MULTICAST_DELAY_GENERATOR : NAK_UNICAST_DELAY_GENERATOR,
subscriberPositions.stream().map(SubscriberPosition::position).collect(toList()),
new UnsafeBufferPosition(countersBuffer, receiverHwmId, countersManager),
clock,
systemCounters,
sourceAddress,
logger);
subscriberPositions.forEach(
(subscriberPosition) -> subscriberPosition.subscription().addConnection(connection, subscriberPosition.position()));
connections.add(connection);
receiverProxy.newConnection(channelEndpoint, connection);
clientProxy.onConnectionReady(
channel,
streamId,
sessionId,
joiningPosition,
rawLog,
correlationId,
subscriberPositions,
generateSourceInfo(sourceAddress));
}
public List<SubscriberPosition> listSubscriberPositions(
final int sessionId,
final int streamId,
final ReceiveChannelEndpoint channelEndpoint,
final String channel,
final long joiningPosition)
{
return subscriptions
.stream()
.filter((subscription) -> subscription.matches(channelEndpoint, streamId))
.map(
(subscription) ->
{
final int positionId = allocateCounter(
"subscriber pos", channel, sessionId, streamId, subscription.registrationId());
final UnsafeBufferPosition position = new UnsafeBufferPosition(countersBuffer, positionId, countersManager);
countersManager.setCounterValue(positionId, joiningPosition);
return new SubscriberPosition(subscription, position);
})
.collect(toList());
}
private void onClientCommand(final int msgTypeId, final MutableDirectBuffer buffer, final int index, final int length)
{
Flyweight flyweight = null;
try
{
switch (msgTypeId)
{
case ADD_PUBLICATION:
{
logger.log(EventCode.CMD_IN_ADD_PUBLICATION, buffer, index, length);
final PublicationMessageFlyweight publicationMessageFlyweight = publicationMsgFlyweight;
publicationMessageFlyweight.offset(index);
flyweight = publicationMessageFlyweight;
onAddPublication(
publicationMessageFlyweight.channel(),
publicationMessageFlyweight.sessionId(),
publicationMessageFlyweight.streamId(),
publicationMessageFlyweight.correlationId(),
publicationMessageFlyweight.clientId());
break;
}
case REMOVE_PUBLICATION:
{
logger.log(EventCode.CMD_IN_REMOVE_PUBLICATION, buffer, index, length);
final RemoveMessageFlyweight removeMessageFlyweight = removeMsgFlyweight;
removeMessageFlyweight.offset(index);
flyweight = removeMessageFlyweight;
onRemovePublication(removeMessageFlyweight.registrationId(), removeMessageFlyweight.correlationId());
break;
}
case ADD_SUBSCRIPTION:
{
logger.log(EventCode.CMD_IN_ADD_SUBSCRIPTION, buffer, index, length);
final SubscriptionMessageFlyweight subscriptionMessageFlyweight = subscriptionMsgFlyweight;
subscriptionMessageFlyweight.offset(index);
flyweight = subscriptionMessageFlyweight;
onAddSubscription(
subscriptionMessageFlyweight.channel(),
subscriptionMessageFlyweight.streamId(),
subscriptionMessageFlyweight.correlationId(),
subscriptionMessageFlyweight.clientId());
break;
}
case REMOVE_SUBSCRIPTION:
{
logger.log(EventCode.CMD_IN_REMOVE_SUBSCRIPTION, buffer, index, length);
final RemoveMessageFlyweight removeMessageFlyweight = removeMsgFlyweight;
removeMessageFlyweight.offset(index);
flyweight = removeMessageFlyweight;
onRemoveSubscription(removeMessageFlyweight.registrationId(), removeMessageFlyweight.correlationId());
break;
}
case CLIENT_KEEPALIVE:
{
logger.log(EventCode.CMD_IN_KEEPALIVE_CLIENT, buffer, index, length);
final CorrelatedMessageFlyweight correlatedMessageFlyweight = correlatedMsgFlyweight;
correlatedMessageFlyweight.offset(index);
flyweight = correlatedMessageFlyweight;
onClientKeepalive(correlatedMessageFlyweight.clientId());
break;
}
}
}
catch (final ControlProtocolException ex)
{
clientProxy.onError(ex.errorCode(), ex.getMessage(), flyweight, length);
logger.logException(ex);
}
catch (final Exception ex)
{
clientProxy.onError(GENERIC_ERROR, ex.getMessage(), flyweight, length);
logger.logException(ex);
}
}
private int processTimers()
{
int workCount = 0;
if (timerWheel.computeDelayInMs() <= 0)
{
workCount = timerWheel.expireTimers();
}
return workCount;
}
private void onAddPublication(
final String channel, final int sessionId, final int streamId, final long correlationId, final long clientId)
{
final UdpChannel udpChannel = UdpChannel.parse(channel);
final SendChannelEndpoint channelEndpoint = getOrCreateSendChannelEndpoint(udpChannel);
NetworkPublication publication = channelEndpoint.getPublication(sessionId, streamId);
if (null == publication)
{
final int initialTermId = BitUtil.generateRandomisedId();
final RawLog rawLog = newPublicationLog(sessionId, streamId, correlationId, udpChannel, initialTermId);
final int senderPositionId = allocateCounter("sender pos", channel, sessionId, streamId, correlationId);
final int publisherLimitId = allocateCounter("publisher limit", channel, sessionId, streamId, correlationId);
final FlowControl flowControl = udpChannel.isMulticast() ? multicastFlowControl.get() : unicastFlowControl.get();
publication = new NetworkPublication(
channelEndpoint,
clock,
rawLog,
new UnsafeBufferPosition(countersBuffer, senderPositionId, countersManager),
new UnsafeBufferPosition(countersBuffer, publisherLimitId, countersManager),
sessionId,
streamId,
initialTermId,
mtuLength,
flowControl.initialPositionLimit(initialTermId, termBufferLength),
systemCounters);
channelEndpoint.addPublication(publication);
publications.add(publication);
senderProxy.newPublication(publication, newRetransmitHandler(publication, initialTermId), flowControl);
}
final AeronClient client = getOrAddClient(clientId);
if (null != publicationRegistrations.putIfAbsent(correlationId, new PublicationRegistration(publication, client)))
{
throw new ControlProtocolException(GENERIC_ERROR, "registration id already in use.");
}
publication.incRef();
clientProxy.onPublicationReady(
channel,
streamId,
sessionId,
publication.rawLog(),
correlationId,
publication.publisherLimitId());
}
private RetransmitHandler newRetransmitHandler(final NetworkPublication publication, final int initialTermId)
{
return new RetransmitHandler(
timerWheel,
systemCounters,
RETRANS_UNICAST_DELAY_GENERATOR,
RETRANS_UNICAST_LINGER_GENERATOR,
publication,
initialTermId,
termBufferLength);
}
private RawLog newPublicationLog(
final int sessionId, final int streamId, final long correlationId, final UdpChannel udpChannel, final int initialTermId)
{
final String canonicalForm = udpChannel.canonicalForm();
final RawLog rawLog = rawLogFactory.newPublication(canonicalForm, sessionId, streamId, correlationId);
final MutableDirectBuffer header = DataHeaderFlyweight.createDefaultHeader(sessionId, streamId, initialTermId);
final UnsafeBuffer logMetaData = rawLog.logMetaData();
LogBufferDescriptor.storeDefaultFrameHeaders(logMetaData, header);
LogBufferDescriptor.initialTermId(logMetaData, initialTermId);
LogBufferDescriptor.mtuLength(logMetaData, mtuLength);
return rawLog;
}
private SendChannelEndpoint getOrCreateSendChannelEndpoint(final UdpChannel udpChannel)
{
SendChannelEndpoint channelEndpoint = sendChannelEndpointByChannelMap.get(udpChannel.canonicalForm());
if (null == channelEndpoint)
{
logger.logChannelCreated(udpChannel.description());
channelEndpoint = new SendChannelEndpoint(
udpChannel,
logger,
Configuration.createLossGenerator(controlLossRate, controlLossSeed),
systemCounters);
channelEndpoint.validateMtuLength(mtuLength);
sendChannelEndpointByChannelMap.put(udpChannel.canonicalForm(), channelEndpoint);
senderProxy.registerSendChannelEndpoint(channelEndpoint);
}
return channelEndpoint;
}
private void onRemovePublication(final long registrationId, final long correlationId)
{
final PublicationRegistration registration = publicationRegistrations.remove(registrationId);
if (registration == null)
{
throw new ControlProtocolException(UNKNOWN_PUBLICATION, "Unknown publication: " + registrationId);
}
registration.remove();
clientProxy.operationSucceeded(correlationId);
}
private void onAddSubscription(final String channel, final int streamId, final long correlationId, final long clientId)
{
final ReceiveChannelEndpoint channelEndpoint = getOrCreateReceiveChannelEndpoint(UdpChannel.parse(channel));
channelEndpoint.incRefToStream(streamId);
receiverProxy.addSubscription(channelEndpoint, streamId);
final AeronClient client = getOrAddClient(clientId);
final DriverSubscription subscription = new DriverSubscription(correlationId, channelEndpoint, streamId, client);
subscriptions.add(subscription);
clientProxy.operationSucceeded(correlationId);
connections
.stream()
.filter((connection) -> connection.matches(channelEndpoint, streamId))
.forEach(
(connection) ->
{
final int subscriberPositionId = allocateCounter(
"subscriber pos", channel, connection.sessionId(), streamId, correlationId);
final UnsafeBufferPosition position = new UnsafeBufferPosition(
countersBuffer, subscriberPositionId, countersManager);
connection.addSubscriber(position);
subscription.addConnection(connection, position);
clientProxy.onConnectionReady(
channel,
streamId,
connection.sessionId(),
connection.rebuildPosition(),
connection.rawLog(),
correlationId,
Collections.singletonList(new SubscriberPosition(subscription, position)),
generateSourceInfo(connection.sourceAddress()));
});
}
private ReceiveChannelEndpoint getOrCreateReceiveChannelEndpoint(final UdpChannel udpChannel)
{
ReceiveChannelEndpoint channelEndpoint = receiveChannelEndpointByChannelMap.get(udpChannel.canonicalForm());
if (null == channelEndpoint)
{
final LossGenerator lossGenerator = Configuration.createLossGenerator(dataLossRate, dataLossSeed);
channelEndpoint = new ReceiveChannelEndpoint(
udpChannel, conductorProxy, receiverProxy.receiver(), logger, systemCounters, lossGenerator);
receiveChannelEndpointByChannelMap.put(udpChannel.canonicalForm(), channelEndpoint);
receiverProxy.registerReceiveChannelEndpoint(channelEndpoint);
}
return channelEndpoint;
}
private void onRemoveSubscription(final long registrationId, final long correlationId)
{
final DriverSubscription subscription = removeSubscription(subscriptions, registrationId);
if (null == subscription)
{
throw new ControlProtocolException(UNKNOWN_SUBSCRIPTION, "Unknown subscription: " + registrationId);
}
subscription.close();
final ReceiveChannelEndpoint channelEndpoint = subscription.channelEndpoint();
final int refCount = channelEndpoint.decRefToStream(subscription.streamId());
if (0 == refCount)
{
receiverProxy.removeSubscription(channelEndpoint, subscription.streamId());
}
if (0 == channelEndpoint.streamCount())
{
receiveChannelEndpointByChannelMap.remove(channelEndpoint.udpChannel().canonicalForm());
receiverProxy.closeReceiveChannelEndpoint(channelEndpoint);
while (!channelEndpoint.isClosed())
{
Thread.yield();
}
}
clientProxy.operationSucceeded(correlationId);
}
private void onClientKeepalive(final long clientId)
{
systemCounters.clientKeepAlives().addOrdered(1);
final AeronClient client = findClient(clients, clientId);
if (null != client)
{
client.timeOfLastKeepalive(clock.time());
}
}
private void onCheckPublicationRegistrations(final long now)
{
final Iterator<PublicationRegistration> iter = publicationRegistrations.values().iterator();
while (iter.hasNext())
{
final PublicationRegistration registration = iter.next();
if (registration.hasClientTimedOut(now))
{
iter.remove();
}
}
}
private void onCheckPublications(final long now)
{
final ArrayList<NetworkPublication> publications = this.publications;
for (int i = publications.size() - 1; i >= 0; i--)
{
final NetworkPublication publication = publications.get(i);
if (publication.isUnreferencedAndFlushed(now) && now > (publication.timeOfFlush() + PUBLICATION_LINGER_NS))
{
final SendChannelEndpoint channelEndpoint = publication.sendChannelEndpoint();
logger.logPublicationRemoval(
channelEndpoint.originalUriString(), publication.sessionId(), publication.streamId());
channelEndpoint.removePublication(publication);
publications.remove(i);
senderProxy.closePublication(publication);
if (channelEndpoint.sessionCount() == 0)
{
sendChannelEndpointByChannelMap.remove(channelEndpoint.udpChannel().canonicalForm());
senderProxy.closeSendChannelEndpoint(channelEndpoint);
}
}
}
}
private void onCheckSubscriptions(final long now)
{
final ArrayList<DriverSubscription> subscriptions = this.subscriptions;
for (int i = subscriptions.size() - 1; i >= 0; i--)
{
final DriverSubscription subscription = subscriptions.get(i);
if (now > (subscription.timeOfLastKeepaliveFromClient() + CLIENT_LIVENESS_TIMEOUT_NS))
{
final ReceiveChannelEndpoint channelEndpoint = subscription.channelEndpoint();
final int streamId = subscription.streamId();
logger.logSubscriptionRemoval(
channelEndpoint.originalUriString(), subscription.streamId(), subscription.registrationId());
subscriptions.remove(i);
subscription.close();
if (0 == channelEndpoint.decRefToStream(subscription.streamId()))
{
receiverProxy.removeSubscription(channelEndpoint, streamId);
}
if (channelEndpoint.streamCount() == 0)
{
receiveChannelEndpointByChannelMap.remove(channelEndpoint.udpChannel().canonicalForm());
receiverProxy.closeReceiveChannelEndpoint(channelEndpoint);
}
}
}
}
private void onCheckConnections(final long now)
{
final ArrayList<NetworkConnection> connections = this.connections;
for (int i = connections.size() - 1; i >= 0; i--)
{
final NetworkConnection conn = connections.get(i);
switch (conn.status())
{
case INACTIVE:
if (conn.isDrained() || now > (conn.timeOfLastStatusChange() + CONNECTION_LIVENESS_TIMEOUT_NS))
{
conn.status(NetworkConnection.Status.LINGER);
clientProxy.onInactiveConnection(
conn.correlationId(),
conn.sessionId(),
conn.streamId(),
conn.rebuildPosition(),
conn.channelUriString());
}
break;
case LINGER:
if (now > (conn.timeOfLastStatusChange() + CONNECTION_LIVENESS_TIMEOUT_NS))
{
logger.logConnectionRemoval(conn.channelUriString(), conn.sessionId(), conn.streamId());
connections.remove(i);
conn.close();
}
break;
}
}
}
private void onCheckClients(final long now)
{
for (int i = clients.size() - 1; i >= 0; i--)
{
final AeronClient client = clients.get(i);
if (now > (client.timeOfLastKeepalive() + CONNECTION_LIVENESS_TIMEOUT_NS))
{
clients.remove(i);
}
}
}
private void onDriverConductorCmd(final DriverConductorCmd cmd)
{
cmd.execute(this);
}
private AeronClient getOrAddClient(final long clientId)
{
AeronClient client = findClient(clients, clientId);
if (null == client)
{
client = new AeronClient(clientId, clock.time());
clients.add(client);
}
return client;
}
private int allocateCounter(
final String type, final String channel, final int sessionId, final int streamId, final long correlationId)
{
return countersManager.allocate(String.format("%s: %s %x %x %x", type, channel, sessionId, streamId, correlationId));
}
private long generateCreationCorrelationId()
{
return toDriverCommands.nextCorrelationId();
}
}
| [Java]: Refactor position allocation code in conductor.
| aeron-driver/src/main/java/uk/co/real_logic/aeron/driver/DriverConductor.java | [Java]: Refactor position allocation code in conductor. |
|
Java | apache-2.0 | 93b026db9fd37d26a57d84ccfaf0b608f0affb40 | 0 | Heart2009/androidsvgdrawable-plugin,avianey/androidsvgdrawable-plugin,hgl888/androidsvgdrawable-plugin,bestwpw/androidsvgdrawable-plugin,gdky005/androidsvgdrawable-plugin | /*
* Copyright 2013, 2014 Antoine Vianey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package fr.avianey.androidsvgdrawable;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Arrays;
import java.util.Collection;
import javax.imageio.ImageIO;
import org.apache.batik.transcoder.TranscoderException;
import org.joor.Reflect;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import fr.avianey.androidsvgdrawable.suite.GenDrawableTestSuite;
import fr.avianey.androidsvgdrawable.util.TestLogger;
import fr.avianey.androidsvgdrawable.util.TestParameters;
@RunWith(Parameterized.class)
public class VisualConversionTest {
private static SvgDrawablePlugin plugin;
private static final String PATH_IN = "./target/test-classes/" + VisualConversionTest.class.getSimpleName() + "/";
private static final File PATH_OUT = new File("./target/generated-png/");
// parameters
private final String filename;
public VisualConversionTest(String filename) {
this.filename = filename;
}
@BeforeClass
public static void setup() {
PATH_OUT.mkdirs();
plugin = new SvgDrawablePlugin(new TestParameters(), new TestLogger());
}
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(
new Object[][] {
{"ic_screen_rotation-mdpi"}, // https://github.com/google/material-design-icons
{"issue_29-mdpi"} // https://github.com/avianey/androidsvgdrawable-plugin/issues/29
}
);
}
@Test
public void test() throws MalformedURLException, IOException, TranscoderException, InstantiationException, IllegalAccessException {
// verify bounds
QualifiedResource svg = QualifiedResource.fromFile(new File(PATH_IN + filename + ".svg"));
Rectangle rect = plugin.extractSVGBounds(svg);
Assert.assertNotNull(rect);
plugin.transcode(svg, svg.getDensity(), rect, PATH_OUT, null);
BufferedImage transcoded = ImageIO.read(new FileInputStream(new File(PATH_OUT, svg.getName() + ".png")));
BufferedImage original = ImageIO.read(new FileInputStream(new File(PATH_IN + svg.getName() + ".pngtest")));
Assert.assertEquals(0, bufferedImagesEqual(transcoded, original), 0.1);
}
private static double bufferedImagesEqual(BufferedImage img1, BufferedImage img2) {
if (img1.getWidth() == img2.getWidth() && img1.getHeight() == img2.getHeight()) {
double inequals = 0;
for (int x = 0; x < img1.getWidth(); x++) {
for (int y = 0; y < img1.getHeight(); y++) {
if (pixelDistance(img1.getRGB(x, y),img2.getRGB(x, y)) > 255) {
inequals++;;
}
}
}
return inequals / (img1.getWidth() * img1.getHeight());
} else {
throw new RuntimeException("Image size are not equals");
}
}
private static double pixelDistance(int argb1, int argb2) {
long dist = 0;
dist += Math.abs((long) ((argb1 & 0xFF000000) - (argb2 & 0xFF000000)) >>> 24);
dist += Math.abs((long) ((argb1 & 0x00FF0000) - (argb2 & 0x00FF0000)) >>> 16);
dist += Math.abs((long) ((argb1 & 0x0000FF00) - (argb2 & 0x0000FF00)) >>> 8);
dist += Math.abs((long) ((argb1 & 0x000000FF) - (argb2 & 0x000000FF)));
return dist;
}
}
| plugin/core/src/test/java/fr/avianey/androidsvgdrawable/VisualConversionTest.java | /*
* Copyright 2013, 2014 Antoine Vianey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package fr.avianey.androidsvgdrawable;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Arrays;
import java.util.Collection;
import javax.imageio.ImageIO;
import org.apache.batik.transcoder.TranscoderException;
import org.joor.Reflect;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import fr.avianey.androidsvgdrawable.suite.GenDrawableTestSuite;
import fr.avianey.androidsvgdrawable.util.TestLogger;
import fr.avianey.androidsvgdrawable.util.TestParameters;
@RunWith(Parameterized.class)
public class VisualConversionTest {
private static SvgDrawablePlugin plugin;
private static final String PATH_IN = "./target/test-classes/" + VisualConversionTest.class.getSimpleName() + "/";
private static final File PATH_OUT = new File("./target/generated-png/");
// parameters
private final String filename;
public VisualConversionTest(String filename) {
this.filename = filename;
}
@BeforeClass
public static void setup() {
PATH_OUT.mkdirs();
plugin = new SvgDrawablePlugin(new TestParameters(), new TestLogger());
}
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(
new Object[][] {
{"ic_screen_rotation-mdpi"}, // https://github.com/google/material-design-icons
{"issue_29-mdpi"} // https://github.com/avianey/androidsvgdrawable-plugin/issues/29
}
);
}
@Test
public void test() throws MalformedURLException, IOException, TranscoderException, InstantiationException, IllegalAccessException {
// verify bounds
QualifiedResource svg = QualifiedResource.fromFile(new File(PATH_IN + filename + ".svg"));
Rectangle rect = plugin.extractSVGBounds(svg);
Assert.assertNotNull(rect);
plugin.transcode(svg, svg.getDensity(), rect, PATH_OUT, null);
BufferedImage transcoded = ImageIO.read(new FileInputStream(new File(PATH_OUT, svg.getName() + ".png")));
BufferedImage original = ImageIO.read(new FileInputStream(new File(PATH_IN + svg.getName() + ".pngtest")));
Assert.assertTrue(bufferedImagesEqual(transcoded, original));
}
private static boolean bufferedImagesEqual(BufferedImage img1, BufferedImage img2) {
if (img1.getWidth() == img2.getWidth() && img1.getHeight() == img2.getHeight()) {
double inequals = 0;
for (int x = 0; x < img1.getWidth(); x++) {
for (int y = 0; y < img1.getHeight(); y++) {
if (img1.getRGB(x, y) != img2.getRGB(x, y)) {
inequals++;;
}
}
}
// inequals if diff < 1%
return inequals / (img1.getWidth() * img1.getHeight()) < .01;
} else {
return false;
}
}
}
| Fix test with oracle jdk (done)
| plugin/core/src/test/java/fr/avianey/androidsvgdrawable/VisualConversionTest.java | Fix test with oracle jdk (done) |
|
Java | apache-2.0 | 92f65dd3bfcc667e8cfc50a6b4ac7f935bc84d90 | 0 | powertac/powertac-core | /*
* Copyright (c) 2011 - 2014 by John Collins
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.powertac.common;
import java.util.Map;
import java.util.TreeSet;
import org.powertac.common.state.StateChange;
import org.apache.commons.configuration.MapConfiguration;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.Instant;
import org.joda.time.base.AbstractDateTime;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
/**
* This is the simulation time-keeper and event queue. Here's how it works:
* <ul>
* <li>You create it with four parameters: (base, start, rate, modulo), defined as
* <ul>
* <li><strong>base</strong> is the start time of the simulation scenario. So if we
* are simulating a period in the summer of 2007, base might be 2007-06-21-12:00.</li>
* <li><strong>start</strong> is the start time of the simulation run.</li>
* <li><strong>rate</strong> is the time-compression ratio for the simulation. So if we are
* running one-hour timeslots every 5 seconds, the rate would be 720.</li>
* <li><strong>modulo</strong> controls the values of simulation time values reported. If
* we are running one-hour timeslots, then the modulo should be one hour, expressed
* in milliseconds. If we are running one-hour timeslots but want to update time every
* 30 minutes of simulated time, then the modulo would be 30*60*1000. Note that
* this will not work correctly unless the calls to updateTime() are made at
* modulo/rate intervals. Also note that the reported time is computed as
* rawTime - rawTime % modulo, which means it will never be ahead of the raw
* simulation time.</li>
* </ul></li>
* <li>Some process periodically calls updateTime(), at least once every simulated hour. This
* sets the currentTime property to the correct scenario time as<br/>
* <code>currentTime = base + (systemTime - start) * rate</code><br/>
* and runs any simulation actions that are due.</li>
* <li>If you want something to happen sometime in the future, you add an action by
* calling addAction(time, action). Assuming time is not in the past, then the action
* (a closure with a single argument, the current time) is added to a time-ordered queue,
* and will be run when its time arrives.</li>
* </ul>
* Note that all times are absolute times represented as UTC; timezone offset is 0, and there
* is no "daylight-saving" time. If we want to represent the effects of DST, we'll have to have
* our customers wake up earlier in the summertime.
* @author John Collins
*/
@Scope("singleton")
@Service
public class TimeService
{
static private Logger log = Logger.getLogger(TimeService.class.getName());
public static final long SECOND = 1000l;
public static final long MINUTE = SECOND * 60;
public static final long HOUR = MINUTE * 60;
public static final long DAY = HOUR * 24;
public static final long WEEK = DAY * 7;
// simulation clock parameters
private long base;
private long start = new DateTime(2036, 12, 31, 23, 59, 0, 0, DateTimeZone.UTC).getMillis();
private long rate = 720l;
private long modulo = HOUR;
// busy flag, to prevent overlap
private boolean busy = false;
// simulation action queue
private TreeSet<SimulationAction> actions;
// the current time
private Instant currentTime;
private DateTime currentDateTime;
// debug code -- keep track of TimeService instances
private static TimeService instance;
private static int index = 0;
private int id;
/**
* Default constructor. You need to set base, rate, start, and modulo before using it.
*/
public TimeService ()
{
super();
id = index++;
instance = this;
}
/**
* Returns the most-recently created instance of TimeService. Intended
* to be used only for testing in Spring-free environment. Note that this
* is not a Singleton-type instance getter - it will not create an instance.
*/
public static TimeService getInstance ()
{
return instance;
}
/**
* Handy constructor for testing
*/
public TimeService (long base, long start, long rate, long modulo)
{
super();
this.base = base;
this.start = start;
this.rate = rate;
this.modulo = modulo;
id = index++;
}
/**
* Sets current time to modulo before the desired start time.
* This allows scheduling
* of actions to take place on the first tick, which should be at the
* desired start time. Call this after setting clock parameters.
*/
public void init (Instant start)
{
currentTime = new Instant(start.getMillis() - modulo);
currentDateTime = new DateTime(currentTime, DateTimeZone.UTC);
DateTimeZone.setDefault(DateTimeZone.UTC);
}
/**
* Updates simulation time when called as specified by clock
* parameters, then runs any actions that may be due.
*/
public void updateTime ()
{
if (busy) {
//log.info "Timer busy";
start += HOUR / rate;
return;
}
busy = true;
setCurrentTime();
runActions();
busy = false;
}
/**
* Returns the most recent Instant at which time % modulo was zero
*/
public Instant truncateInstant (Instant time, long mod)
{
long ms = time.getMillis();
return new Instant(ms - ms % mod);
}
/**
* Sets base, rate, and modulo clock parameters with a single call. We
* do not set start at this point, because it is changed whenever the clock
* is paused and therefore needs to be treated separately.
*/
public void setClockParameters (long base, long rate, long modulo)
{
this.base = base;
this.rate = rate;
this.modulo = modulo;
}
/**
* Sets base, rate, and modulo parameters from a map, which is wrapped
* in a Configuration to allow for conversions and default values. The
* map must contain entries named "base", "rate", and "modulo". We also init
* the clock here, because we have all the parameters.
*/
public void setClockParameters (Map<String, Long> params)
{
MapConfiguration config = new MapConfiguration(params);
this.base = config.getLong("base", base);
this.rate = config.getLong("rate", rate);
this.modulo = config.getLong("modulo", modulo);
}
/**
* Sets base, rate, and modulo from a Competition instance
*/
public void setClockParameters (Competition comp)
{
setClockParameters(comp.getClockParameters());
}
public long getBase ()
{
return base;
}
public Instant getBaseInstant ()
{
return new Instant(base);
}
/**
* @deprecated use {@link setClockParameters} instead
*/
@Deprecated
public void setBase (long value)
{
base = value;
}
public long getStart ()
{
return start;
}
public void setStart (long start)
{
this.start = start;
//setCurrentTime();
}
public long getRate ()
{
return rate;
}
/**
* @deprecated use {@link setClockParameters} instead
*/
@Deprecated
public void setRate (long value)
{
rate = value;
}
public long getModulo ()
{
return modulo;
}
/**
* @deprecated use {@link setClockParameters} instead
*/
@Deprecated
public void setModulo (long value)
{
modulo = value;
}
/**
* Returns the current time as an Instant
*/
public Instant getCurrentTime()
{
return currentTime;
}
public DateTime getCurrentDateTime()
{
return currentDateTime;
}
/**
* Returns the current hour-of-day
*/
public int getHourOfDay()
{
return currentDateTime.getHourOfDay();
}
/**
* Sets current time to a specific value. Intended for testing purposes only.
*/
@StateChange
public void setCurrentTime (Instant time)
{
log.debug("ts" + id + " setCurrentTime to " + time.toString());
currentTime = time;
currentDateTime = new DateTime(time, DateTimeZone.UTC);
}
/**
* Computes and returns the offset in msec between the current system time
* and the current clock time.
*/
public long getOffset ()
{
long systemTime = new Instant().getMillis();
long simTime = (currentTime.getMillis() - base) / rate + start;
return systemTime - simTime;
}
/**
* Sets current time to a specific value. Intended for testing purposes only.
*/
@StateChange
protected void setCurrentTime (AbstractDateTime time)
{
log.debug("ts" + id + " setCurrentTime to " + time.toString());
setCurrentTime(new Instant(time));
//currentTime = new Instant(time);
//currentDateTime = new DateTime(time, DateTimeZone.UTC);
}
public void setCurrentTime ()
{
long systemTime = new Instant().getMillis();
if (systemTime >= start) {
long raw = base + (systemTime - start) * rate;
//currentTime = new Instant(raw - raw % modulo);
//currentDateTime = new DateTime(currentTime, DateTimeZone.UTC);
log.debug("ts" + id + " updateTime: sys=" + systemTime +
", simTime=" + currentTime);
setCurrentTime(new Instant(raw - raw % modulo));
}
}
/**
* Adds an action to the simulation queue, to be triggered at the specified time.
*/
public void addAction (Instant time, TimedAction act)
{
if (actions == null)
actions = new TreeSet<SimulationAction>();
actions.add(new SimulationAction(time, act));
}
/**
* Runs any actions that are due at the current simulated time.
*/
void runActions ()
{
if (actions == null)
return;
while (!actions.isEmpty() && !actions.first().atTime.isAfter(currentTime)) {
SimulationAction act = actions.first();
act.action.perform(currentTime);
actions.remove(act);
}
}
class SimulationAction implements Comparable<SimulationAction>
{
public Instant atTime;
TimedAction action;
public SimulationAction (Instant time, TimedAction action)
{
this.atTime = time;
this.action = action;
}
@Override
public int compareTo (SimulationAction obj)
{
return atTime.compareTo(((SimulationAction)obj).atTime);
}
}
}
| src/main/java/org/powertac/common/TimeService.java | /*
* Copyright (c) 2011 - 2014 by John Collins
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.powertac.common;
import java.util.Map;
import java.util.TreeSet;
import org.powertac.common.state.StateChange;
import org.apache.commons.configuration.MapConfiguration;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.Instant;
import org.joda.time.base.AbstractDateTime;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
/**
* This is the simulation time-keeper and event queue. Here's how it works:
* <ul>
* <li>You create it with four parameters: (base, start, rate, modulo), defined as
* <ul>
* <li><strong>base</strong> is the start time of the simulation scenario. So if we
* are simulating a period in the summer of 2007, base might be 2007-06-21-12:00.</li>
* <li><strong>start</strong> is the start time of the simulation run.</li>
* <li><strong>rate</strong> is the time-compression ratio for the simulation. So if we are
* running one-hour timeslots every 5 seconds, the rate would be 720.</li>
* <li><strong>modulo</strong> controls the values of simulation time values reported. If
* we are running one-hour timeslots, then the modulo should be one hour, expressed
* in milliseconds. If we are running one-hour timeslots but want to update time every
* 30 minutes of simulated time, then the modulo would be 30*60*1000. Note that
* this will not work correctly unless the calls to updateTime() are made at
* modulo/rate intervals. Also note that the reported time is computed as
* rawTime - rawTime % modulo, which means it will never be ahead of the raw
* simulation time.</li>
* </ul></li>
* <li>Some process periodically calls updateTime(), at least once every simulated hour. This
* sets the currentTime property to the correct scenario time as<br/>
* <code>currentTime = base + (systemTime - start) * rate</code><br/>
* and runs any simulation actions that are due.</li>
* <li>If you want something to happen sometime in the future, you add an action by
* calling addAction(time, action). Assuming time is not in the past, then the action
* (a closure with a single argument, the current time) is added to a time-ordered queue,
* and will be run when its time arrives.</li>
* </ul>
* Note that all times are absolute times represented as UTC; timezone offset is 0, and there
* is no "daylight-saving" time. If we want to represent the effects of DST, we'll have to have
* our customers wake up earlier in the summertime.
* @author John Collins
*/
@Scope("singleton")
@Service
public class TimeService
{
static private Logger log = Logger.getLogger(TimeService.class.getName());
public static final long SECOND = 1000l;
public static final long MINUTE = SECOND * 60;
public static final long HOUR = MINUTE * 60;
public static final long DAY = HOUR * 24;
public static final long WEEK = DAY * 7;
// simulation clock parameters
private long base;
private long start = new DateTime(2036, 12, 31, 23, 59, 0, 0, DateTimeZone.UTC).getMillis();
private long rate = 720l;
private long modulo = HOUR;
// busy flag, to prevent overlap
private boolean busy = false;
// simulation action queue
private TreeSet<SimulationAction> actions;
// the current time
private Instant currentTime;
private DateTime currentDateTime;
// debug code -- keep track of TimeService instances
private static TimeService instance;
private static int index = 0;
private int id;
/**
* Default constructor. You need to set base, rate, start, and modulo before using it.
*/
public TimeService ()
{
super();
id = index++;
instance = this;
}
/**
* Returns the most-recently created instance of TimeService. Intended
* to be used only for testing in Spring-free environment. Note that this
* is not a Singleton-type instance getter - it will not create an instance.
*/
public static TimeService getInstance ()
{
return instance;
}
/**
* Handy constructor for testing
*/
public TimeService (long base, long start, long rate, long modulo)
{
super();
this.base = base;
this.start = start;
this.rate = rate;
this.modulo = modulo;
id = index++;
}
/**
* Sets current time to modulo before the desired start time.
* This allows scheduling
* of actions to take place on the first tick, which should be at the
* desired start time. Call this after setting clock parameters.
*/
public void init (Instant start)
{
currentTime = new Instant(start.getMillis() - modulo);
currentDateTime = new DateTime(currentTime, DateTimeZone.UTC);
DateTimeZone.setDefault(DateTimeZone.UTC);
}
/**
* Updates simulation time when called as specified by clock
* parameters, then runs any actions that may be due.
*/
public void updateTime ()
{
if (busy) {
//log.info "Timer busy";
start += HOUR / rate;
return;
}
busy = true;
setCurrentTime();
runActions();
busy = false;
}
/**
* Returns the most recent Instant at which time % modulo was zero
*/
public Instant truncateInstant (Instant time, long mod)
{
long ms = time.getMillis();
return new Instant(ms - ms % mod);
}
/**
* Sets base, rate, and modulo clock parameters with a single call. We
* do not set start at this point, because it is changed whenever the clock
* is paused and therefore needs to be treated separately.
*/
public void setClockParameters (long base, long rate, long modulo)
{
this.base = base;
this.rate = rate;
this.modulo = modulo;
}
/**
* Sets base, rate, and modulo parameters from a map, which is wrapped
* in a Configuration to allow for conversions and default values. The
* map must contain entries named "base", "rate", and "modulo". We also init
* the clock here, because we have all the parameters.
*/
public void setClockParameters (Map<String, Long> params)
{
MapConfiguration config = new MapConfiguration(params);
this.base = config.getLong("base", base);
this.rate = config.getLong("rate", rate);
this.modulo = config.getLong("modulo", modulo);
}
/**
* Sets base, rate, and modulo from a Competition instance
*/
public void setClockParameters (Competition comp)
{
setClockParameters(comp.getClockParameters());
}
public long getBase ()
{
return base;
}
public Instant getBaseInstant ()
{
return new Instant(base);
}
/**
* @deprecated use {@link setClockParameters} instead
*/
@Deprecated
public void setBase (long value)
{
base = value;
}
public long getStart ()
{
return start;
}
public void setStart (long start)
{
this.start = start;
//setCurrentTime();
}
public long getRate ()
{
return rate;
}
/**
* @deprecated use {@link setClockParameters} instead
*/
@Deprecated
public void setRate (long value)
{
rate = value;
}
public long getModulo ()
{
return modulo;
}
/**
* @deprecated use {@link setClockParameters} instead
*/
@Deprecated
public void setModulo (long value)
{
modulo = value;
}
/**
* Returns the current time as an Instant
*/
public Instant getCurrentTime()
{
return currentTime;
}
public DateTime getCurrentDateTime()
{
return currentDateTime;
}
/**
* Returns the current hour-of-day
*/
public int getHourOfDay()
{
return currentDateTime.getHourOfDay();
}
/**
* Sets current time to a specific value. Intended for testing purposes only.
*/
@StateChange
public void setCurrentTime (Instant time)
{
log.debug("ts" + id + " setCurrentTime to " + time.toString());
currentTime = time;
currentDateTime = new DateTime(time, DateTimeZone.UTC);
}
/**
* Computes and returns the offset in msec between the current system time
* and the current clock time.
*/
public long getOffset ()
{
long systemTime = new Instant().getMillis();
long simTime = (currentTime.getMillis() - base) / rate + start;
return systemTime - simTime;
}
/**
* Sets current time to a specific value. Intended for testing purposes only.
*/
@StateChange
protected void setCurrentTime (AbstractDateTime time)
{
log.debug("ts" + id + " setCurrentTime to " + time.toString());
currentTime = new Instant(time);
currentDateTime = new DateTime(time, DateTimeZone.UTC);
}
public void setCurrentTime ()
{
long systemTime = new Instant().getMillis();
if (systemTime >= start) {
long raw = base + (systemTime - start) * rate;
//currentTime = new Instant(raw - raw % modulo);
//currentDateTime = new DateTime(currentTime, DateTimeZone.UTC);
log.debug("ts" + id + " updateTime: sys=" + systemTime +
", simTime=" + currentTime);
setCurrentTime(new Instant(raw - raw % modulo));
}
}
/**
* Adds an action to the simulation queue, to be triggered at the specified time.
*/
public void addAction (Instant time, TimedAction act)
{
if (actions == null)
actions = new TreeSet<SimulationAction>();
actions.add(new SimulationAction(time, act));
}
/**
* Runs any actions that are due at the current simulated time.
*/
void runActions ()
{
if (actions == null)
return;
while (!actions.isEmpty() && !actions.first().atTime.isAfter(currentTime)) {
SimulationAction act = actions.first();
act.action.perform(currentTime);
actions.remove(act);
}
}
class SimulationAction implements Comparable<SimulationAction>
{
public Instant atTime;
TimedAction action;
public SimulationAction (Instant time, TimedAction action)
{
this.atTime = time;
this.action = action;
}
@Override
public int compareTo (SimulationAction obj)
{
return atTime.compareTo(((SimulationAction)obj).atTime);
}
}
}
| minor clean up in TimeService
| src/main/java/org/powertac/common/TimeService.java | minor clean up in TimeService |
|
Java | apache-2.0 | bbbacbb7cf297e8287f71c20ffc272373faaeb08 | 0 | bsideup/groovy-core,nkhuyu/incubator-groovy,shils/incubator-groovy,jwagenleitner/incubator-groovy,tkruse/incubator-groovy,apache/incubator-groovy,pickypg/incubator-groovy,nkhuyu/incubator-groovy,fpavageau/groovy,upadhyayap/incubator-groovy,bsideup/groovy-core,sagarsane/groovy-core,i55ac/incubator-groovy,jwagenleitner/incubator-groovy,sagarsane/groovy-core,graemerocher/incubator-groovy,kidaa/incubator-groovy,armsargis/groovy,kenzanmedia/incubator-groovy,alien11689/incubator-groovy,apache/groovy,bsideup/groovy-core,rabbitcount/incubator-groovy,ChanJLee/incubator-groovy,shils/incubator-groovy,jwagenleitner/incubator-groovy,paulk-asert/groovy,rlovtangen/groovy-core,traneHead/groovy-core,kidaa/incubator-groovy,shils/groovy,paulk-asert/incubator-groovy,taoguan/incubator-groovy,aim-for-better/incubator-groovy,upadhyayap/incubator-groovy,eginez/incubator-groovy,dpolivaev/groovy,genqiang/incubator-groovy,adjohnson916/groovy-core,PascalSchumacher/incubator-groovy,aaronzirbes/incubator-groovy,paulk-asert/groovy,russel/incubator-groovy,pledbrook/incubator-groovy,samanalysis/incubator-groovy,adjohnson916/groovy-core,traneHead/groovy-core,rabbitcount/incubator-groovy,ChanJLee/incubator-groovy,avafanasiev/groovy,nkhuyu/incubator-groovy,russel/groovy,gillius/incubator-groovy,EPadronU/incubator-groovy,kidaa/incubator-groovy,sagarsane/incubator-groovy,groovy/groovy-core,ChanJLee/incubator-groovy,rabbitcount/incubator-groovy,paulk-asert/incubator-groovy,ebourg/incubator-groovy,i55ac/incubator-groovy,tkruse/incubator-groovy,ebourg/groovy-core,christoph-frick/groovy-core,pickypg/incubator-groovy,pledbrook/incubator-groovy,adjohnson916/incubator-groovy,ebourg/incubator-groovy,yukangguo/incubator-groovy,ebourg/groovy-core,dpolivaev/groovy,ChanJLee/incubator-groovy,russel/incubator-groovy,kidaa/incubator-groovy,jwagenleitner/groovy,guangying945/incubator-groovy,avafanasiev/groovy,kenzanmedia/incubator-groovy,armsargis/groovy,paplorinc/incubator-groovy,paulk-asert/groovy,nkhuyu/incubator-groovy,bsideup/incubator-groovy,i55ac/incubator-groovy,sagarsane/groovy-core,christoph-frick/groovy-core,shils/incubator-groovy,shils/groovy,paulk-asert/incubator-groovy,yukangguo/incubator-groovy,bsideup/incubator-groovy,fpavageau/groovy,apache/incubator-groovy,groovy/groovy-core,rlovtangen/groovy-core,paplorinc/incubator-groovy,traneHead/groovy-core,mariogarcia/groovy-core,eginez/incubator-groovy,paplorinc/incubator-groovy,ebourg/groovy-core,dpolivaev/groovy,aim-for-better/incubator-groovy,apache/groovy,gillius/incubator-groovy,mariogarcia/groovy-core,christoph-frick/groovy-core,gillius/incubator-groovy,dpolivaev/groovy,fpavageau/groovy,bsideup/incubator-groovy,PascalSchumacher/incubator-groovy,samanalysis/incubator-groovy,EPadronU/incubator-groovy,antoaravinth/incubator-groovy,russel/incubator-groovy,sagarsane/groovy-core,eginez/incubator-groovy,PascalSchumacher/incubator-groovy,jwagenleitner/groovy,aim-for-better/incubator-groovy,russel/groovy,nobeans/incubator-groovy,nobeans/incubator-groovy,guangying945/incubator-groovy,alien11689/groovy-core,alien11689/incubator-groovy,jwagenleitner/groovy,EPadronU/incubator-groovy,mariogarcia/groovy-core,russel/groovy,antoaravinth/incubator-groovy,taoguan/incubator-groovy,groovy/groovy-core,avafanasiev/groovy,guangying945/incubator-groovy,PascalSchumacher/incubator-groovy,graemerocher/incubator-groovy,bsideup/groovy-core,jwagenleitner/incubator-groovy,aaronzirbes/incubator-groovy,armsargis/groovy,armsargis/groovy,apache/incubator-groovy,yukangguo/incubator-groovy,antoaravinth/incubator-groovy,PascalSchumacher/incubator-groovy,paulk-asert/groovy,christoph-frick/groovy-core,kenzanmedia/incubator-groovy,alien11689/incubator-groovy,yukangguo/incubator-groovy,aim-for-better/incubator-groovy,genqiang/incubator-groovy,alien11689/groovy-core,rlovtangen/groovy-core,mariogarcia/groovy-core,pledbrook/incubator-groovy,eginez/incubator-groovy,fpavageau/groovy,adjohnson916/incubator-groovy,graemerocher/incubator-groovy,ebourg/groovy-core,rabbitcount/incubator-groovy,taoguan/incubator-groovy,guangying945/incubator-groovy,tkruse/incubator-groovy,adjohnson916/groovy-core,sagarsane/incubator-groovy,sagarsane/incubator-groovy,genqiang/incubator-groovy,nobeans/incubator-groovy,sagarsane/incubator-groovy,samanalysis/incubator-groovy,adjohnson916/groovy-core,jwagenleitner/groovy,groovy/groovy-core,alien11689/groovy-core,alien11689/groovy-core,ebourg/incubator-groovy,paulk-asert/incubator-groovy,tkruse/incubator-groovy,shils/groovy,adjohnson916/groovy-core,alien11689/incubator-groovy,adjohnson916/incubator-groovy,ebourg/incubator-groovy,apache/groovy,EPadronU/incubator-groovy,taoguan/incubator-groovy,shils/groovy,antoaravinth/incubator-groovy,samanalysis/incubator-groovy,russel/groovy,sagarsane/groovy-core,aaronzirbes/incubator-groovy,paulk-asert/incubator-groovy,nobeans/incubator-groovy,christoph-frick/groovy-core,apache/groovy,ebourg/groovy-core,upadhyayap/incubator-groovy,kenzanmedia/incubator-groovy,shils/incubator-groovy,gillius/incubator-groovy,rlovtangen/groovy-core,adjohnson916/incubator-groovy,bsideup/incubator-groovy,pickypg/incubator-groovy,pickypg/incubator-groovy,i55ac/incubator-groovy,mariogarcia/groovy-core,traneHead/groovy-core,graemerocher/incubator-groovy,avafanasiev/groovy,apache/incubator-groovy,russel/incubator-groovy,genqiang/incubator-groovy,paplorinc/incubator-groovy,upadhyayap/incubator-groovy,rlovtangen/groovy-core,pledbrook/incubator-groovy,aaronzirbes/incubator-groovy,alien11689/groovy-core,groovy/groovy-core | /*
* Copyright 2003-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.groovy.transform;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.regex.Matcher;
import org.codehaus.groovy.ast.*;
import org.codehaus.groovy.ast.expr.*;
import org.codehaus.groovy.classgen.asm.InvocationWriter;
import org.codehaus.groovy.control.*;
import static org.codehaus.groovy.ast.ClassHelper.*;
import static org.codehaus.groovy.syntax.Types.*;
import static org.codehaus.groovy.ast.tools.WideningCategories.*;
/**
* Handles the implementation of the @StaticTypes transformation
* @author <a href="mailto:[email protected]">Jochen "blackdrag" Theodorou</a>
*/
@GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION)
public class StaticTypesTransformation implements ASTTransformation {
// @Override
public void visit(ASTNode[] nodes, SourceUnit source) {
// AnnotationNode annotationInformation = (AnnotationNode) nodes[0];
AnnotatedNode node = (AnnotatedNode) nodes[1];
Visitor visitor = new Visitor(source, (ClassNode) node);
if (node instanceof ClassNode) {
visitor.visitClass((ClassNode) node);
} else {
node.visit(visitor);
}
}
public final static class StaticTypesMarker{}
private static class Visitor extends ClassCodeVisitorSupport {
private final static ClassNode
Collection_TYPE = makeWithoutCaching(Collection.class),
Number_TYPE = makeWithoutCaching(Number.class),
Matcher_TYPE = makeWithoutCaching(Matcher.class),
ArrayList_TYPE = makeWithoutCaching(ArrayList.class);
private SourceUnit source;
private ClassNode classNode;
public Visitor(SourceUnit source, ClassNode cn){
this.source = source;
this.classNode = cn;
}
// @Override
protected SourceUnit getSourceUnit() {
return source;
}
@Override
public void visitVariableExpression(VariableExpression vexp) {
super.visitVariableExpression(vexp);
if ( vexp!=VariableExpression.THIS_EXPRESSION &&
vexp!=VariableExpression.SUPER_EXPRESSION)
{
if (vexp.getName().equals("this")) storeType(vexp, classNode);
if (vexp.getName().equals("super")) storeType(vexp, classNode.getSuperClass());
}
}
@Override
public void visitBinaryExpression(BinaryExpression expression) {
super.visitBinaryExpression(expression);
ClassNode lType = getType(expression.getLeftExpression(), classNode);
ClassNode rType = getType(expression.getRightExpression(), classNode);
int op = expression.getOperation().getType();
ClassNode resultType = getResultType(lType, op, rType, expression);
if (resultType==null) {
addError("tbd...", expression);
resultType = lType;
}
storeType(expression, resultType);
if (!isAssignment(op)) return;
checkCompatibleAssignmenTypes(lType,resultType,expression);
}
@Override
public void visitBitwiseNegationExpression(BitwiseNegationExpression expression) {
super.visitBitwiseNegationExpression(expression);
ClassNode type = getType(expression, classNode);
ClassNode typeRe = type.redirect();
ClassNode resultType;
if (isBigIntCategory(typeRe)) {
// allow any internal number that is not a floating point one
resultType = type;
} else if (typeRe==STRING_TYPE || typeRe==GSTRING_TYPE) {
resultType = PATTERN_TYPE;
} else if (typeRe==ArrayList_TYPE) {
resultType = ArrayList_TYPE;
} else {
MethodNode mn = findMethodOrFail(expression, type, "bitwiseNegate");
resultType = mn.getReturnType();
}
storeType(expression, resultType);
}
@Override
public void visitUnaryPlusExpression(UnaryPlusExpression expression) {
super.visitUnaryPlusExpression(expression);
negativeOrPositiveUnary(expression, "positive");
}
@Override
public void visitUnaryMinusExpression(UnaryMinusExpression expression) {
super.visitUnaryMinusExpression(expression);
negativeOrPositiveUnary(expression, "negative");
}
private void negativeOrPositiveUnary(Expression expression, String name) {
ClassNode type = getType(expression, classNode);
ClassNode typeRe = type.redirect();
ClassNode resultType;
if (isBigDecCategory(typeRe)) {
resultType = type;
} else if (typeRe==ArrayList_TYPE) {
resultType = ArrayList_TYPE;
} else {
MethodNode mn = findMethodOrFail(expression, type, name);
resultType = mn.getReturnType();
}
storeType(expression, resultType);
}
@Override
public void visitConstructorCallExpression(ConstructorCallExpression call) {
super.visitConstructorCallExpression(call);
ClassNode[] args = getArgumentTypes(InvocationWriter.makeArgumentList(call.getArguments()), classNode);
findMethodOrFail(call, classNode, "init", args);
}
private static ClassNode[] getArgumentTypes(ArgumentListExpression args, ClassNode current) {
List<Expression> arglist = args.getExpressions();
ClassNode[] ret = new ClassNode[arglist.size()];
int i=0;
for (Expression exp : arglist) {
ret[i] = getType(exp, current);
i++;
}
return ret;
}
@Override
public void visitMethodCallExpression(MethodCallExpression call) {
super.visitMethodCallExpression(call);
if (call.getMethodAsString()==null) {
addError("cannot resolve dynamic method name at compile time.", call.getMethod());
} else {
ClassNode[] args = getArgumentTypes(InvocationWriter.makeArgumentList(call.getArguments()), classNode);
MethodNode mn = findMethodOrFail(call, getType(call.getObjectExpression(), classNode), call.getMethodAsString(), args);
if (mn==null) return;
storeType(call, mn.getReturnType());
}
}
private void storeType(Expression exp, ClassNode cn) {
exp.setNodeMetaData(StaticTypesMarker.class, cn);
}
private ClassNode getResultType(ClassNode left, int op, ClassNode right, BinaryExpression expr) {
ClassNode leftRedirect = left.redirect();
ClassNode rightRedirect = right.redirect();
if (op==ASSIGN) {
checkCompatibleAssignmenTypes(leftRedirect,rightRedirect,expr);
// we don't check the other assignments here, because
// we need first to check the operation itself.
// assignment return type is lhs type
return left;
} else if (isBoolIntrinsicOp(op)) {
return boolean_TYPE;
} else if (isArrayOp(op)) {
//TODO: do getAt and setAt
} else if (op==FIND_REGEX) {
// this case always succeeds the result is a Matcher
return Matcher_TYPE;
}
// the left operand is determining the result of the operation
// for primitives and their wrapper we use a fixed table here
else if (isNumberType(leftRedirect) && isNumberType(rightRedirect)) {
if (isOperationInGroup(op)) {
if (isIntCategory(leftRedirect) && isIntCategory(rightRedirect)) return int_TYPE;
if (isLongCategory(leftRedirect) && isLongCategory(rightRedirect)) return Long_TYPE;
if (isBigIntCategory(leftRedirect) && isBigIntCategory(rightRedirect)) return BigInteger_TYPE;
if (isBigDecCategory(leftRedirect) && isBigDecCategory(rightRedirect)) return BigDecimal_TYPE;
if (isDoubleCategory(leftRedirect) && isDoubleCategory(rightRedirect)) return double_TYPE;
} else if (isPowerOperator(op)) {
return Number_TYPE;
} else if (isBitOperator(op)) {
if (isIntCategory(leftRedirect) && isIntCategory(rightRedirect)) return int_TYPE;
if (isLongCategory(leftRedirect) && isLongCategory(rightRedirect)) return Long_TYPE;
if (isBigIntCategory(leftRedirect) && isBigIntCategory(rightRedirect)) return BigInteger_TYPE;
}
}
// try to find a method for the operation
String operationName = getOperationName(op);
MethodNode method = findMethodOrFail(expr, leftRedirect, operationName, leftRedirect, rightRedirect);
if (method!=null) {
if (isCompareToBoolean(op)) return boolean_TYPE;
if (op==COMPARE_TO) return int_TYPE;
return method.getReturnType();
}
//TODO: other cases
return null;
}
private MethodNode findMethodOrFail(
Expression expr,
ClassNode receiver, String name, ClassNode... args)
{
List<MethodNode> methods = receiver.getMethods(name);
for (MethodNode m : methods) {
// we return the first method that may match
// we don't need the exact match here for now
Parameter[] params = m.getParameters();
if (params.length == args.length) {
if ( allParametersAndArgumentsMatch(params,args) ||
lastArgMatchesVarg(params,args))
{
return m;
}
} else if (isVargs(params)) {
// there are three case for vargs
// (1) varg part is left out
if (params.length == args.length+1) return m;
// (2) last argument is put in the vargs array
// that case is handled above already
// (3) there is more than one argument for the vargs array
if ( params.length < args.length &&
excessArgumentsMatchesVargsParameter(params,args))
{
return m;
}
}
}
addError("Cannot find matching method "+name,expr);
return null;
}
private static boolean allParametersAndArgumentsMatch(Parameter[] params, ClassNode[] args) {
// we already know the lengths are equal
for (int i=0; i<params.length; i++) {
if (!isAssignableTo(params[i].getType(), args[i])) return false;
}
return true;
}
private static boolean excessArgumentsMatchesVargsParameter(Parameter[] params, ClassNode[] args) {
// we already know parameter length is bigger zero and last is a vargs
// the excess arguments are all put in an array for the vargs call
// so check against the component type
ClassNode vargsBase = params[params.length-1].getType().getComponentType();
for (int i=params.length; i<args.length; i++) {
if (!isAssignableTo(vargsBase, args[i])) return false;
}
return true;
}
private static boolean lastArgMatchesVarg(Parameter[] params, ClassNode... args) {
if (!isVargs(params)) return false;
// case length ==0 handled already
// we have now two cases,
// the argument is wrapped in the vargs array or
// the argument is an array that can be used for the vargs part directly
// we test only the wrapping part, since the non wrapping is done already
ClassNode ptype=params[params.length-1].getType().getComponentType();
ClassNode arg = args[args.length-1];
return isAssignableTo(ptype,arg);
}
private static boolean isAssignableTo(ClassNode toBeAssignedTo, ClassNode type) {
if (toBeAssignedTo.isDerivedFrom(type)) return true;
if (toBeAssignedTo.redirect()==STRING_TYPE && type.redirect()==GSTRING_TYPE) {
return true;
}
toBeAssignedTo = getWrapper(toBeAssignedTo);
type = getWrapper(type);
if ( toBeAssignedTo.isDerivedFrom(Number_TYPE) &&
type.isDerivedFrom(Number_TYPE))
{
return true;
}
if (toBeAssignedTo.isInterface() && type.implementsInterface(toBeAssignedTo)) {
return true;
}
return false;
}
private static boolean isVargs(Parameter[] params) {
if (params.length==0) return false;
if (params[params.length-1].getType().isArray()) return true;
return false;
}
private static boolean isCompareToBoolean(int op) {
return op==COMPARE_GREATER_THAN ||
op==COMPARE_GREATER_THAN_EQUAL ||
op==COMPARE_LESS_THAN ||
op==COMPARE_LESS_THAN_EQUAL;
}
private static boolean isArrayOp(int op) {
return op==LEFT_SQUARE_BRACKET;
}
private static boolean isBoolIntrinsicOp(int op) {
return op==LOGICAL_AND || op==LOGICAL_OR ||
op==MATCH_REGEX || op==KEYWORD_INSTANCEOF;
}
private static boolean isPowerOperator(int op) {
return op==POWER || op==POWER_EQUAL;
}
/**
* Returns true for operations that are of the class, that given a
* common type class for left and right, the operation "left op right"
* will have a result in the same type class
* In Groovy on numbers that is +,-,* as well as their variants
* with equals.
*/
private static boolean isOperationInGroup(int op) {
switch (op) {
case PLUS: case PLUS_EQUAL:
case MINUS: case MINUS_EQUAL:
case MULTIPLY: case MULTIPLY_EQUAL:
return true;
default:
return false;
}
}
private static boolean isBitOperator(int op) {
switch (op) {
case BITWISE_OR_EQUAL: case BITWISE_OR:
case BITWISE_AND_EQUAL: case BITWISE_AND:
case BITWISE_XOR_EQUAL: case BITWISE_XOR:
return true;
default:
return false;
}
}
private static boolean isAssignment(int op) {
switch (op) {
case ASSIGN:
case LOGICAL_OR_EQUAL: case LOGICAL_AND_EQUAL:
case PLUS_EQUAL: case MINUS_EQUAL:
case MULTIPLY_EQUAL: case DIVIDE_EQUAL:
case INTDIV_EQUAL: case MOD_EQUAL:
case POWER_EQUAL:
case LEFT_SHIFT_EQUAL: case RIGHT_SHIFT_EQUAL:
case RIGHT_SHIFT_UNSIGNED_EQUAL:
case BITWISE_OR_EQUAL: case BITWISE_AND_EQUAL:
case BITWISE_XOR_EQUAL:
return true;
default: return false;
}
}
private static ClassNode getType(Expression exp, ClassNode current) {
ClassNode cn = (ClassNode) exp.getNodeMetaData(StaticTypesMarker.class);
if (cn!=null) return cn;
if (exp instanceof VariableExpression){
VariableExpression vexp = (VariableExpression) exp;
if (vexp==VariableExpression.THIS_EXPRESSION) return current;
if (vexp==VariableExpression.SUPER_EXPRESSION) return current.getSuperClass();
}
return exp.getType();
}
private void checkCompatibleAssignmenTypes(ClassNode left, ClassNode right, Expression expr) {
ClassNode leftRedirect = left.redirect();
ClassNode rightRedirect = right.redirect();
// on an assignment everything that can be done by a GroovyCast is allowed
// anything can be assigned to an Object, String, boolean, Boolean
// or Class typed variable
if ( leftRedirect==OBJECT_TYPE ||
leftRedirect==STRING_TYPE ||
leftRedirect==boolean_TYPE ||
leftRedirect==Boolean_TYPE ||
leftRedirect==CLASS_Type) {
return;
}
// if left is Enum and right is String or GString we do valueOf
if ( leftRedirect.isDerivedFrom(Enum_Type) &&
(rightRedirect==GSTRING_TYPE || rightRedirect==STRING_TYPE)) {
return;
}
// if right is array, map or collection we try invoking the
// constructor
if ( rightRedirect.implementsInterface(MAP_TYPE) ||
rightRedirect.implementsInterface(Collection_TYPE) ||
rightRedirect.isArray()) {
//TODO: in case of the array we could maybe make a partial check
return;
}
// simple check on being subclass
if (right.isDerivedFrom(left) || left.implementsInterface(right)) return;
// if left and right are primitives or numbers allow
if (isPrimitiveType(leftRedirect) && isPrimitiveType(rightRedirect)) return;
if (isNumberType(leftRedirect) && isNumberType(rightRedirect)) return;
addError("Cannot assign value of type "+right+" to variable of type "+left, expr);
}
}
private static String getOperationName(int op) {
switch (op) {
case COMPARE_EQUAL:
case COMPARE_NOT_EQUAL:
// this is only correct in this context here, normally
// we would have to compile against compareTo if available
// but since we don't compile here, this one is enough
return "equals";
case COMPARE_TO:
case COMPARE_GREATER_THAN:
case COMPARE_GREATER_THAN_EQUAL:
case COMPARE_LESS_THAN:
case COMPARE_LESS_THAN_EQUAL:
return "compareTo";
case BITWISE_AND:
case BITWISE_AND_EQUAL:
return "and";
case BITWISE_OR:
case BITWISE_OR_EQUAL:
return "or";
case BITWISE_XOR:
case BITWISE_XOR_EQUAL:
return "xor";
case PLUS:
case PLUS_EQUAL:
return "plus";
case MINUS:
case MINUS_EQUAL:
return "minus";
case MULTIPLY:
case MULTIPLY_EQUAL:
return "multiply";
case DIVIDE:
case DIVIDE_EQUAL:
return "div";
case INTDIV:
case INTDIV_EQUAL:
return "intdiv";
case MOD:
case MOD_EQUAL:
return "mod";
case POWER:
case POWER_EQUAL:
return "power";
case LEFT_SHIFT:
case LEFT_SHIFT_EQUAL:
return "leftShift";
case RIGHT_SHIFT:
case RIGHT_SHIFT_EQUAL:
return "rightShift";
case RIGHT_SHIFT_UNSIGNED:
case RIGHT_SHIFT_UNSIGNED_EQUAL:
return "rightShiftUnsigned";
case KEYWORD_IN:
return "isCase";
default:
return null;
}
}
}
| src/main/org/codehaus/groovy/transform/StaticTypesTransformation.java | /*
* Copyright 2003-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.groovy.transform;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.regex.Matcher;
import org.codehaus.groovy.ast.*;
import org.codehaus.groovy.ast.expr.*;
import org.codehaus.groovy.classgen.asm.InvocationWriter;
import org.codehaus.groovy.control.*;
import static org.codehaus.groovy.ast.ClassHelper.*;
import static org.codehaus.groovy.syntax.Types.*;
import static org.codehaus.groovy.ast.tools.WideningCategories.*;
/**
* Handles the implementation of the @StaticTypes transformation
* @author <a href="mailto:[email protected]">Jochen "blackdrag" Theodorou</a>
*/
@GroovyASTTransformation(phase = CompilePhase.CANONICALIZATION)
public class StaticTypesTransformation implements ASTTransformation {
// @Override
public void visit(ASTNode[] nodes, SourceUnit source) {
// AnnotationNode annotationInformation = (AnnotationNode) nodes[0];
AnnotatedNode node = (AnnotatedNode) nodes[1];
Visitor visitor = new Visitor(source, (ClassNode) node);
if (node instanceof ClassNode) {
visitor.visitClass((ClassNode) node);
} else {
node.visit(visitor);
}
}
public final static class StaticTypesMarker{}
private static class Visitor extends ClassCodeVisitorSupport {
private final static ClassNode
Collection_TYPE = makeWithoutCaching(Collection.class),
Number_TYPE = makeWithoutCaching(Number.class),
Matcher_TYPE = makeWithoutCaching(Matcher.class),
ArrayList_TYPE = makeWithoutCaching(ArrayList.class);
private SourceUnit source;
private ClassNode classNode;
public Visitor(SourceUnit source, ClassNode cn){
this.source = source;
this.classNode = cn;
}
// @Override
protected SourceUnit getSourceUnit() {
return source;
}
@Override
public void visitBinaryExpression(BinaryExpression expression) {
super.visitBinaryExpression(expression);
ClassNode lType = getType(expression.getLeftExpression());
ClassNode rType = getType(expression.getRightExpression());
int op = expression.getOperation().getType();
ClassNode resultType = getResultType(lType, op, rType, expression);
if (resultType==null) {
addError("tbd...", expression);
resultType = lType;
}
storeType(expression, resultType);
if (!isAssignment(op)) return;
checkCompatibleAssignmenTypes(lType,resultType,expression);
}
@Override
public void visitBitwiseNegationExpression(BitwiseNegationExpression expression) {
super.visitBitwiseNegationExpression(expression);
ClassNode type = getType(expression);
ClassNode typeRe = type.redirect();
ClassNode resultType;
if (isBigIntCategory(typeRe)) {
// allow any internal number that is not a floating point one
resultType = type;
} else if (typeRe==STRING_TYPE || typeRe==GSTRING_TYPE) {
resultType = PATTERN_TYPE;
} else if (typeRe==ArrayList_TYPE) {
resultType = ArrayList_TYPE;
} else {
MethodNode mn = findMethodOrFail(expression, type, "bitwiseNegate");
resultType = mn.getReturnType();
}
storeType(expression, resultType);
}
@Override
public void visitUnaryPlusExpression(UnaryPlusExpression expression) {
super.visitUnaryPlusExpression(expression);
negativeOrPositiveUnary(expression, "positive");
}
@Override
public void visitUnaryMinusExpression(UnaryMinusExpression expression) {
super.visitUnaryMinusExpression(expression);
negativeOrPositiveUnary(expression, "negative");
}
private void negativeOrPositiveUnary(Expression expression, String name) {
ClassNode type = getType(expression);
ClassNode typeRe = type.redirect();
ClassNode resultType;
if (isBigDecCategory(typeRe)) {
resultType = type;
} else if (typeRe==ArrayList_TYPE) {
resultType = ArrayList_TYPE;
} else {
MethodNode mn = findMethodOrFail(expression, type, name);
resultType = mn.getReturnType();
}
storeType(expression, resultType);
}
@Override
public void visitConstructorCallExpression(ConstructorCallExpression call) {
super.visitConstructorCallExpression(call);
ClassNode[] args = getArgumentTypes(InvocationWriter.makeArgumentList(call.getArguments()));
findMethodOrFail(call, classNode, "init", args);
}
private static ClassNode[] getArgumentTypes(ArgumentListExpression args) {
List<Expression> arglist = args.getExpressions();
ClassNode[] ret = new ClassNode[arglist.size()];
int i=0;
for (Expression exp : arglist) {
ret[i] = getType(exp);
i++;
}
return ret;
}
@Override
public void visitMethodCallExpression(MethodCallExpression call) {
super.visitMethodCallExpression(call);
if (call.getMethodAsString()==null) {
addError("cannot resolve dynamic method name at compile time.", call.getMethod());
} else {
ClassNode[] args = getArgumentTypes(InvocationWriter.makeArgumentList(call.getArguments()));
MethodNode mn = findMethodOrFail(call, classNode, call.getMethodAsString(), args);
if (mn==null) return;
storeType(call, mn.getReturnType());
}
}
private void storeType(Expression exp, ClassNode cn) {
exp.setNodeMetaData(StaticTypesMarker.class, cn);
}
private ClassNode getResultType(ClassNode left, int op, ClassNode right, BinaryExpression expr) {
ClassNode leftRedirect = left.redirect();
ClassNode rightRedirect = right.redirect();
if (op==ASSIGN) {
checkCompatibleAssignmenTypes(leftRedirect,rightRedirect,expr);
// we don't check the other assignments here, because
// we need first to check the operation itself.
// assignment return type is lhs type
return left;
} else if (isBoolIntrinsicOp(op)) {
return boolean_TYPE;
} else if (isArrayOp(op)) {
//TODO: do getAt and setAt
} else if (op==FIND_REGEX) {
// this case always succeeds the result is a Matcher
return Matcher_TYPE;
}
// the left operand is determining the result of the operation
// for primitives and their wrapper we use a fixed table here
else if (isNumberType(leftRedirect) && isNumberType(rightRedirect)) {
if (isOperationInGroup(op)) {
if (isIntCategory(leftRedirect) && isIntCategory(rightRedirect)) return int_TYPE;
if (isLongCategory(leftRedirect) && isLongCategory(rightRedirect)) return Long_TYPE;
if (isBigIntCategory(leftRedirect) && isBigIntCategory(rightRedirect)) return BigInteger_TYPE;
if (isBigDecCategory(leftRedirect) && isBigDecCategory(rightRedirect)) return BigDecimal_TYPE;
if (isDoubleCategory(leftRedirect) && isDoubleCategory(rightRedirect)) return double_TYPE;
} else if (isPowerOperator(op)) {
return Number_TYPE;
} else if (isBitOperator(op)) {
if (isIntCategory(leftRedirect) && isIntCategory(rightRedirect)) return int_TYPE;
if (isLongCategory(leftRedirect) && isLongCategory(rightRedirect)) return Long_TYPE;
if (isBigIntCategory(leftRedirect) && isBigIntCategory(rightRedirect)) return BigInteger_TYPE;
}
}
// try to find a method for the operation
String operationName = getOperationName(op);
MethodNode method = findMethodOrFail(expr, leftRedirect, operationName, leftRedirect, rightRedirect);
if (method!=null) {
if (isCompareToBoolean(op)) return boolean_TYPE;
if (op==COMPARE_TO) return int_TYPE;
return method.getReturnType();
}
//TODO: other cases
return null;
}
private MethodNode findMethodOrFail(
Expression expr,
ClassNode receiver, String name, ClassNode... args)
{
List<MethodNode> methods = receiver.getMethods(name);
for (MethodNode m : methods) {
// we return the first method that may match
// we don't need the exact match here for now
Parameter[] params = m.getParameters();
if (params.length == args.length) {
if ( allParametersAndArgumentsMatch(params,args) ||
lastArgMatchesVarg(params,args))
{
return m;
}
} else if (isVargs(params)) {
// there are three case for vargs
// (1) varg part is left out
if (params.length == args.length+1) return m;
// (2) last argument is put in the vargs array
// that case is handled above already
// (3) there is more than one argument for the vargs array
if ( params.length < args.length &&
excessArgumentsMatchesVargsParameter(params,args))
{
return m;
}
}
}
addError("Cannot find matching method "+name,expr);
return null;
}
private static boolean allParametersAndArgumentsMatch(Parameter[] params, ClassNode[] args) {
// we already know the lengths are equal
for (int i=0; i<params.length; i++) {
if (!isAssignableTo(params[i].getType(), args[i])) return false;
}
return true;
}
private static boolean excessArgumentsMatchesVargsParameter(Parameter[] params, ClassNode[] args) {
// we already know parameter length is bigger zero and last is a vargs
// the excess arguments are all put in an array for the vargs call
// so check against the component type
ClassNode vargsBase = params[params.length-1].getType().getComponentType();
for (int i=params.length; i<args.length; i++) {
if (!isAssignableTo(vargsBase, args[i])) return false;
}
return true;
}
private static boolean lastArgMatchesVarg(Parameter[] params, ClassNode... args) {
if (!isVargs(params)) return false;
// case length ==0 handled already
// we have now two cases,
// the argument is wrapped in the vargs array or
// the argument is an array that can be used for the vargs part directly
// we test only the wrapping part, since the non wrapping is done already
ClassNode ptype=params[params.length-1].getType().getComponentType();
ClassNode arg = args[args.length-1];
return isAssignableTo(ptype,arg);
}
private static boolean isAssignableTo(ClassNode toBeAssignedTo, ClassNode type) {
if (toBeAssignedTo.isDerivedFrom(type)) return true;
if (toBeAssignedTo.redirect()==STRING_TYPE && type.redirect()==GSTRING_TYPE) {
return true;
}
toBeAssignedTo = getWrapper(toBeAssignedTo);
type = getWrapper(type);
if ( toBeAssignedTo.implementsInterface(Number_TYPE) &&
type.implementsInterface(Number_TYPE))
{
return true;
}
if (toBeAssignedTo.isInterface() && type.implementsInterface(toBeAssignedTo)) {
return true;
}
return false;
}
private static boolean isVargs(Parameter[] params) {
if (params.length==0) return false;
if (params[params.length-1].getType().isArray()) return true;
return false;
}
private static boolean isCompareToBoolean(int op) {
return op==COMPARE_GREATER_THAN ||
op==COMPARE_GREATER_THAN_EQUAL ||
op==COMPARE_LESS_THAN ||
op==COMPARE_LESS_THAN_EQUAL;
}
private static boolean isArrayOp(int op) {
return op==LEFT_SQUARE_BRACKET;
}
private static boolean isBoolIntrinsicOp(int op) {
return op==LOGICAL_AND || op==LOGICAL_OR ||
op==MATCH_REGEX || op==KEYWORD_INSTANCEOF;
}
private static boolean isPowerOperator(int op) {
return op==POWER || op==POWER_EQUAL;
}
/**
* Returns true for operations that are of the class, that given a
* common type class for left and right, the operation "left op right"
* will have a result in the same type class
* In Groovy on numbers that is +,-,* as well as their variants
* with equals.
*/
private static boolean isOperationInGroup(int op) {
switch (op) {
case PLUS: case PLUS_EQUAL:
case MINUS: case MINUS_EQUAL:
case MULTIPLY: case MULTIPLY_EQUAL:
return true;
default:
return false;
}
}
private static boolean isBitOperator(int op) {
switch (op) {
case BITWISE_OR_EQUAL: case BITWISE_OR:
case BITWISE_AND_EQUAL: case BITWISE_AND:
case BITWISE_XOR_EQUAL: case BITWISE_XOR:
return true;
default:
return false;
}
}
private static boolean isAssignment(int op) {
switch (op) {
case ASSIGN:
case LOGICAL_OR_EQUAL: case LOGICAL_AND_EQUAL:
case PLUS_EQUAL: case MINUS_EQUAL:
case MULTIPLY_EQUAL: case DIVIDE_EQUAL:
case INTDIV_EQUAL: case MOD_EQUAL:
case POWER_EQUAL:
case LEFT_SHIFT_EQUAL: case RIGHT_SHIFT_EQUAL:
case RIGHT_SHIFT_UNSIGNED_EQUAL:
case BITWISE_OR_EQUAL: case BITWISE_AND_EQUAL:
case BITWISE_XOR_EQUAL:
return true;
default: return false;
}
}
private static ClassNode getType(Expression exp) {
ClassNode cn = (ClassNode) exp.getNodeMetaData(StaticTypesMarker.class);
if (cn!=null) return cn;
return exp.getType();
}
private void checkCompatibleAssignmenTypes(ClassNode left, ClassNode right, Expression expr) {
ClassNode leftRedirect = left.redirect();
ClassNode rightRedirect = right.redirect();
// on an assignment everything that can be done by a GroovyCast is allowed
// anything can be assigned to an Object, String, boolean, Boolean
// or Class typed variable
if ( leftRedirect==OBJECT_TYPE ||
leftRedirect==STRING_TYPE ||
leftRedirect==boolean_TYPE ||
leftRedirect==Boolean_TYPE ||
leftRedirect==CLASS_Type) {
return;
}
// if left is Enum and right is String or GString we do valueOf
if ( leftRedirect.isDerivedFrom(Enum_Type) &&
(rightRedirect==GSTRING_TYPE || rightRedirect==STRING_TYPE)) {
return;
}
// if right is array, map or collection we try invoking the
// constructor
if ( rightRedirect.implementsInterface(MAP_TYPE) ||
rightRedirect.implementsInterface(Collection_TYPE) ||
rightRedirect.isArray()) {
//TODO: in case of the array we could maybe make a partial check
return;
}
// simple check on being subclass
if (right.isDerivedFrom(left) || left.implementsInterface(right)) return;
// if left and right are primitives or numbers allow
if (isPrimitiveType(leftRedirect) && isPrimitiveType(rightRedirect)) return;
if (isNumberType(leftRedirect) && isNumberType(rightRedirect)) return;
addError("Cannot assign value of type "+right+" to variable of type "+left, expr);
}
}
private static String getOperationName(int op) {
switch (op) {
case COMPARE_EQUAL:
case COMPARE_NOT_EQUAL:
// this is only correct in this context here, normally
// we would have to compile against compareTo if available
// but since we don't compile here, this one is enough
return "equals";
case COMPARE_TO:
case COMPARE_GREATER_THAN:
case COMPARE_GREATER_THAN_EQUAL:
case COMPARE_LESS_THAN:
case COMPARE_LESS_THAN_EQUAL:
return "compareTo";
case BITWISE_AND:
case BITWISE_AND_EQUAL:
return "and";
case BITWISE_OR:
case BITWISE_OR_EQUAL:
return "or";
case BITWISE_XOR:
case BITWISE_XOR_EQUAL:
return "xor";
case PLUS:
case PLUS_EQUAL:
return "plus";
case MINUS:
case MINUS_EQUAL:
return "minus";
case MULTIPLY:
case MULTIPLY_EQUAL:
return "multiply";
case DIVIDE:
case DIVIDE_EQUAL:
return "div";
case INTDIV:
case INTDIV_EQUAL:
return "intdiv";
case MOD:
case MOD_EQUAL:
return "mod";
case POWER:
case POWER_EQUAL:
return "power";
case LEFT_SHIFT:
case LEFT_SHIFT_EQUAL:
return "leftShift";
case RIGHT_SHIFT:
case RIGHT_SHIFT_EQUAL:
return "rightShift";
case RIGHT_SHIFT_UNSIGNED:
case RIGHT_SHIFT_UNSIGNED_EQUAL:
return "rightShiftUnsigned";
case KEYWORD_IN:
return "isCase";
default:
return null;
}
}
}
| fix method selection for grumpy a bit
| src/main/org/codehaus/groovy/transform/StaticTypesTransformation.java | fix method selection for grumpy a bit |
|
Java | apache-2.0 | b542f8fc236950ef15418464d039cfecf35cebb1 | 0 | voyagersearch/quickstart-java | package voyager.quickstart.location.earthquake;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.common.SolrInputDocument;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Matchers;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import voyager.api.domain.model.entry.DexField;
import voyager.jobs.JobSubmitterList;
public class EarthquakesLocationTest {
@Test
public void testReadIndex() throws Exception {
JobSubmitterList jobs = new JobSubmitterList();
SolrClient solr = Mockito.mock(SolrClient.class);
final List<SolrInputDocument> values = new ArrayList<>();
Mockito.when(solr.add(Matchers.any(SolrInputDocument.class))).then(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
values.add( (SolrInputDocument)invocation.getArguments()[0] );
return null;
}
});
EarthquakesLocation loc = new EarthquakesLocation();
loc.setURI(new URI("http://nothing/")); // not used
EarthquakesRunner runner = new EarthquakesRunner(loc, solr, jobs) {
@Override
protected InputStream openStream(URI uri) throws IOException
{
return EarthquakesLocationTest.class.getResourceAsStream("all_day.atom");
}
};
runner.run();
Assert.assertEquals(210, values.size());
// make sure everything has a "pointDD" field
for(SolrInputDocument doc : values) {
Assert.assertNotNull(doc.getFieldValue(DexField.GEO.name));
}
}
}
| src/test/java/voyager/quickstart/location/earthquake/EarthquakesLocationTest.java | package voyager.quickstart.location.earthquake;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.common.SolrInputDocument;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Matchers;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import voyager.api.domain.model.entry.DexField;
import voyager.jobs.JobSubmitterList;
public class EarthquakesLocationTest {
@Test
public void testReadIndex() throws Exception {
JobSubmitterList jobs = new JobSubmitterList();
SolrClient solr = Mockito.mock(SolrClient.class);
final List<SolrInputDocument> values = new ArrayList<>();
Mockito.when(solr.add(Matchers.any(SolrInputDocument.class))).then(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
values.add( (SolrInputDocument)invocation.getArguments()[0] );
return null;
}
});
EarthquakesLocation loc = new EarthquakesLocation();
loc.setURI(new URI("http://nothing/")); // not used
EarthquakesRunner runner = new EarthquakesRunner(loc, solr, jobs) {
@Override
protected InputStream openStream(URI uri) throws IOException
{
return EarthquakesLocationTest.class.getResourceAsStream("all_day.atom");
}
};
runner.run();
Assert.assertEquals(210, values.size());
// make sure everything has a "pointDD" field
for(SolrInputDocument doc : values) {
Assert.assertNotNull(doc.getFieldValue(DexField.POINT_DD.name));
}
}
}
| Replace POINT_DD with GEO
| src/test/java/voyager/quickstart/location/earthquake/EarthquakesLocationTest.java | Replace POINT_DD with GEO |
|
Java | apache-2.0 | ef5980983a791671ee9d1db974c61db2da9b64e4 | 0 | cache2k/cache2k,cache2k/cache2k,cache2k/cache2k | package org.cache2k.impl;
/*
* #%L
* cache2k core package
* %%
* Copyright (C) 2000 - 2014 headissue GmbH, Munich
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
import org.cache2k.Cache;
import org.cache2k.CacheConfig;
import org.cache2k.ClosableIterator;
import org.cache2k.StorageConfiguration;
import org.cache2k.impl.threading.Futures;
import org.cache2k.impl.threading.LimitedPooledExecutor;
import org.cache2k.impl.timer.TimerListener;
import org.cache2k.impl.timer.TimerService;
import org.cache2k.spi.SingleProviderResolver;
import org.cache2k.storage.CacheStorage;
import org.cache2k.storage.CacheStorageContext;
import org.cache2k.storage.CacheStorageProvider;
import org.cache2k.storage.FlushableStorage;
import org.cache2k.storage.MarshallerFactory;
import org.cache2k.storage.Marshallers;
import org.cache2k.storage.TransientStorageClass;
import org.cache2k.storage.PurgeableStorage;
import org.cache2k.storage.StorageEntry;
import org.cache2k.impl.util.Log;
import org.cache2k.impl.util.TunableConstants;
import org.cache2k.impl.util.TunableFactory;
import javax.annotation.Nonnull;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Passes cache operation to the storage layer. Implements common
* services for the storage layer. This class heavily interacts
* with the base cache and contains mostly everything special
* needed if a storage is defined. This means the design is not
* perfectly layered, in some cases the
* e.g. the get operation does interacts with the
* underlying storage, wheres iterate
*
* @author Jens Wilke; created: 2014-05-08
*/
@SuppressWarnings({"unchecked", "SynchronizeOnNonFinalField"})
public class PassingStorageAdapter extends StorageAdapter {
private Tunable tunable = TunableFactory.get(Tunable.class);
private BaseCache cache;
CacheStorage storage;
boolean passivation = false;
long errorCount = 0;
Set<Object> deletedKeys = null;
StorageContext context;
StorageConfiguration config;
ExecutorService executor;
long flushIntervalMillis = 0;
Object flushLock = new Object();
TimerService.CancelHandle flushTimerHandle;
@Nonnull
Future<Void> lastExecutingFlush = new Futures.FinishedFuture<>();
Object purgeRunningLock = new Object();
Log log;
StorageAdapter.Parent parent;
public PassingStorageAdapter(BaseCache _cache, CacheConfig _cacheConfig,
StorageConfiguration _storageConfig) {
cache = _cache;
parent = _cache;
context = new StorageContext(_cache);
context.keyType = _cacheConfig.getKeyType();
context.valueType = _cacheConfig.getValueType();
config = _storageConfig;
if (tunable.useManagerThreadPool) {
executor = new LimitedPooledExecutor(cache.manager.getThreadPool());
} else {
executor = Executors.newCachedThreadPool();
}
log = Log.getLog(Cache.class.getName() + ".storage/" + cache.getCompleteName());
}
/**
* By default log lifecycle operations as info.
*/
protected void logLifecycleOperation(String s) {
log.info(s);
}
public void open() {
try {
CacheStorageProvider<?> pr = (CacheStorageProvider)
SingleProviderResolver.getInstance().resolve(config.getImplementation());
storage = pr.create(context, config);
flushIntervalMillis = config.getFlushIntervalMillis();
if (!(storage instanceof FlushableStorage)) {
flushIntervalMillis = -1;
}
if (config.isPassivation() || storage instanceof TransientStorageClass) {
deletedKeys = new HashSet<>();
passivation = true;
}
logLifecycleOperation("opened, state: " + storage);
} catch (Exception ex) {
if (config.isReliable()) {
disableAndThrow("error initializing, disabled", ex);
} else {
disable("error initializing, disabled", ex);
}
}
}
/**
* Store entry on cache put. Entry must be locked, since we use the
* entry directly for handing it over to the storage, it is not
* allowed to change.
*/
public void put(BaseCache.Entry e) {
if (passivation) {
synchronized (deletedKeys) {
deletedKeys.remove(e.getKey());
}
return;
}
doPut(e);
}
private void doPut(BaseCache.Entry e) {
try {
storage.put(e);
checkStartFlushTimer();
} catch (Exception ex) {
if (config.isReliable()) {
disableAndThrow("exception in storage.put()", ex);
} else {
errorCount++;
try {
if (!storage.contains(e.getKey())) {
return;
}
storage.remove(e.getKey());
} catch (Exception ex2) {
ex.addSuppressed(ex2);
disableAndThrow("exception in storage.put(), mitigation failed, entry state unknown", ex);
}
}
}
}
public StorageEntry get(Object k) {
if (deletedKeys != null) {
synchronized (deletedKeys) {
if (deletedKeys.contains(k)) {
return null;
}
}
}
try {
return storage.get(k);
} catch (Exception ex) {
errorCount++;
if (config.isReliable()) {
throw new CacheStorageException("cache get", ex);
}
return null;
}
}
/**
* If passivation is not enabled, then we need to do nothing here since, the
* entry was transferred to the storage on the {@link #put(org.cache2k.impl.BaseCache.Entry)}
* operation. With passivation enabled, the entries need to be transferred when evicted from
* the heap.
*
* <p/>The storage operation is done in the calling thread, which should be a client thread.
* The cache client will be throttled until the I/O operation is finished. This is what we
* want in general. To decouple it, we need to implement async storage I/O support.
*/
public void evict(BaseCache.Entry e) {
if (passivation) {
putEventually(e);
}
}
/**
* An expired entry was removed from the memory cache and
* can also be removed from the storage. For the moment, this
* does nothing, since we cannot do the removal in the calling
* thread and decoupling yields bad race conditions.
* Expired entries in the storage are remove by the purge run.
*/
public void expire(BaseCache.Entry e) {
}
/**
* Store it in the storage if needed, that is if it is dirty
* or if the entry is not yet in the storage. When an off heap
* and persistent storage is aggregated, evicted entries will
* be put to the off heap storage, but not into the persistent
* storage again.
*/
private void putEventually(BaseCache.Entry e) {
if (!e.isDirty()) {
if (!(storage instanceof TransientStorageClass)) {
return;
}
try {
if (storage.contains(e.getKey())) {
return;
}
} catch (Exception ex) {
errorCount++;
disable("storage.contains(), unknown state", ex);
throw new CacheStorageException("", ex);
}
}
doPut(e);
}
public void remove(Object key) {
if (deletedKeys != null) {
synchronized (deletedKeys) {
deletedKeys.remove(key);
}
return;
}
try {
storage.remove(key);
checkStartFlushTimer();
} catch (Exception ex) {
disableAndThrow("storage.remove()", ex);
}
}
@Override
public ClosableIterator<BaseCache.Entry> iterateAll() {
final CompleteIterator it = new CompleteIterator();
if (tunable.iterationQueueCapacity > 0) {
it.queue = new ArrayBlockingQueue<>(tunable.iterationQueueCapacity);
} else {
it.queue = new SynchronousQueue<>();
}
synchronized (cache.lock) {
it.localIteration = cache.iterateAllLocalEntries();
it.localIteration.setKeepIterated(true);
it.keepHashCtrlForClearDetection = cache.mainHashCtrl;
if (!passivation) {
it.maximumEntriesToIterate = storage.getEntryCount();
} else {
it.maximumEntriesToIterate = Integer.MAX_VALUE;
}
}
it.executorForStorageCall = executor;
long now = System.currentTimeMillis();
it.runnable = new StorageVisitCallable(now, it);
return it;
}
public void purge() {
synchronized (purgeRunningLock) {
long now = System.currentTimeMillis();
PurgeableStorage.PurgeResult res;
if (storage instanceof PurgeableStorage) {
try {
PurgeableStorage.PurgeContext ctx = new MyPurgeContext();
res = ((PurgeableStorage) storage).purge(ctx, now, now);
} catch (Exception ex) {
disable("expire exception", ex);
return;
}
} else {
res = purgeByVisit(now, now);
}
if (log.isInfoEnabled()) {
long t = System.currentTimeMillis();
log.info("purge (force): " +
"runtimeMillis=" + (t - now) + ", " +
"scanned=" + res.getEntriesScanned() + ", " +
"purged=" + res.getEntriesPurged() +
(res.getBytesFreed() >=0 ? ", " + "freedBytes=" + res.getBytesFreed() : ""));
}
}
}
PurgeableStorage.PurgeResult purgeByVisit(
final long _valueExpiryTime,
final long _entryExpireTime) {
CacheStorage.EntryFilter f = new CacheStorage.EntryFilter() {
@Override
public boolean shouldInclude(Object _key) {
return true;
}
};
CacheStorage.VisitContext ctx = new BaseVisitContext() {
@Override
public boolean needMetaData() {
return true;
}
@Override
public boolean needValue() {
return false;
}
};
final AtomicInteger _scanCount = new AtomicInteger();
final AtomicInteger _purgeCount = new AtomicInteger();
CacheStorage.EntryVisitor v = new CacheStorage.EntryVisitor() {
@Override
public void visit(StorageEntry e) throws Exception {
_scanCount.incrementAndGet();
if ((e.getEntryExpiryTime() > 0 && e.getEntryExpiryTime() < _entryExpireTime) ||
(e.getValueExpiryTime() > 0 && e.getValueExpiryTime() < _valueExpiryTime)) {
storage.remove(e.getKey());
remove(e.getKey());
_purgeCount.incrementAndGet();
}
}
};
try {
storage.visit(ctx, f, v);
ctx.awaitTermination();
} catch (Exception ex) {
disable("visit exception", ex);
}
if (_purgeCount.get() > 0) {
checkStartFlushTimer();
}
return new PurgeableStorage.PurgeResult() {
@Override
public long getBytesFreed() {
return -1;
}
@Override
public int getEntriesPurged() {
return _purgeCount.get();
}
@Override
public int getEntriesScanned() {
return _scanCount.get();
}
};
}
abstract class BaseVisitContext extends MyMultiThreadContext implements CacheStorage.VisitContext {
}
class MyPurgeContext extends MyMultiThreadContext implements PurgeableStorage.PurgeContext {
}
class StorageVisitCallable implements LimitedPooledExecutor.NeverRunInCallingTask<Void> {
long now;
CompleteIterator it;
StorageVisitCallable(long now, CompleteIterator it) {
this.now = now;
this.it = it;
}
@Override
public Void call() {
final BlockingQueue<StorageEntry> _queue = it.queue;
CacheStorage.EntryVisitor v = new CacheStorage.EntryVisitor() {
@Override
public void visit(StorageEntry se) throws InterruptedException {
if (se.getValueExpiryTime() != 0 && se.getValueExpiryTime() <= now) { return; }
_queue.put(se);
}
};
CacheStorage.EntryFilter f = new CacheStorage.EntryFilter() {
@Override
public boolean shouldInclude(Object _key) {
return !BaseCache.Hash.contains(it.keysIterated, _key, cache.modifiedHash(_key.hashCode()));
}
};
try {
storage.visit(it, f, v);
} catch (Exception ex) {
it.abortOnException(ex);
_queue.clear();
} finally {
try {
it.awaitTermination();
} catch (InterruptedException ex) {
}
for (;;) {
try {
_queue.put(LAST_ENTRY);
break;
} catch (InterruptedException ex) {
}
}
}
return null;
}
}
static final BaseCache.Entry LAST_ENTRY = new BaseCache.Entry();
class MyMultiThreadContext implements CacheStorage.MultiThreadedContext {
ExecutorService executorForVisitThread;
boolean abortFlag;
Throwable abortException;
@Override
public ExecutorService getExecutorService() {
if (executorForVisitThread == null) {
if (tunable.useManagerThreadPool) {
LimitedPooledExecutor ex = new LimitedPooledExecutor(cache.manager.getThreadPool());
ex.setExceptionListener(new LimitedPooledExecutor.ExceptionListener() {
@Override
public void exceptionWasThrown(Throwable ex) {
abortOnException(ex);
}
});
executorForVisitThread = ex;
} else {
executorForVisitThread = createOperationExecutor();
}
}
return executorForVisitThread;
}
@Override
public void awaitTermination() throws InterruptedException {
if (executorForVisitThread != null) {
if (!executorForVisitThread.isTerminated()) {
if (shouldStop()) {
executorForVisitThread.shutdownNow();
} else {
executorForVisitThread.shutdown();
}
boolean _terminated = false;
if (tunable.terminationInfoSeconds > 0) {
_terminated = executorForVisitThread.awaitTermination(
tunable.terminationInfoSeconds, TimeUnit.SECONDS);
}
if (!_terminated) {
if (log.isInfoEnabled() && tunable.terminationInfoSeconds > 0) {
log.info(
"still waiting for thread termination after " +
tunable.terminationInfoSeconds + " seconds," +
" waiting for " + tunable.terminationTimeoutSeconds + " seconds");
}
_terminated = executorForVisitThread.awaitTermination(
tunable.terminationTimeoutSeconds - tunable.terminationTimeoutSeconds, TimeUnit.SECONDS);
if (!_terminated) {
log.warn("threads not terminated after " + tunable.terminationTimeoutSeconds + " seconds");
}
}
}
}
}
@Override
public void abortOnException(Throwable ex) {
if (abortException == null) {
abortException = ex;
}
abortFlag = true;
}
@Override
public boolean shouldStop() {
return abortFlag;
}
}
class CompleteIterator
extends MyMultiThreadContext
implements ClosableIterator<BaseCache.Entry>, CacheStorage.VisitContext {
BaseCache.Hash keepHashCtrlForClearDetection;
BaseCache.Entry[] keysIterated;
ClosableConcurrentHashEntryIterator localIteration;
int maximumEntriesToIterate;
StorageEntry entry;
BlockingQueue<StorageEntry> queue;
Callable<Void> runnable;
Future<Void> futureToCheckAbnormalTermination;
ExecutorService executorForStorageCall;
@Override
public boolean needMetaData() {
return true;
}
@Override
public boolean needValue() {
return true;
}
@Override
public boolean hasNext() {
if (localIteration != null) {
boolean b = localIteration.hasNext();
if (b) {
BaseCache.Entry e;
entry = e = localIteration.next();
return true;
}
if (localIteration.iteratedCtl.size >= maximumEntriesToIterate) {
queue = null;
} else {
keysIterated = localIteration.iterated;
futureToCheckAbnormalTermination =
executorForStorageCall.submit(runnable);
}
localIteration = null;
}
if (queue != null) {
if (abortException != null) {
queue = null;
throw new StorageIterationException(abortException);
}
if (cache.shutdownInitiated) {
throw new CacheClosedException();
}
if (keepHashCtrlForClearDetection.isCleared()) {
close();
return false;
}
try {
for (;;) {
entry = queue.poll(1234, TimeUnit.MILLISECONDS);
if (entry == null) {
if (!futureToCheckAbnormalTermination.isDone()) {
continue;
}
futureToCheckAbnormalTermination.get();
}
break;
}
if (entry != LAST_ENTRY) {
return true;
}
} catch (InterruptedException _ignore) {
} catch (ExecutionException ex) {
if (abortException == null) {
abortException = ex;
}
}
queue = null;
if (abortException != null) {
throw new CacheStorageException(abortException);
}
}
return false;
}
/**
* {@link BaseCache#insertEntryFromStorage(org.cache2k.storage.StorageEntry, boolean)}
* could be executed here or within the separate read thread. Since the eviction cannot run
* in parallel it is slightly better to do it here. This way the operation takes place on
* the same thread and cache trashing on the CPUs will be reduced.
*/
@Override
public BaseCache.Entry next() {
return cache.insertEntryFromStorage(entry, false);
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public void close() {
if (localIteration != null) {
localIteration.close();
localIteration = null;
}
if (executorForStorageCall != null) {
executorForStorageCall.shutdownNow();
executorForStorageCall = null;
queue = null;
}
}
}
static class StorageIterationException extends CacheStorageException {
StorageIterationException(Throwable cause) {
super(cause);
}
}
/**
* Start timer to flush data or do nothing if flush already scheduled.
*/
private void checkStartFlushTimer() {
if (flushIntervalMillis <= 0) {
return;
}
synchronized (flushLock) {
if (flushTimerHandle != null) {
return;
}
scheduleFlushTimer();
}
}
private void scheduleFlushTimer() {
TimerListener l = new TimerListener() {
@Override
public void fire(long _time) {
onFlushTimerEvent();
}
};
long _fireTime = System.currentTimeMillis() + config.getFlushIntervalMillis();
flushTimerHandle = cache.timerService.add(l, _fireTime);
}
protected void onFlushTimerEvent() {
synchronized (flushLock) {
flushTimerHandle.cancel();
flushTimerHandle = null;
if (storage instanceof ClearStorageBuffer ||
(!lastExecutingFlush.isDone())) {
checkStartFlushTimer();
return;
}
Callable<Void> c = new LimitedPooledExecutor.NeverRunInCallingTask<Void>() {
@Override
public Void call() throws Exception {
doStorageFlush();
return null;
}
};
lastExecutingFlush = executor.submit(c);
}
}
/**
* Initiate flush on the storage. If a concurrent flush is going on, wait for
* it until initiating a new one.
*/
public void flush() {
synchronized (flushLock) {
if (flushTimerHandle != null) {
flushTimerHandle.cancel();
flushTimerHandle = null;
}
}
Callable<Void> c = new Callable<Void>() {
@Override
public Void call() throws Exception {
doStorageFlush();
return null;
}
};
FutureTask<Void> _inThreadFlush = new FutureTask<>(c);
boolean _anotherFlushSubmittedNotByUs = false;
for (;;) {
if (!lastExecutingFlush.isDone()) {
try {
lastExecutingFlush.get();
if (_anotherFlushSubmittedNotByUs) {
return;
}
} catch (Exception ex) {
disableAndThrow("flush execution", ex);
}
}
synchronized (this) {
if (!lastExecutingFlush.isDone()) {
_anotherFlushSubmittedNotByUs = true;
continue;
}
lastExecutingFlush = _inThreadFlush;
}
_inThreadFlush.run();
break;
}
}
private void doStorageFlush() throws Exception {
FlushableStorage.FlushContext ctx = new MyFlushContext();
FlushableStorage _storage = (FlushableStorage) storage;
_storage.flush(ctx, System.currentTimeMillis());
log.info("flushed, state: " + storage);
}
/** may be executed more than once */
public synchronized Future<Void> cancelTimerJobs() {
if (flushIntervalMillis >= 0) {
flushIntervalMillis = -1;
}
if (flushTimerHandle != null) {
flushTimerHandle.cancel();
flushTimerHandle = null;
}
if (!lastExecutingFlush.isDone()) {
lastExecutingFlush.cancel(false);
return lastExecutingFlush;
}
return new Futures.FinishedFuture<>();
}
public Future<Void> shutdown() {
if (storage instanceof ClearStorageBuffer) {
throw new CacheInternalError("Clear is supposed to be in shutdown wait task queue");
}
Callable<Void> _closeTaskChain = new Callable<Void>() {
@Override
public Void call() throws Exception {
if (config.isFlushOnClose()) {
flush();
} else {
Future<Void> _previousFlush = lastExecutingFlush;
if (_previousFlush != null) {
_previousFlush.cancel(true);
_previousFlush.get();
}
}
logLifecycleOperation("closing, state: " + storage);
storage.close();
return null;
}
};
if (passivation && !(storage instanceof TransientStorageClass)) {
final Callable<Void> _before = _closeTaskChain;
_closeTaskChain = new Callable<Void>() {
@Override
public Void call() throws Exception {
passivateHeapEntriesOnShutdown();
executor.submit(_before);
return null;
}
};
}
return executor.submit(_closeTaskChain);
}
/**
* Iterate through the heap entries and store them in the storage.
*/
private void passivateHeapEntriesOnShutdown() {
Iterator<BaseCache.Entry> it;
try {
synchronized (cache.lock) {
it = cache.iterateAllLocalEntries();
}
while (it.hasNext()) {
BaseCache.Entry e = it.next();
synchronized (e) {
putEventually(e);
}
}
if (deletedKeys != null) {
for (Object k : deletedKeys) {
storage.remove(k);
}
}
} catch (Exception ex) {
rethrow("shutdown passivation", ex);
}
}
/**
* True means actually no operations started on the storage again, yet
*/
public boolean checkStorageStillDisconnectedForClear() {
if (storage instanceof ClearStorageBuffer) {
ClearStorageBuffer _buffer = (ClearStorageBuffer) storage;
if (!_buffer.isTransferringToStorage()) {
return true;
}
}
return false;
}
/**
* Disconnect storage so cache can wait for all entry operations to finish.
*/
public void disconnectStorageForClear() {
synchronized (this) {
ClearStorageBuffer _buffer = new ClearStorageBuffer();
_buffer.nextStorage = storage;
storage = _buffer;
if (_buffer.nextStorage instanceof ClearStorageBuffer) {
ClearStorageBuffer _ongoingClear = (ClearStorageBuffer) _buffer.nextStorage;
if (_ongoingClear.clearThreadFuture != null) {
_ongoingClear.shouldStop = true;
}
}
}
}
/**
* Called in a (maybe) separate thread after disconnect. Cache
* already is doing operations meanwhile and the storage operations
* are buffered. Here we have multiple race conditions. A clear() exists
* immediately but the storage is still working on the first clear.
* All previous clear processes will be cancelled and the last one may
* will. However, this method is not necessarily executed in the order
* the clear or the disconnect took place. This is checked also.
*/
public Future<Void> startClearingAndReconnection() {
synchronized (this) {
final ClearStorageBuffer _buffer = (ClearStorageBuffer) storage;
if (_buffer.clearThreadFuture != null) {
return _buffer.clearThreadFuture;
}
ClearStorageBuffer _previousBuffer = null;
if (_buffer.getNextStorage() instanceof ClearStorageBuffer) {
_previousBuffer = (ClearStorageBuffer) _buffer.getNextStorage();
_buffer.nextStorage = _buffer.getOriginalStorage();
}
final ClearStorageBuffer _waitingBufferStack = _previousBuffer;
Callable<Void> c = new LimitedPooledExecutor.NeverRunInCallingTask<Void>() {
@Override
public Void call() throws Exception {
try {
if (_waitingBufferStack != null) {
_waitingBufferStack.waitForAll();
}
} catch (Exception ex) {
disable("exception during waiting for previous clear", ex);
throw new CacheStorageException(ex);
}
synchronized (this) {
if (_buffer.shouldStop) {
return null;
}
}
try {
_buffer.getOriginalStorage().clear();
} catch (Exception ex) {
disable("exception during clear", ex);
throw new CacheStorageException(ex);
}
synchronized (cache.lock) {
_buffer.startTransfer();
}
try {
_buffer.transfer();
} catch (Exception ex) {
disable("exception during clear, operations replay", ex);
throw new CacheStorageException(ex);
}
synchronized (this) {
if (_buffer.shouldStop) { return null; }
storage = _buffer.getOriginalStorage();
}
return null;
}
};
_buffer.clearThreadFuture = executor.submit(c);
return _buffer.clearThreadFuture;
}
}
public void disableAndThrow(String _logMessage, Throwable ex) {
errorCount++;
disable(_logMessage, ex);
rethrow(_logMessage, ex);
}
public void disable(String _logMessage, Throwable ex) {
log.warn(_logMessage, ex);
disable(ex);
}
public void disable(Throwable ex) {
if (storage == null) { return; }
synchronized (cache.lock) {
synchronized (this) {
if (storage == null) { return; }
CacheStorage _storage = storage;
if (_storage instanceof ClearStorageBuffer) {
ClearStorageBuffer _buffer = (ClearStorageBuffer) _storage;
_buffer.disableOnFailure(ex);
}
try {
_storage.close();
} catch (Exception _ignore) {
}
storage = null;
parent.resetStorage(this, new NoopStorageAdapter(cache));
}
}
}
/**
* orange alert level if buffer is active, so we get alerted if storage
* clear isn't finished.
*/
@Override
public int getAlert() {
if (errorCount > 0) {
return 1;
}
if (storage instanceof ClearStorageBuffer) {
return 1;
}
return 0;
}
/**
* Calculates the cache size, depending on the persistence configuration
*/
@Override
public int getTotalEntryCount() {
if (!passivation) {
return storage.getEntryCount();
}
return storage.getEntryCount() + cache.getLocalSize();
}
public CacheStorage getImplementation() {
return storage;
}
class MyFlushContext
extends MyMultiThreadContext
implements FlushableStorage.FlushContext {
}
static class StorageContext implements CacheStorageContext {
BaseCache cache;
Class<?> keyType;
Class<?> valueType;
StorageContext(BaseCache cache) {
this.cache = cache;
}
@Override
public Properties getProperties() {
return null;
}
@Override
public String getManagerName() {
return cache.manager.getName();
}
@Override
public String getCacheName() {
return cache.getName();
}
@Override
public Class<?> getKeyType() {
return keyType;
}
@Override
public Class<?> getValueType() {
return valueType;
}
@Override
public MarshallerFactory getMarshallerFactory() {
return Marshallers.getInstance();
}
@Override
public void requestMaintenanceCall(int _intervalMillis) {
}
@Override
public void notifyEvicted(StorageEntry e) {
}
@Override
public void notifyExpired(StorageEntry e) {
}
}
ExecutorService createOperationExecutor() {
return
new ThreadPoolExecutor(
0, Runtime.getRuntime().availableProcessors() * 123 / 100,
21, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(),
THREAD_FACTORY,
new ThreadPoolExecutor.CallerRunsPolicy());
}
static final ThreadFactory THREAD_FACTORY = new MyThreadFactory();
@SuppressWarnings("NullableProblems")
static class MyThreadFactory implements ThreadFactory {
AtomicInteger count = new AtomicInteger();
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r, "cache2k-storage#" + count.incrementAndGet());
if (t.isDaemon()) {
t.setDaemon(false);
}
if (t.getPriority() != Thread.NORM_PRIORITY) {
t.setPriority(Thread.NORM_PRIORITY);
}
return t;
}
}
public static class Tunable extends TunableConstants {
/**
* If the iteration client needs more time then the read threads,
* the queue fills up. When the capacity is reached the reading
* threads block until the client is requesting the next entry.
*
* <p>A low number makes sense here just to make sure that the read threads are
* not waiting if the iterator client is doing some processing. We should
* never put a large number here, to keep overall memory capacity control
* within the cache and don't introduce additional buffers.
*
* <p>When the value is 0 a {@link java.util.concurrent.SynchronousQueue}
* is used.
*/
public int iterationQueueCapacity = 3;
public boolean useManagerThreadPool = true;
/**
* Thread termination writes a info log message, if we still wait for termination.
* Set to 0 to disable. Default: 5
*/
public int terminationInfoSeconds = 5;
/**
* Maximum time to await the termination of all executor threads. Default: 2000
*/
public int terminationTimeoutSeconds = 200;
}
}
| core/src/main/java/org/cache2k/impl/PassingStorageAdapter.java | package org.cache2k.impl;
/*
* #%L
* cache2k core package
* %%
* Copyright (C) 2000 - 2014 headissue GmbH, Munich
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
import org.cache2k.Cache;
import org.cache2k.CacheConfig;
import org.cache2k.ClosableIterator;
import org.cache2k.StorageConfiguration;
import org.cache2k.impl.threading.Futures;
import org.cache2k.impl.threading.LimitedPooledExecutor;
import org.cache2k.impl.timer.TimerListener;
import org.cache2k.impl.timer.TimerService;
import org.cache2k.spi.SingleProviderResolver;
import org.cache2k.storage.CacheStorage;
import org.cache2k.storage.CacheStorageContext;
import org.cache2k.storage.CacheStorageProvider;
import org.cache2k.storage.FlushableStorage;
import org.cache2k.storage.MarshallerFactory;
import org.cache2k.storage.Marshallers;
import org.cache2k.storage.TransientStorageClass;
import org.cache2k.storage.PurgeableStorage;
import org.cache2k.storage.StorageEntry;
import org.cache2k.impl.util.Log;
import org.cache2k.impl.util.TunableConstants;
import org.cache2k.impl.util.TunableFactory;
import javax.annotation.Nonnull;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Passes cache operation to the storage layer. Implements common
* services for the storage layer. This class heavily interacts
* with the base cache and contains mostly everything special
* needed if a storage is defined. This means the design is not
* perfectly layered, in some cases the
* e.g. the get operation does interacts with the
* underlying storage, wheres iterate
*
* @author Jens Wilke; created: 2014-05-08
*/
@SuppressWarnings({"unchecked", "SynchronizeOnNonFinalField"})
public class PassingStorageAdapter extends StorageAdapter {
private Tunable tunable = TunableFactory.get(Tunable.class);
private BaseCache cache;
CacheStorage storage;
boolean passivation = false;
long errorCount = 0;
Set<Object> deletedKeys = null;
StorageContext context;
StorageConfiguration config;
ExecutorService executor;
long flushIntervalMillis = 0;
Object flushLock = new Object();
TimerService.CancelHandle flushTimerHandle;
@Nonnull
Future<Void> lastExecutingFlush = new Futures.FinishedFuture<>();
Object purgeRunningLock = new Object();
Log log;
StorageAdapter.Parent parent;
public PassingStorageAdapter(BaseCache _cache, CacheConfig _cacheConfig,
StorageConfiguration _storageConfig) {
cache = _cache;
parent = _cache;
context = new StorageContext(_cache);
context.keyType = _cacheConfig.getKeyType();
context.valueType = _cacheConfig.getValueType();
config = _storageConfig;
if (tunable.useManagerThreadPool) {
executor = new LimitedPooledExecutor(cache.manager.getThreadPool());
} else {
executor = Executors.newCachedThreadPool();
}
log = Log.getLog(Cache.class.getName() + ".storage/" + cache.getCompleteName());
}
/**
* By default log lifecycle operations as info.
*/
protected void logLifecycleOperation(String s) {
log.info(s);
}
public void open() {
try {
CacheStorageProvider<?> pr = (CacheStorageProvider)
SingleProviderResolver.getInstance().resolve(config.getImplementation());
storage = pr.create(context, config);
flushIntervalMillis = config.getFlushIntervalMillis();
if (!(storage instanceof FlushableStorage)) {
flushIntervalMillis = -1;
}
if (config.isPassivation() || storage instanceof TransientStorageClass) {
deletedKeys = new HashSet<>();
passivation = true;
}
logLifecycleOperation("opened, state: " + storage);
} catch (Exception ex) {
if (config.isReliable()) {
disableAndThrow("error initializing, disabled", ex);
} else {
disable("error initializing, disabled", ex);
}
}
}
/**
* Store entry on cache put. Entry must be locked, since we use the
* entry directly for handing it over to the storage, it is not
* allowed to change.
*/
public void put(BaseCache.Entry e) {
if (passivation) {
synchronized (deletedKeys) {
deletedKeys.remove(e.getKey());
}
return;
}
doPut(e);
}
private void doPut(BaseCache.Entry e) {
try {
storage.put(e);
checkStartFlushTimer();
} catch (Exception ex) {
if (config.isReliable()) {
disableAndThrow("exception in storage.put()", ex);
} else {
errorCount++;
try {
if (!storage.contains(e.getKey())) {
return;
}
storage.remove(e.getKey());
} catch (Exception ex2) {
ex.addSuppressed(ex2);
disableAndThrow("exception in storage.put(), mitigation failed, entry state unknown", ex);
}
}
}
}
public StorageEntry get(Object k) {
if (deletedKeys != null) {
synchronized (deletedKeys) {
if (deletedKeys.contains(k)) {
return null;
}
}
}
try {
return storage.get(k);
} catch (Exception ex) {
errorCount++;
if (config.isReliable()) {
throw new CacheStorageException("cache get", ex);
}
return null;
}
}
/**
* If passivation is not enabled, then we need to do nothing here since, the
* entry was transferred to the storage on the {@link #put(org.cache2k.impl.BaseCache.Entry)}
* operation. With passivation enabled, the entries need to be transferred when evicted from
* the heap.
*
* <p/>The storage operation is done in the calling thread, which should be a client thread.
* The cache client will be throttled until the I/O operation is finished. This is what we
* want in general. To decouple it, we need to implement async storage I/O support.
*/
public void evict(BaseCache.Entry e) {
if (passivation) {
putEventually(e);
}
}
/**
* An expired entry was removed from the memory cache and
* can also be removed from the storage. For the moment, this
* does nothing, since we cannot do the removal in the calling
* thread and decoupling yields bad race conditions.
* Expired entries in the storage are remove by the purge run.
*/
public void expire(BaseCache.Entry e) {
}
/**
* Store it in the storage if needed, that is if it is dirty
* or if the entry is not yet in the storage. When an off heap
* and persistent storage is aggregated, evicted entries will
* be put to the off heap storage, but not into the persistent
* storage again.
*/
private void putEventually(BaseCache.Entry e) {
if (!e.isDirty()) {
if (!(storage instanceof TransientStorageClass)) {
return;
}
try {
if (storage.contains(e.getKey())) {
return;
}
} catch (Exception ex) {
errorCount++;
disable("storage.contains(), unknown state", ex);
throw new CacheStorageException("", ex);
}
}
doPut(e);
}
public void remove(Object key) {
if (deletedKeys != null) {
synchronized (deletedKeys) {
deletedKeys.remove(key);
}
return;
}
try {
storage.remove(key);
checkStartFlushTimer();
} catch (Exception ex) {
disableAndThrow("storage.remove()", ex);
}
}
@Override
public ClosableIterator<BaseCache.Entry> iterateAll() {
final CompleteIterator it = new CompleteIterator();
if (tunable.iterationQueueCapacity > 0) {
it.queue = new ArrayBlockingQueue<>(tunable.iterationQueueCapacity);
} else {
it.queue = new SynchronousQueue<>();
}
synchronized (cache.lock) {
it.localIteration = cache.iterateAllLocalEntries();
it.localIteration.setKeepIterated(true);
it.keepHashCtrlForClearDetection = cache.mainHashCtrl;
if (!passivation) {
it.maximumEntriesToIterate = storage.getEntryCount();
} else {
it.maximumEntriesToIterate = Integer.MAX_VALUE;
}
}
it.executorForStorageCall = executor;
long now = System.currentTimeMillis();
it.runnable = new StorageVisitCallable(now, it);
return it;
}
public void purge() {
synchronized (purgeRunningLock) {
long now = System.currentTimeMillis();
PurgeableStorage.PurgeResult res;
if (storage instanceof PurgeableStorage) {
try {
PurgeableStorage.PurgeContext ctx = new MyPurgeContext();
res = ((PurgeableStorage) storage).purge(ctx, now, now);
} catch (Exception ex) {
disable("expire exception", ex);
return;
}
} else {
res = purgeByVisit(now);
}
if (log.isInfoEnabled()) {
long t = System.currentTimeMillis();
log.info("purge (force): " +
"runtimeMillis=" + (t - now) + ", " +
"scanned=" + res.getEntriesScanned() + ", " +
"purged=" + res.getEntriesPurged() +
(res.getBytesFreed() >=0 ? ", " + "freedBytes=" + res.getBytesFreed() : ""));
}
}
}
PurgeableStorage.PurgeResult purgeByVisit(final long now) {
CacheStorage.EntryFilter f = new CacheStorage.EntryFilter() {
@Override
public boolean shouldInclude(Object _key) {
return true;
}
};
CacheStorage.VisitContext ctx = new BaseVisitContext() {
@Override
public boolean needMetaData() {
return true;
}
@Override
public boolean needValue() {
return false;
}
};
final AtomicInteger _scanCount = new AtomicInteger();
final AtomicInteger _purgeCount = new AtomicInteger();
CacheStorage.EntryVisitor v = new CacheStorage.EntryVisitor() {
@Override
public void visit(StorageEntry e) throws Exception {
_scanCount.incrementAndGet();
if (e.getValueExpiryTime() < now) {
storage.remove(e.getKey());
remove(e.getKey());
_purgeCount.incrementAndGet();
}
}
};
try {
storage.visit(ctx, f, v);
ctx.awaitTermination();
} catch (Exception ex) {
disable("visit exception", ex);
}
if (_purgeCount.get() > 0) {
checkStartFlushTimer();
}
return new PurgeableStorage.PurgeResult() {
@Override
public long getBytesFreed() {
return -1;
}
@Override
public int getEntriesPurged() {
return _purgeCount.get();
}
@Override
public int getEntriesScanned() {
return _scanCount.get();
}
};
}
abstract class BaseVisitContext extends MyMultiThreadContext implements CacheStorage.VisitContext {
}
class MyPurgeContext extends MyMultiThreadContext implements PurgeableStorage.PurgeContext {
}
class StorageVisitCallable implements LimitedPooledExecutor.NeverRunInCallingTask<Void> {
long now;
CompleteIterator it;
StorageVisitCallable(long now, CompleteIterator it) {
this.now = now;
this.it = it;
}
@Override
public Void call() {
final BlockingQueue<StorageEntry> _queue = it.queue;
CacheStorage.EntryVisitor v = new CacheStorage.EntryVisitor() {
@Override
public void visit(StorageEntry se) throws InterruptedException {
if (se.getValueExpiryTime() != 0 && se.getValueExpiryTime() <= now) { return; }
_queue.put(se);
}
};
CacheStorage.EntryFilter f = new CacheStorage.EntryFilter() {
@Override
public boolean shouldInclude(Object _key) {
return !BaseCache.Hash.contains(it.keysIterated, _key, cache.modifiedHash(_key.hashCode()));
}
};
try {
storage.visit(it, f, v);
} catch (Exception ex) {
it.abortOnException(ex);
_queue.clear();
} finally {
try {
it.awaitTermination();
} catch (InterruptedException ex) {
}
for (;;) {
try {
_queue.put(LAST_ENTRY);
break;
} catch (InterruptedException ex) {
}
}
}
return null;
}
}
static final BaseCache.Entry LAST_ENTRY = new BaseCache.Entry();
class MyMultiThreadContext implements CacheStorage.MultiThreadedContext {
ExecutorService executorForVisitThread;
boolean abortFlag;
Throwable abortException;
@Override
public ExecutorService getExecutorService() {
if (executorForVisitThread == null) {
if (tunable.useManagerThreadPool) {
LimitedPooledExecutor ex = new LimitedPooledExecutor(cache.manager.getThreadPool());
ex.setExceptionListener(new LimitedPooledExecutor.ExceptionListener() {
@Override
public void exceptionWasThrown(Throwable ex) {
abortOnException(ex);
}
});
executorForVisitThread = ex;
} else {
executorForVisitThread = createOperationExecutor();
}
}
return executorForVisitThread;
}
@Override
public void awaitTermination() throws InterruptedException {
if (executorForVisitThread != null) {
if (!executorForVisitThread.isTerminated()) {
if (shouldStop()) {
executorForVisitThread.shutdownNow();
} else {
executorForVisitThread.shutdown();
}
boolean _terminated = false;
if (tunable.terminationInfoSeconds > 0) {
_terminated = executorForVisitThread.awaitTermination(
tunable.terminationInfoSeconds, TimeUnit.SECONDS);
}
if (!_terminated) {
if (log.isInfoEnabled() && tunable.terminationInfoSeconds > 0) {
log.info(
"still waiting for thread termination after " +
tunable.terminationInfoSeconds + " seconds," +
" waiting for " + tunable.terminationTimeoutSeconds + " seconds");
}
_terminated = executorForVisitThread.awaitTermination(
tunable.terminationTimeoutSeconds - tunable.terminationTimeoutSeconds, TimeUnit.SECONDS);
if (!_terminated) {
log.warn("threads not terminated after " + tunable.terminationTimeoutSeconds + " seconds");
}
}
}
}
}
@Override
public void abortOnException(Throwable ex) {
if (abortException == null) {
abortException = ex;
}
abortFlag = true;
}
@Override
public boolean shouldStop() {
return abortFlag;
}
}
class CompleteIterator
extends MyMultiThreadContext
implements ClosableIterator<BaseCache.Entry>, CacheStorage.VisitContext {
BaseCache.Hash keepHashCtrlForClearDetection;
BaseCache.Entry[] keysIterated;
ClosableConcurrentHashEntryIterator localIteration;
int maximumEntriesToIterate;
StorageEntry entry;
BlockingQueue<StorageEntry> queue;
Callable<Void> runnable;
Future<Void> futureToCheckAbnormalTermination;
ExecutorService executorForStorageCall;
@Override
public boolean needMetaData() {
return true;
}
@Override
public boolean needValue() {
return true;
}
@Override
public boolean hasNext() {
if (localIteration != null) {
boolean b = localIteration.hasNext();
if (b) {
BaseCache.Entry e;
entry = e = localIteration.next();
return true;
}
if (localIteration.iteratedCtl.size >= maximumEntriesToIterate) {
queue = null;
} else {
keysIterated = localIteration.iterated;
futureToCheckAbnormalTermination =
executorForStorageCall.submit(runnable);
}
localIteration = null;
}
if (queue != null) {
if (abortException != null) {
queue = null;
throw new StorageIterationException(abortException);
}
if (cache.shutdownInitiated) {
throw new CacheClosedException();
}
if (keepHashCtrlForClearDetection.isCleared()) {
close();
return false;
}
try {
for (;;) {
entry = queue.poll(1234, TimeUnit.MILLISECONDS);
if (entry == null) {
if (!futureToCheckAbnormalTermination.isDone()) {
continue;
}
futureToCheckAbnormalTermination.get();
}
break;
}
if (entry != LAST_ENTRY) {
return true;
}
} catch (InterruptedException _ignore) {
} catch (ExecutionException ex) {
if (abortException == null) {
abortException = ex;
}
}
queue = null;
if (abortException != null) {
throw new CacheStorageException(abortException);
}
}
return false;
}
/**
* {@link BaseCache#insertEntryFromStorage(org.cache2k.storage.StorageEntry, boolean)}
* could be executed here or within the separate read thread. Since the eviction cannot run
* in parallel it is slightly better to do it here. This way the operation takes place on
* the same thread and cache trashing on the CPUs will be reduced.
*/
@Override
public BaseCache.Entry next() {
return cache.insertEntryFromStorage(entry, false);
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public void close() {
if (localIteration != null) {
localIteration.close();
localIteration = null;
}
if (executorForStorageCall != null) {
executorForStorageCall.shutdownNow();
executorForStorageCall = null;
queue = null;
}
}
}
static class StorageIterationException extends CacheStorageException {
StorageIterationException(Throwable cause) {
super(cause);
}
}
/**
* Start timer to flush data or do nothing if flush already scheduled.
*/
private void checkStartFlushTimer() {
if (flushIntervalMillis <= 0) {
return;
}
synchronized (flushLock) {
if (flushTimerHandle != null) {
return;
}
scheduleFlushTimer();
}
}
private void scheduleFlushTimer() {
TimerListener l = new TimerListener() {
@Override
public void fire(long _time) {
onFlushTimerEvent();
}
};
long _fireTime = System.currentTimeMillis() + config.getFlushIntervalMillis();
flushTimerHandle = cache.timerService.add(l, _fireTime);
}
protected void onFlushTimerEvent() {
synchronized (flushLock) {
flushTimerHandle.cancel();
flushTimerHandle = null;
if (storage instanceof ClearStorageBuffer ||
(!lastExecutingFlush.isDone())) {
checkStartFlushTimer();
return;
}
Callable<Void> c = new LimitedPooledExecutor.NeverRunInCallingTask<Void>() {
@Override
public Void call() throws Exception {
doStorageFlush();
return null;
}
};
lastExecutingFlush = executor.submit(c);
}
}
/**
* Initiate flush on the storage. If a concurrent flush is going on, wait for
* it until initiating a new one.
*/
public void flush() {
synchronized (flushLock) {
if (flushTimerHandle != null) {
flushTimerHandle.cancel();
flushTimerHandle = null;
}
}
Callable<Void> c = new Callable<Void>() {
@Override
public Void call() throws Exception {
doStorageFlush();
return null;
}
};
FutureTask<Void> _inThreadFlush = new FutureTask<>(c);
boolean _anotherFlushSubmittedNotByUs = false;
for (;;) {
if (!lastExecutingFlush.isDone()) {
try {
lastExecutingFlush.get();
if (_anotherFlushSubmittedNotByUs) {
return;
}
} catch (Exception ex) {
disableAndThrow("flush execution", ex);
}
}
synchronized (this) {
if (!lastExecutingFlush.isDone()) {
_anotherFlushSubmittedNotByUs = true;
continue;
}
lastExecutingFlush = _inThreadFlush;
}
_inThreadFlush.run();
break;
}
}
private void doStorageFlush() throws Exception {
FlushableStorage.FlushContext ctx = new MyFlushContext();
FlushableStorage _storage = (FlushableStorage) storage;
_storage.flush(ctx, System.currentTimeMillis());
log.info("flushed, state: " + storage);
}
/** may be executed more than once */
public synchronized Future<Void> cancelTimerJobs() {
if (flushIntervalMillis >= 0) {
flushIntervalMillis = -1;
}
if (flushTimerHandle != null) {
flushTimerHandle.cancel();
flushTimerHandle = null;
}
if (!lastExecutingFlush.isDone()) {
lastExecutingFlush.cancel(false);
return lastExecutingFlush;
}
return new Futures.FinishedFuture<>();
}
public Future<Void> shutdown() {
if (storage instanceof ClearStorageBuffer) {
throw new CacheInternalError("Clear is supposed to be in shutdown wait task queue");
}
Callable<Void> _closeTaskChain = new Callable<Void>() {
@Override
public Void call() throws Exception {
if (config.isFlushOnClose()) {
flush();
} else {
Future<Void> _previousFlush = lastExecutingFlush;
if (_previousFlush != null) {
_previousFlush.cancel(true);
_previousFlush.get();
}
}
logLifecycleOperation("closing, state: " + storage);
storage.close();
return null;
}
};
if (passivation && !(storage instanceof TransientStorageClass)) {
final Callable<Void> _before = _closeTaskChain;
_closeTaskChain = new Callable<Void>() {
@Override
public Void call() throws Exception {
passivateHeapEntriesOnShutdown();
executor.submit(_before);
return null;
}
};
}
return executor.submit(_closeTaskChain);
}
/**
* Iterate through the heap entries and store them in the storage.
*/
private void passivateHeapEntriesOnShutdown() {
Iterator<BaseCache.Entry> it;
try {
synchronized (cache.lock) {
it = cache.iterateAllLocalEntries();
}
while (it.hasNext()) {
BaseCache.Entry e = it.next();
synchronized (e) {
putEventually(e);
}
}
if (deletedKeys != null) {
for (Object k : deletedKeys) {
storage.remove(k);
}
}
} catch (Exception ex) {
rethrow("shutdown passivation", ex);
}
}
/**
* True means actually no operations started on the storage again, yet
*/
public boolean checkStorageStillDisconnectedForClear() {
if (storage instanceof ClearStorageBuffer) {
ClearStorageBuffer _buffer = (ClearStorageBuffer) storage;
if (!_buffer.isTransferringToStorage()) {
return true;
}
}
return false;
}
/**
* Disconnect storage so cache can wait for all entry operations to finish.
*/
public void disconnectStorageForClear() {
synchronized (this) {
ClearStorageBuffer _buffer = new ClearStorageBuffer();
_buffer.nextStorage = storage;
storage = _buffer;
if (_buffer.nextStorage instanceof ClearStorageBuffer) {
ClearStorageBuffer _ongoingClear = (ClearStorageBuffer) _buffer.nextStorage;
if (_ongoingClear.clearThreadFuture != null) {
_ongoingClear.shouldStop = true;
}
}
}
}
/**
* Called in a (maybe) separate thread after disconnect. Cache
* already is doing operations meanwhile and the storage operations
* are buffered. Here we have multiple race conditions. A clear() exists
* immediately but the storage is still working on the first clear.
* All previous clear processes will be cancelled and the last one may
* will. However, this method is not necessarily executed in the order
* the clear or the disconnect took place. This is checked also.
*/
public Future<Void> startClearingAndReconnection() {
synchronized (this) {
final ClearStorageBuffer _buffer = (ClearStorageBuffer) storage;
if (_buffer.clearThreadFuture != null) {
return _buffer.clearThreadFuture;
}
ClearStorageBuffer _previousBuffer = null;
if (_buffer.getNextStorage() instanceof ClearStorageBuffer) {
_previousBuffer = (ClearStorageBuffer) _buffer.getNextStorage();
_buffer.nextStorage = _buffer.getOriginalStorage();
}
final ClearStorageBuffer _waitingBufferStack = _previousBuffer;
Callable<Void> c = new LimitedPooledExecutor.NeverRunInCallingTask<Void>() {
@Override
public Void call() throws Exception {
try {
if (_waitingBufferStack != null) {
_waitingBufferStack.waitForAll();
}
} catch (Exception ex) {
disable("exception during waiting for previous clear", ex);
throw new CacheStorageException(ex);
}
synchronized (this) {
if (_buffer.shouldStop) {
return null;
}
}
try {
_buffer.getOriginalStorage().clear();
} catch (Exception ex) {
disable("exception during clear", ex);
throw new CacheStorageException(ex);
}
synchronized (cache.lock) {
_buffer.startTransfer();
}
try {
_buffer.transfer();
} catch (Exception ex) {
disable("exception during clear, operations replay", ex);
throw new CacheStorageException(ex);
}
synchronized (this) {
if (_buffer.shouldStop) { return null; }
storage = _buffer.getOriginalStorage();
}
return null;
}
};
_buffer.clearThreadFuture = executor.submit(c);
return _buffer.clearThreadFuture;
}
}
public void disableAndThrow(String _logMessage, Throwable ex) {
errorCount++;
disable(_logMessage, ex);
rethrow(_logMessage, ex);
}
public void disable(String _logMessage, Throwable ex) {
log.warn(_logMessage, ex);
disable(ex);
}
public void disable(Throwable ex) {
if (storage == null) { return; }
synchronized (cache.lock) {
synchronized (this) {
if (storage == null) { return; }
CacheStorage _storage = storage;
if (_storage instanceof ClearStorageBuffer) {
ClearStorageBuffer _buffer = (ClearStorageBuffer) _storage;
_buffer.disableOnFailure(ex);
}
try {
_storage.close();
} catch (Exception _ignore) {
}
storage = null;
parent.resetStorage(this, new NoopStorageAdapter(cache));
}
}
}
/**
* orange alert level if buffer is active, so we get alerted if storage
* clear isn't finished.
*/
@Override
public int getAlert() {
if (errorCount > 0) {
return 1;
}
if (storage instanceof ClearStorageBuffer) {
return 1;
}
return 0;
}
/**
* Calculates the cache size, depending on the persistence configuration
*/
@Override
public int getTotalEntryCount() {
if (!passivation) {
return storage.getEntryCount();
}
return storage.getEntryCount() + cache.getLocalSize();
}
public CacheStorage getImplementation() {
return storage;
}
class MyFlushContext
extends MyMultiThreadContext
implements FlushableStorage.FlushContext {
}
static class StorageContext implements CacheStorageContext {
BaseCache cache;
Class<?> keyType;
Class<?> valueType;
StorageContext(BaseCache cache) {
this.cache = cache;
}
@Override
public Properties getProperties() {
return null;
}
@Override
public String getManagerName() {
return cache.manager.getName();
}
@Override
public String getCacheName() {
return cache.getName();
}
@Override
public Class<?> getKeyType() {
return keyType;
}
@Override
public Class<?> getValueType() {
return valueType;
}
@Override
public MarshallerFactory getMarshallerFactory() {
return Marshallers.getInstance();
}
@Override
public void requestMaintenanceCall(int _intervalMillis) {
}
@Override
public void notifyEvicted(StorageEntry e) {
}
@Override
public void notifyExpired(StorageEntry e) {
}
}
ExecutorService createOperationExecutor() {
return
new ThreadPoolExecutor(
0, Runtime.getRuntime().availableProcessors() * 123 / 100,
21, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(),
THREAD_FACTORY,
new ThreadPoolExecutor.CallerRunsPolicy());
}
static final ThreadFactory THREAD_FACTORY = new MyThreadFactory();
@SuppressWarnings("NullableProblems")
static class MyThreadFactory implements ThreadFactory {
AtomicInteger count = new AtomicInteger();
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r, "cache2k-storage#" + count.incrementAndGet());
if (t.isDaemon()) {
t.setDaemon(false);
}
if (t.getPriority() != Thread.NORM_PRIORITY) {
t.setPriority(Thread.NORM_PRIORITY);
}
return t;
}
}
public static class Tunable extends TunableConstants {
/**
* If the iteration client needs more time then the read threads,
* the queue fills up. When the capacity is reached the reading
* threads block until the client is requesting the next entry.
*
* <p>A low number makes sense here just to make sure that the read threads are
* not waiting if the iterator client is doing some processing. We should
* never put a large number here, to keep overall memory capacity control
* within the cache and don't introduce additional buffers.
*
* <p>When the value is 0 a {@link java.util.concurrent.SynchronousQueue}
* is used.
*/
public int iterationQueueCapacity = 3;
public boolean useManagerThreadPool = true;
/**
* Thread termination writes a info log message, if we still wait for termination.
* Set to 0 to disable. Default: 5
*/
public int terminationInfoSeconds = 5;
/**
* Maximum time to await the termination of all executor threads. Default: 2000
*/
public int terminationTimeoutSeconds = 200;
}
}
| work on purge, fix time check
| core/src/main/java/org/cache2k/impl/PassingStorageAdapter.java | work on purge, fix time check |
|
Java | apache-2.0 | d64af279cec4a00b56c9a9fc0e50ef3fd9a3c9cf | 0 | akihito104/UdonRoad | /*
* Copyright (c) 2016. Matsuda, Akihit (akihito104)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.freshdigitable.udonroad;
import android.support.annotation.Nullable;
import android.text.Selection;
import android.text.SpanWatcher;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.style.ClickableSpan;
import android.text.style.URLSpan;
import android.view.View;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import twitter4j.MediaEntity;
import twitter4j.Status;
import twitter4j.URLEntity;
import twitter4j.UserMentionEntity;
/**
* SpannableStringUtil creates clickable text.
*
* Created by akihit on 2016/10/08.
*/
class SpannableStringUtil {
static CharSequence create(Status bindingStatus) {
final List<SpanningInfo> spannableInfo = createSpanningInfo(bindingStatus);
return createClickableSpan(bindingStatus.getText(), spannableInfo);
}
static CharSequence create(final String text, URLEntity[] urlEntities) {
if (TextUtils.isEmpty(text)) {
return "";
}
final List<SpanningInfo> urlSpanningInfo = createURLSpanningInfo(text, urlEntities, null);
return createClickableSpan(text, urlSpanningInfo);
}
private static List<SpanningInfo> createSpanningInfo(Status bindingStatus) {
List<SpanningInfo> info = new ArrayList<>();
info.addAll(createURLSpanningInfo(bindingStatus));
info.addAll(createUserSpanningInfo(bindingStatus));
for (int i = info.size() - 1; i >= 0; i--) {
final SpanningInfo spanningInfo = info.get(i);
for (int j = 0; j < i; j++) {
if (spanningInfo.start == info.get(j).start) {
info.remove(spanningInfo);
break;
}
}
}
return info;
}
private static List<SpanningInfo> createURLSpanningInfo(Status bindingStatus) {
final String text = bindingStatus.getText();
final String quotedStatusIdStr = bindingStatus.getQuotedStatus() != null
? Long.toString(bindingStatus.getQuotedStatusId())
: "";
final List<SpanningInfo> info = new ArrayList<>();
final URLEntity[] urlEntities = bindingStatus.getURLEntities();
info.addAll(createURLSpanningInfo(text, urlEntities, quotedStatusIdStr));
final MediaEntity[] me = bindingStatus.getMediaEntities();
for (MediaEntity e : me) {
int start = text.indexOf(e.getURL());
int end = start + e.getURL().length();
if (isInvalidRange(text, start, end)) {
continue;
}
info.add(new SpanningInfo(null, start, end, ""));
}
return info;
}
private static List<SpanningInfo> createURLSpanningInfo(final String text,
URLEntity[] urlEntities,
@Nullable String quotedStatusIdStr) {
List<SpanningInfo> info = new ArrayList<>(urlEntities.length);
for (URLEntity u : urlEntities) {
int start = text.indexOf(u.getURL());
int end = start + u.getURL().length();
if (isInvalidRange(text, start, end)) {
if (TextUtils.isEmpty(u.getExpandedURL())) {
continue;
}
start = text.indexOf(u.getExpandedURL());
end = start + u.getExpandedURL().length();
if (isInvalidRange(text, start, end)) {
continue;
}
}
if (!TextUtils.isEmpty(quotedStatusIdStr)
&& u.getExpandedURL().contains(quotedStatusIdStr)) {
info.add(new SpanningInfo(null, start, end, ""));
}
info.add(new SpanningInfo(new URLSpan(u.getExpandedURL()), start, end, u.getDisplayURL()));
}
return info;
}
private static List<SpanningInfo> createUserSpanningInfo(Status bindingStatus) {
final String text = bindingStatus.getText();
final UserMentionEntity[] userMentionEntities = bindingStatus.getUserMentionEntities();
final List<SpanningInfo> info = new ArrayList<>();
for (UserMentionEntity u : userMentionEntities) {
final int start = text.indexOf("@" + u.getScreenName());
final int end = start + u.getScreenName().length() + 1;
if (isInvalidRange(text, start, end)) {
continue;
}
final long id = u.getId();
info.add(new SpanningInfo(new ClickableSpan() {
@Override
public void onClick(View view) {
UserInfoActivity.start(view.getContext(), id);
}
}, start, end, null));
}
return info;
}
private static boolean isInvalidRange(String text, int start, int end) {
return start < 0 || end > text.length() || start > text.length();
}
private static CharSequence createClickableSpan(String text, List<SpanningInfo> info) {
// to manipulate changing tweet text length, sort descending
SpannableStringBuilder ssb = new SpannableStringBuilder(text);
Collections.sort(info, new Comparator<SpanningInfo>() {
@Override
public int compare(SpanningInfo l, SpanningInfo r) {
return r.start - l.start;
}
});
for (SpanningInfo si : info) {
if (si.isSpanning()) {
ssb.setSpan(si.span, si.start, si.end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
if (si.isReplacing()) {
ssb.replace(si.start, si.end, si.displayingText);
}
}
return ssb;
}
/**
* SpanningInfo is information to create SpannableStringBuilder.
*
* Created by akihit on 2016/08/20.
*/
private static class SpanningInfo {
final ClickableSpan span;
final int start;
final int end;
final String displayingText;
SpanningInfo(@Nullable ClickableSpan span, int start, int end, @Nullable String displayingText) {
this.span = span != null ? new WatchedClickableSpan(span) : null;
this.start = start;
this.end = end;
this.displayingText = displayingText;
}
boolean isSpanning() {
return span != null;
}
boolean isReplacing() {
return displayingText != null;
}
}
private static class WatchedClickableSpan extends ClickableSpan implements SpanWatcher {
final String TAG = WatchedClickableSpan.class.getSimpleName();
final ClickableSpan clickableSpan;
private boolean selected = false;
WatchedClickableSpan(ClickableSpan clickableSpan) {
this.clickableSpan = clickableSpan;
}
@Override
public void onSpanAdded(Spannable text, Object what, int start, int end) {
// dependent internal logic of LinkMovementMethod.onTouchEvent()
if (what == Selection.SELECTION_START) {
selected = true;
}
}
@Override
public void onSpanRemoved(Spannable text, Object what, int start, int end) {
// dependent internal logic of LinkMovementMethod.onTouchEvent()
if (what == Selection.SELECTION_START) {
selected = false;
}
}
@Override
public void onClick(View widget) {
// dependent internal logic of LinkMovementMethod.onTouchEvent()
clickableSpan.onClick(widget);
if (widget instanceof TextView) {
Selection.removeSelection(((Spannable) ((TextView) widget).getText()));
}
}
@Override
public void updateDrawState(TextPaint ds) {
ds.bgColor = selected ? 0xffeeeeee : 0; // XXX
super.updateDrawState(ds);
}
@Override
public void onSpanChanged(Spannable text, Object what, int ostart, int oend, int nstart, int nend) {
}
}
}
| app/src/main/java/com/freshdigitable/udonroad/SpannableStringUtil.java | /*
* Copyright (c) 2016. Matsuda, Akihit (akihito104)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.freshdigitable.udonroad;
import android.support.annotation.Nullable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ClickableSpan;
import android.text.style.URLSpan;
import android.view.View;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import twitter4j.MediaEntity;
import twitter4j.Status;
import twitter4j.URLEntity;
import twitter4j.UserMentionEntity;
/**
* SpannableStringUtil creates clickable text.
*
* Created by akihit on 2016/10/08.
*/
class SpannableStringUtil {
static CharSequence create(Status bindingStatus) {
final List<SpanningInfo> spannableInfo = createSpanningInfo(bindingStatus);
return createClickableSpan(bindingStatus.getText(), spannableInfo);
}
static CharSequence create(final String text, URLEntity[] urlEntities) {
if (TextUtils.isEmpty(text)) {
return "";
}
final List<SpanningInfo> urlSpanningInfo = createURLSpanningInfo(text, urlEntities, null);
return createClickableSpan(text, urlSpanningInfo);
}
private static List<SpanningInfo> createSpanningInfo(Status bindingStatus) {
List<SpanningInfo> info = new ArrayList<>();
info.addAll(createURLSpanningInfo(bindingStatus));
info.addAll(createUserSpanningInfo(bindingStatus));
for (int i = info.size() - 1; i >= 0; i--) {
final SpanningInfo spanningInfo = info.get(i);
for (int j = 0; j < i; j++) {
if (spanningInfo.start == info.get(j).start) {
info.remove(spanningInfo);
break;
}
}
}
return info;
}
private static List<SpanningInfo> createURLSpanningInfo(Status bindingStatus) {
final String text = bindingStatus.getText();
final String quotedStatusIdStr = bindingStatus.getQuotedStatus() != null
? Long.toString(bindingStatus.getQuotedStatusId())
: "";
final List<SpanningInfo> info = new ArrayList<>();
final URLEntity[] urlEntities = bindingStatus.getURLEntities();
info.addAll(createURLSpanningInfo(text, urlEntities, quotedStatusIdStr));
final MediaEntity[] me = bindingStatus.getMediaEntities();
for (MediaEntity e : me) {
int start = text.indexOf(e.getURL());
int end = start + e.getURL().length();
if (isInvalidRange(text, start, end)) {
continue;
}
info.add(new SpanningInfo(null, start, end, ""));
}
return info;
}
private static List<SpanningInfo> createURLSpanningInfo(final String text,
URLEntity[] urlEntities,
@Nullable String quotedStatusIdStr) {
List<SpanningInfo> info = new ArrayList<>(urlEntities.length);
for (URLEntity u : urlEntities) {
int start = text.indexOf(u.getURL());
int end = start + u.getURL().length();
if (isInvalidRange(text, start, end)) {
if (TextUtils.isEmpty(u.getExpandedURL())) {
continue;
}
start = text.indexOf(u.getExpandedURL());
end = start + u.getExpandedURL().length();
if (isInvalidRange(text, start, end)) {
continue;
}
}
if (!TextUtils.isEmpty(quotedStatusIdStr)
&& u.getExpandedURL().contains(quotedStatusIdStr)) {
info.add(new SpanningInfo(null, start, end, ""));
}
info.add(new SpanningInfo(new URLSpan(u.getExpandedURL()), start, end, u.getDisplayURL()));
}
return info;
}
private static List<SpanningInfo> createUserSpanningInfo(Status bindingStatus) {
final String text = bindingStatus.getText();
final UserMentionEntity[] userMentionEntities = bindingStatus.getUserMentionEntities();
final List<SpanningInfo> info = new ArrayList<>();
for (UserMentionEntity u : userMentionEntities) {
final int start = text.indexOf("@" + u.getScreenName());
final int end = start + u.getScreenName().length() + 1;
if (isInvalidRange(text, start, end)) {
continue;
}
final long id = u.getId();
info.add(new SpanningInfo(new ClickableSpan() {
@Override
public void onClick(View view) {
UserInfoActivity.start(view.getContext(), id);
}
}, start, end, null));
}
return info;
}
private static boolean isInvalidRange(String text, int start, int end) {
return start < 0 || end > text.length() || start > text.length();
}
private static CharSequence createClickableSpan(String text, List<SpanningInfo> info) {
// to manipulate changing tweet text length, sort descending
SpannableStringBuilder ssb = new SpannableStringBuilder(text);
Collections.sort(info, new Comparator<SpanningInfo>() {
@Override
public int compare(SpanningInfo l, SpanningInfo r) {
return r.start - l.start;
}
});
for (SpanningInfo si : info) {
if (si.isSpanning()) {
ssb.setSpan(si.span, si.start, si.end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
if (si.isReplacing()) {
ssb.replace(si.start, si.end, si.displayingText);
}
}
return ssb;
}
/**
* SpanningInfo is information to create SpannableStringBuilder.
*
* Created by akihit on 2016/08/20.
*/
private static class SpanningInfo {
final ClickableSpan span;
final int start;
final int end;
final String displayingText;
SpanningInfo(@Nullable ClickableSpan span, int start, int end, @Nullable String displayingText) {
this.span = span;
this.start = start;
this.end = end;
this.displayingText = displayingText;
}
boolean isSpanning() {
return span != null;
}
boolean isReplacing() {
return displayingText != null;
}
}
}
| added feedback to be touched ClickableSpan (workaround)
| app/src/main/java/com/freshdigitable/udonroad/SpannableStringUtil.java | added feedback to be touched ClickableSpan (workaround) |
|
Java | apache-2.0 | 8ef09f0747f500c846877a347503971a8eb92058 | 0 | apixandru/rummikub-java,apixandru/rummikub-java,apixandru/rummikub-java | package com.github.apixandru.games.rummikub.ui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
import com.github.apixandru.games.rummikub.model.CardPile;
/**
* @author Alexandru-Constantin Bledea
* @since Oct 15, 2015
*/
public final class Main {
/**
* @param args
*/
public static void main(final String[] args) {
final JFrame frame = new JFrame();
frame.getContentPane().setPreferredSize(new Dimension(20 * 60, 7 * 96));
final JPanel grid = new JPanel();
final JLayeredPane layeredPane = frame.getLayeredPane();
layeredPane.add(grid, JLayeredPane.DEFAULT_LAYER);
final CardDndListener listener = new CardDndListener(new ComponentDragSource(grid));
layeredPane.addMouseListener(listener);
layeredPane.addMouseMotionListener(listener);
initializeGrid(grid, new CardPile());
frame.pack();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
/**
* @param contentToCenter
* @return
*/
private static JPanel centerHorizontally(final JPanel contentToCenter) {
final JPanel result = new JPanel();
result.setLayout(new BoxLayout(result, BoxLayout.X_AXIS));
result.add(Box.createHorizontalGlue());
result.add(contentToCenter);
result.add(Box.createHorizontalGlue());
return result;
}
/**
* @param grid
* @param cardPile
*/
private static void initializeGrid(final JPanel grid, final CardPile cardPile) {
final int rows = 7;
final int cols = 20;
grid.setLayout(new GridLayout(rows, cols));
grid.setSize(new Dimension(cols * 60, rows * 96));
boolean first = true;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
final JPanel square = new JPanel(new BorderLayout());
square.setBorder(new LineBorder(Color.LIGHT_GRAY));
grid.add(square);
if (first) {
first = false;
square.add(new CardUi(cardPile.nextCard()));
}
}
}
}
}
| src/main/java/com/github/apixandru/games/rummikub/ui/Main.java | package com.github.apixandru.games.rummikub.ui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
import com.github.apixandru.games.rummikub.model.CardPile;
/**
* @author Alexandru-Constantin Bledea
* @since Oct 15, 2015
*/
public final class Main {
/**
* @param args
*/
public static void main(final String[] args) {
final JFrame frame = new JFrame();
frame.getContentPane().setPreferredSize(new Dimension(20 * 60, 7 * 96));
final JPanel grid = new JPanel();
final JLayeredPane layeredPane = frame.getLayeredPane();
layeredPane.add(grid, JLayeredPane.DEFAULT_LAYER);
final CardDndListener listener = new CardDndListener(new ComponentDragSource(grid));
layeredPane.addMouseListener(listener);
layeredPane.addMouseMotionListener(listener);
initializeGrid(grid, new CardPile());
frame.pack();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
/**
* @param grid
* @param cardPile
*/
private static void initializeGrid(final JPanel grid, final CardPile cardPile) {
final int rows = 7;
final int cols = 20;
grid.setLayout(new GridLayout(rows, cols));
grid.setSize(new Dimension(cols * 60, rows * 96));
boolean first = true;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
final JPanel square = new JPanel(new BorderLayout());
square.setBorder(new LineBorder(Color.LIGHT_GRAY));
grid.add(square);
if (first) {
first = false;
square.add(new CardUi(cardPile.nextCard()));
}
}
}
}
}
| create helper to center horizontally
| src/main/java/com/github/apixandru/games/rummikub/ui/Main.java | create helper to center horizontally |
|
Java | bsd-3-clause | 9d9f9c096cb4b546bdbc49a0eaa43994b53df019 | 0 | ontodev/robot,ontodev/robot,ontodev/robot | package org.obolibrary.robot;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Execute collections of commands.
*
* @author <a href="mailto:[email protected]">James A. Overton</a>
*/
public class CommandManager implements Command {
/** Logger. */
private static final Logger logger = LoggerFactory.getLogger(CommandManager.class);
/** Namespace for error messages. */
private static final String NS = "errors#";
/** Error message when no command is provided. */
private static final String missingCommandError =
NS + "MISSING COMMAND ERROR no command provided";
/** Error message when the command provided is null. */
private static final String nullCommandError = NS + "MISSING COMMAND ERROR command is null: %s";
/** Error message when no options are provided for a command. */
private static final String noOptionsError =
NS + "OPTIONS ERROR no options provided for command: %s";
/** Error message when there is an unknown command provided. */
private static final String unknownArgError =
NS + "UNKNOWN ARG ERROR unknown command or option: %s";
/** Store the command-line options for the command. */
private Options globalOptions;
/** Store a map from command names to Command objects. */
private Map<String, Command> commands = new LinkedHashMap<String, Command>();
/** Initialze the command. */
public CommandManager() {
globalOptions = CommandLineHelper.getCommonOptions();
}
/**
* Name of the command.
*
* @return name
*/
public String getName() {
return "robot";
}
/**
* Brief description of the command.
*
* @return description
*/
public String getDescription() {
return "work with OWL ontologies";
}
/**
* Command-line usage for the command.
*
* @return usage
*/
public String getUsage() {
return "robot [command] [options] <arguments>";
}
/**
* Command-line options for the command.
*
* @return options
*/
public Options getOptions() {
return globalOptions;
}
/**
* Add a new command to this manager.
*
* @param commandName the of the command (one word)
* @param command the Command object to register
*/
public void addCommand(String commandName, Command command) {
commands.put(commandName, command);
}
/**
* Convenience method to convert from a List to an array.
*
* @param list a list of strings
* @return an array of strings
*/
private String[] asArgs(List<String> list) {
return list.toArray(new String[list.size()]);
}
/**
* Given some Options and some arguments, collect all the options until the first non-option
* argument, then remove those used argument strings from the arguments list and return the used
* arguments as a new list.
*
* @param options the options to collect
* @param arguments a list of remaining command-line arguments; used option strings are removed
* from this list
* @return the list of used argument strings
* @throws ParseException if command line cannot be parsed
*/
public List<String> getOptionArgs(Options options, List<String> arguments) throws ParseException {
// parse all options until a non-option is found
CommandLineParser parser = new PosixParser();
CommandLine line = parser.parse(options, asArgs(arguments), true);
int index = arguments.size() - line.getArgList().size();
List<String> used = new ArrayList<String>(arguments.subList(0, index));
arguments.subList(0, index).clear();
return used;
}
/**
* Given command-line arguments, execute one or more commands.
*
* @param args the command line arguments
*/
public void main(String[] args) {
try {
execute(null, args);
} catch (Exception e) {
ExceptionHelper.handleException(e);
printHelp();
System.exit(1);
}
}
/**
* Given an input state and command-line arguments, execute one or more commands.
*
* @param state an state to work with, or null
* @param args the command-line arguments
* @return the result state of the last subcommand or null on bad input
* @throws Exception on any problems
*/
public CommandState execute(CommandState state, String[] args) throws Exception {
CommandLine line = CommandLineHelper.maybeGetCommandLine(getUsage(), getOptions(), args, true);
if (line == null) {
return null;
}
if (state == null) {
state = new CommandState();
}
List<String> arguments = new ArrayList<String>(Arrays.asList(args));
if (arguments.size() == 0) {
throw new IllegalArgumentException(missingCommandError);
}
List<String> globalOptionArgs = getOptionArgs(globalOptions, arguments);
while (arguments.size() > 0) {
state = executeCommand(state, globalOptionArgs, arguments);
}
return state;
}
/**
* Given an input state, global option strings, and remaining command-line argument strings, use
* as many arguments as needed to execute a single command. The arguments used by the command are
* removed from the arguments list, which can then be used to execute further commands.
*
* @param state the state from the previous command, or null
* @param globalOptionArgs a list of global option strings
* @param arguments the list of remaining command-line arguments; any arguments that are used will
* be removed from this list
* @return the state that results from this command
* @throws Exception on any problems
*/
public CommandState executeCommand(
CommandState state, List<String> globalOptionArgs, List<String> arguments) throws Exception {
String commandName = null;
if (arguments.size() > 0) {
commandName = arguments.remove(0);
}
if (commandName == null) {
throw new IllegalArgumentException(missingCommandError);
}
commandName = commandName.trim().toLowerCase();
if (commandName.equals("help")) {
if (arguments.size() == 0) {
printHelp();
} else {
globalOptionArgs.add("--help");
}
return state;
}
if (commandName.equals("version")) {
CommandLineHelper.printVersion();
return state;
}
if (!commands.containsKey(commandName)) {
throw new IllegalArgumentException(String.format(unknownArgError, commandName));
}
Command command = commands.get(commandName);
if (command == null) {
throw new IllegalArgumentException(String.format(nullCommandError, commandName));
}
if (command.getOptions() == null) {
throw new IllegalArgumentException(String.format(noOptionsError, commandName));
}
List<String> localOptionArgs = getOptionArgs(command.getOptions(), arguments);
List<String> optionArgs = new ArrayList<String>();
optionArgs.addAll(globalOptionArgs);
optionArgs.addAll(localOptionArgs);
// Check to make sure the next provided arg is a valid command after parsing Option Args
if (!arguments.isEmpty()) {
String nextArg = arguments.get(0);
if (!commands.keySet().contains(nextArg)) {
throw new IllegalArgumentException(String.format(unknownArgError, nextArg));
}
}
long start = System.currentTimeMillis();
try {
state = command.execute(state, asArgs(optionArgs));
} catch (Exception e) {
// Ensure command-specific usage info is returned
CommandLineHelper.handleException(command.getUsage(), command.getOptions(), e);
} finally {
double duration = (System.currentTimeMillis() - start) / 1000.0;
logger.warn("Subcommand Timing: " + commandName + " took " + duration + " seconds");
}
return state;
}
/** Print general help plus a list of available commands. */
public void printHelp() {
CommandLineHelper.printHelp(getUsage(), getOptions());
System.out.println("commands:");
printHelpEntry("help", "print help for command");
for (Map.Entry<String, Command> entry : commands.entrySet()) {
printHelpEntry(entry);
}
}
/**
* Print a help entry for a single command.
*
* @param entry an entry from the map of commands
*/
public void printHelpEntry(Map.Entry<String, Command> entry) {
printHelpEntry(entry.getKey(), entry.getValue().getDescription());
}
/**
* Print a help entry for a single command.
*
* @param name the name of the command
* @param description a brief description of the command
*/
public void printHelpEntry(String name, String description) {
System.out.println(String.format(" %-16s %s", name, description));
}
}
| robot-command/src/main/java/org/obolibrary/robot/CommandManager.java | package org.obolibrary.robot;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Execute collections of commands.
*
* @author <a href="mailto:[email protected]">James A. Overton</a>
*/
public class CommandManager implements Command {
/** Logger. */
private static final Logger logger = LoggerFactory.getLogger(CommandManager.class);
/** Namespace for error messages. */
private static final String NS = "errors#";
/** Error message when no command is provided. */
private static final String missingCommandError =
NS + "MISSING COMMAND ERROR no command provided";
/** Error message when the command provided is null. */
private static final String nullCommandError = NS + "MISSING COMMAND ERROR command is null: %s";
/** Error message when no options are provided for a command. */
private static final String noOptionsError =
NS + "OPTIONS ERROR no options provided for command: %s";
/** Error message when there is an unknown command provided. */
private static final String unknownArgError =
NS + "UNKNOWN ARG ERROR unknown command or option: %s";
/** Store the command-line options for the command. */
private Options globalOptions;
/** Store a map from command names to Command objects. */
private Map<String, Command> commands = new LinkedHashMap<String, Command>();
/** Initialze the command. */
public CommandManager() {
globalOptions = CommandLineHelper.getCommonOptions();
}
/**
* Name of the command.
*
* @return name
*/
public String getName() {
return "robot";
}
/**
* Brief description of the command.
*
* @return description
*/
public String getDescription() {
return "work with OWL ontologies";
}
/**
* Command-line usage for the command.
*
* @return usage
*/
public String getUsage() {
return "robot [command] [options] <arguments>";
}
/**
* Command-line options for the command.
*
* @return options
*/
public Options getOptions() {
return globalOptions;
}
/**
* Add a new command to this manager.
*
* @param commandName the of the command (one word)
* @param command the Command object to register
*/
public void addCommand(String commandName, Command command) {
commands.put(commandName, command);
}
/**
* Convenience method to convert from a List to an array.
*
* @param list a list of strings
* @return an array of strings
*/
private String[] asArgs(List<String> list) {
return list.toArray(new String[list.size()]);
}
/**
* Given some Options and some arguments, collect all the options until the first non-option
* argument, then remove those used argument strings from the arguments list and return the used
* arguments as a new list.
*
* @param options the options to collect
* @param arguments a list of remaining command-line arguments; used option strings are removed
* from this list
* @return the list of used argument strings
* @throws ParseException if command line cannot be parsed
*/
public List<String> getOptionArgs(Options options, List<String> arguments) throws ParseException {
// parse all options until a non-option is found
CommandLineParser parser = new PosixParser();
CommandLine line = parser.parse(options, asArgs(arguments), true);
int index = arguments.size() - line.getArgList().size();
List<String> used = new ArrayList<String>(arguments.subList(0, index));
arguments.subList(0, index).clear();
return used;
}
/**
* Given command-line arguments, execute one or more commands.
*
* @param args the command line arguments
*/
public void main(String[] args) {
try {
execute(null, args);
} catch (Exception e) {
ExceptionHelper.handleException(e);
printHelp();
System.exit(1);
}
}
/**
* Given an input state and command-line arguments, execute one or more commands.
*
* @param state an state to work with, or null
* @param args the command-line arguments
* @return the result state of the last subcommand or null on bad input
* @throws Exception on any problems
*/
public CommandState execute(CommandState state, String[] args) throws Exception {
CommandLine line = CommandLineHelper.maybeGetCommandLine(getUsage(), getOptions(), args, true);
if (line == null) {
return null;
}
if (state == null) {
state = new CommandState();
}
List<String> arguments = new ArrayList<String>(Arrays.asList(args));
if (arguments.size() == 0) {
throw new IllegalArgumentException(missingCommandError);
}
List<String> globalOptionArgs = getOptionArgs(globalOptions, arguments);
while (arguments.size() > 0) {
state = executeCommand(state, globalOptionArgs, arguments);
}
return state;
}
/**
* Given an input state, global option strings, and remaining command-line argument strings, use
* as many arguments as needed to execute a single command. The arguments used by the command are
* removed from the arguments list, which can then be used to execute further commands.
*
* @param state the state from the previous command, or null
* @param globalOptionArgs a list of global option strings
* @param arguments the list of remaining command-line arguments; any arguments that are used will
* be removed from this list
* @return the state that results from this command
* @throws Exception on any problems
*/
public CommandState executeCommand(
CommandState state, List<String> globalOptionArgs, List<String> arguments) throws Exception {
String commandName = null;
if (arguments.size() > 0) {
commandName = arguments.remove(0);
}
if (commandName == null) {
throw new IllegalArgumentException(missingCommandError);
}
commandName = commandName.trim().toLowerCase();
if (commandName.equals("help")) {
if (arguments.size() == 0) {
printHelp();
} else {
globalOptionArgs.add("--help");
}
return state;
}
if (commandName.equals("version")) {
CommandLineHelper.printVersion();
return state;
}
if (!commands.containsKey(commandName)) {
throw new IllegalArgumentException(String.format(unknownArgError, commandName));
}
Command command = commands.get(commandName);
if (command == null) {
throw new IllegalArgumentException(String.format(nullCommandError, commandName));
}
if (command.getOptions() == null) {
throw new IllegalArgumentException(String.format(noOptionsError, commandName));
}
List<String> localOptionArgs = getOptionArgs(command.getOptions(), arguments);
List<String> optionArgs = new ArrayList<String>();
optionArgs.addAll(globalOptionArgs);
optionArgs.addAll(localOptionArgs);
// Check to make sure the next provided arg is a valid command after parsing Option Args
if (!arguments.isEmpty()) {
String nextArg = arguments.get(0);
if (!commands.keySet().contains(nextArg)) {
throw new IllegalArgumentException(String.format(unknownArgError, nextArg));
}
}
long start = System.currentTimeMillis();
try {
state = command.execute(state, asArgs(optionArgs));
} catch (Exception e) {
// Ensure command-specific usage info is returned
CommandLineHelper.handleException(command.getUsage(), command.getOptions(), e);
} finally {
double duration = (System.currentTimeMillis() - start) / 1000.0;
System.out.println(commandName + " took " + duration + " seconds");
}
return state;
}
/** Print general help plus a list of available commands. */
public void printHelp() {
CommandLineHelper.printHelp(getUsage(), getOptions());
System.out.println("commands:");
printHelpEntry("help", "print help for command");
for (Map.Entry<String, Command> entry : commands.entrySet()) {
printHelpEntry(entry);
}
}
/**
* Print a help entry for a single command.
*
* @param entry an entry from the map of commands
*/
public void printHelpEntry(Map.Entry<String, Command> entry) {
printHelpEntry(entry.getKey(), entry.getValue().getDescription());
}
/**
* Print a help entry for a single command.
*
* @param name the name of the command
* @param description a brief description of the command
*/
public void printHelpEntry(String name, String description) {
System.out.println(String.format(" %-16s %s", name, description));
}
}
| using logger and string Subcommand Timing to find the messages
| robot-command/src/main/java/org/obolibrary/robot/CommandManager.java | using logger and string Subcommand Timing to find the messages |
|
Java | bsd-3-clause | 92fe1a4bf9affe4aff688dfda875968cf5af8e2a | 0 | variflight/feeyo-redisproxy,variflight/feeyo-redisproxy | package com.feeyo.redis.net.backend.callback;
import java.io.IOException;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.feeyo.net.codec.redis.RedisResponse;
import com.feeyo.net.codec.redis.RedisResponseDecoderV2;
import com.feeyo.net.nio.util.TimeUtil;
import com.feeyo.redis.engine.manage.stat.StatUtil;
import com.feeyo.redis.net.backend.BackendConnection;
import com.feeyo.redis.net.front.RedisFrontConnection;
/**
* direct transfer bakend data to front connection must attach (setAttachement)
* front connection on backend connection
*
* @author zhuam
*
*/
public class DirectTransTofrontCallBack extends AbstractBackendCallback {
private static Logger LOGGER = LoggerFactory.getLogger( DirectTransTofrontCallBack.class );
protected RedisResponseDecoderV2 decoder = new RedisResponseDecoderV2();
// 写入到前端
protected int writeToFront(RedisFrontConnection frontCon, RedisResponse response, int size) throws IOException {
int tmpSize = size;
if ( frontCon.isClosed() ) {
throw new IOException("front conn is closed!");
}
if ( response.type() == '+'
|| response.type() == '-'
|| response.type() == ':'
|| response.type() == '$') {
byte[] buf = (byte[])response.data() ;
tmpSize += buf.length;
frontCon.write( buf );
// fast GC
response.clear();
} else {
if ( response.data() instanceof byte[] ) {
byte[] buf = (byte[])response.data() ;
tmpSize += buf.length;
frontCon.write( buf );
// fast GC
response.clear();
} else {
RedisResponse[] items = (RedisResponse[]) response.data();
for(int i = 0; i < items.length; i++) {
if ( i == 0 ) {
byte[] buf = (byte[])items[i].data() ;
tmpSize += buf.length;
frontCon.write( buf );
// fast GC
response.clear();
} else {
tmpSize = writeToFront(frontCon, items[i], tmpSize);
}
}
}
}
return tmpSize;
}
// 写入到前端
protected int writeToFront(RedisFrontConnection frontCon, byte[] response, int size) throws IOException {
int tmpSize = size;
if (frontCon.isClosed()) {
throw new IOException("front conn is closed!");
}
tmpSize += response.length;
frontCon.write(response);
// fast GC
response = null;
return tmpSize;
}
@Override
public void handleResponse(BackendConnection backendCon, byte[] byteBuff) throws IOException {
// 应答解析
List<RedisResponse> resps = decoder.decode( byteBuff );
if ( resps != null ) {
// 获取前端 connection
// --------------------------------------------------------------
RedisFrontConnection frontCon = getFrontCon( backendCon );
try {
String password = frontCon.getPassword();
String cmd = frontCon.getSession().getRequestCmd();
String key = frontCon.getSession().getRequestKey();
int requestSize = frontCon.getSession().getRequestSize();
long requestTimeMills = frontCon.getSession().getRequestTimeMills();
long responseTimeMills = TimeUtil.currentTimeMillis();
int responseSize = 0;
for(RedisResponse resp: resps)
responseSize += this.writeToFront(frontCon, resp, 0);
resps.clear(); // help GC
resps = null;
int procTimeMills = (int)(responseTimeMills - requestTimeMills);
int backendWaitTimeMills = (int)(backendCon.getLastReadTime() - backendCon.getLastWriteTime());
// 后段链接释放
backendCon.release();
// 数据收集
StatUtil.collect(password, cmd, key, requestSize, responseSize, procTimeMills, backendWaitTimeMills, false, false);
} catch(IOException e2) {
if ( frontCon != null) {
frontCon.close("write err");
}
long backId = backendCon != null ? backendCon.getId() : -1;
LOGGER.error("backend write to front err, back id=" + backId , e2);
// 由 reactor close
throw e2;
}
}
}
} | src/main/java/com/feeyo/redis/net/backend/callback/DirectTransTofrontCallBack.java | package com.feeyo.redis.net.backend.callback;
import java.io.IOException;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.feeyo.net.codec.redis.RedisResponse;
import com.feeyo.net.codec.redis.RedisResponseDecoderV2;
import com.feeyo.net.nio.util.TimeUtil;
import com.feeyo.redis.engine.manage.stat.StatUtil;
import com.feeyo.redis.net.backend.BackendConnection;
import com.feeyo.redis.net.front.RedisFrontConnection;
/**
* direct transfer bakend data to front connection must attach (setAttachement)
* front connection on backend connection
*
* @author zhuam
*
*/
public class DirectTransTofrontCallBack extends AbstractBackendCallback {
private static Logger LOGGER = LoggerFactory.getLogger( DirectTransTofrontCallBack.class );
protected RedisResponseDecoderV2 decoder = new RedisResponseDecoderV2();
// 写入到前端
protected int writeToFront(RedisFrontConnection frontCon, RedisResponse response, int size) throws IOException {
int tmpSize = size;
if ( frontCon.isClosed() ) {
throw new IOException("front conn is closed!");
}
if ( response.type() == '+'
|| response.type() == '-'
|| response.type() == ':'
|| response.type() == '$') {
byte[] buf = (byte[])response.data() ;
tmpSize += buf.length;
frontCon.write( buf );
// fast GC
response.clear();
} else {
if ( response.data() instanceof byte[] ) {
byte[] buf = (byte[])response.data() ;
tmpSize += buf.length;
frontCon.write( buf );
// fast GC
response.clear();
} else {
RedisResponse[] items = (RedisResponse[]) response.data();
for(int i = 0; i < items.length; i++) {
if ( i == 0 ) {
byte[] buf = (byte[])items[i].data() ;
tmpSize += buf.length;
frontCon.write( buf );
// fast GC
response.clear();
} else {
tmpSize = writeToFront(frontCon, items[i], tmpSize);
}
}
}
}
return tmpSize;
}
// 写入到前端
protected int writeToFront(RedisFrontConnection frontCon, byte[] response, int size) throws IOException {
int tmpSize = size;
if (frontCon.isClosed()) {
throw new IOException("front conn is closed!");
}
tmpSize += response.length;
frontCon.write(response);
// fast GC
response = null;
return tmpSize;
}
@Override
public void handleResponse(BackendConnection backendCon, byte[] byteBuff) throws IOException {
// 应答解析
List<RedisResponse> resps = decoder.decode( byteBuff );
if ( resps != null ) {
// 获取前端 connection
// --------------------------------------------------------------
RedisFrontConnection frontCon = getFrontCon( backendCon );
try {
String password = frontCon.getPassword();
String cmd = frontCon.getSession().getRequestCmd();
String key = frontCon.getSession().getRequestKey();
int requestSize = frontCon.getSession().getRequestSize();
long requestTimeMills = frontCon.getSession().getRequestTimeMills();
long responseTimeMills = TimeUtil.currentTimeMillis();
int responseSize = 0;
for(RedisResponse resp: resps)
responseSize += this.writeToFront(frontCon, resp, 0);
resps.clear(); // help GC
resps = null;
int procTimeMills = (int)(responseTimeMills - requestTimeMills);
int backendWaitTimeMills = (int)(backendCon.getLastReadTime() - backendCon.getLastWriteTime());
// 后段链接释放
backendCon.release();
// 数据收集
StatUtil.collect(password, cmd, key, requestSize, responseSize, procTimeMills, backendWaitTimeMills, false, false);
} catch(IOException e2) {
if ( frontCon != null) {
frontCon.close("write err");
}
// 由 reactor close
LOGGER.error("backend write to front err:", e2);
throw e2;
}
}
}
} | 增加 backId 便于定位问题 | src/main/java/com/feeyo/redis/net/backend/callback/DirectTransTofrontCallBack.java | 增加 backId 便于定位问题 |
|
Java | mit | 08be8eb4f8ae4b202c7ab74de51958c632a13223 | 0 | pomes/github-api,marc-guenther/github-api,mmitche/github-api,Shredder121/github-api,kohsuke/github-api,stephenc/github-api,PankajHingane-REISysIn/KnowledgeArticleExportImport,jeffnelson/github-api,recena/github-api | package org.kohsuke.github;
import org.junit.After;
import org.junit.Test;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
/**
* @author Kohsuke Kawaguchi
*/
public class PullRequestTest extends AbstractGitHubApiTestBase {
@Test
public void createPullRequest() throws Exception {
String name = rnd.next();
GHPullRequest p = getRepository().createPullRequest(name, "stable", "master", "## test");
System.out.println(p.getUrl());
assertEquals(name, p.getTitle());
}
@Test
public void createPullRequestComment() throws Exception {
String name = rnd.next();
GHPullRequest p = getRepository().createPullRequest(name, "stable", "master", "## test");
p.comment("Some comment");
}
@Test
public void testPullRequestReviewComments() throws Exception {
String name = rnd.next();
GHPullRequest p = getRepository().createPullRequest(name, "stable", "master", "## test");
System.out.println(p.getUrl());
assertTrue(p.listReviewComments().asList().isEmpty());
p.createReviewComment("Sample review comment", p.getHead().getSha(), "cli/pom.xml", 5);
List<GHPullRequestReviewComment> comments = p.listReviewComments().asList();
assertEquals(1, comments.size());
GHPullRequestReviewComment comment = comments.get(0);
assertEquals("Sample review comment", comment.getBody());
comment.update("Updated review comment");
comments = p.listReviewComments().asList();
assertEquals(1, comments.size());
comment = comments.get(0);
assertEquals("Updated review comment", comment.getBody());
comment.delete();
comments = p.listReviewComments().asList();
assertTrue(comments.isEmpty());
}
@Test
public void testMergeCommitSHA() throws Exception {
String name = rnd.next();
GHPullRequest p = getRepository().createPullRequest(name, "stable", "master", "## test");
GHPullRequest updated = getRepository().getPullRequest(p.getNumber());
GHCommit commit = getRepository().getCommit(updated.getMergeCommitSha());
assertNotNull(commit);
}
@Test
// Requires push access to the test repo to pass
public void setLabels() throws Exception {
GHPullRequest p = getRepository().createPullRequest(rnd.next(), "stable", "master", "## test");
String label = rnd.next();
p.setLabels(label);
Collection<GHLabel> labels = getRepository().getPullRequest(p.getNumber()).getLabels();
assertEquals(1, labels.size());
assertEquals(label, labels.iterator().next().getName());
}
@Test
// Requires push access to the test repo to pass
public void setAssignee() throws Exception {
GHPullRequest p = getRepository().createPullRequest(rnd.next(), "stable", "master", "## test");
GHMyself user = gitHub.getMyself();
p.assignTo(user);
assertEquals(user, getRepository().getPullRequest(p.getNumber()).getAssignee());
}
@Test
public void testGetUser() throws IOException {
GHPullRequest p = getRepository().createPullRequest(rnd.next(), "stable", "master", "## test");
GHPullRequest prSingle = getRepository().getPullRequest(p.getNumber());
assertNotNull(prSingle.getUser().root);
prSingle.getMergeable();
assertNotNull(prSingle.getUser().root);
PagedIterable<GHPullRequest> ghPullRequests = getRepository().listPullRequests(GHIssueState.OPEN);
for (GHPullRequest pr : ghPullRequests) {
assertNotNull(pr.getUser().root);
pr.getMergeable();
assertNotNull(pr.getUser().root);
}
}
@After
public void cleanUp() throws Exception {
for (GHPullRequest pr : getRepository().getPullRequests(GHIssueState.OPEN)) {
pr.close();
}
}
private GHRepository getRepository() throws IOException {
return gitHub.getOrganization("github-api-test-org").getRepository("jenkins");
}
}
| src/test/java/org/kohsuke/github/PullRequestTest.java | package org.kohsuke.github;
import org.junit.After;
import org.junit.Test;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
/**
* @author Kohsuke Kawaguchi
*/
public class PullRequestTest extends AbstractGitHubApiTestBase {
@Test
public void createPullRequest() throws Exception {
String name = rnd.next();
GHPullRequest p = getRepository().createPullRequest(name, "stable", "master", "## test");
System.out.println(p.getUrl());
assertEquals(name, p.getTitle());
}
@Test
public void createPullRequestComment() throws Exception {
String name = rnd.next();
GHPullRequest p = getRepository().createPullRequest(name, "stable", "master", "## test");
p.comment("Some comment");
}
@Test
public void testPullRequestReviewComments() throws Exception {
String name = rnd.next();
GHPullRequest p = getRepository().createPullRequest(name, "stable", "master", "## test");
System.out.println(p.getUrl());
assertTrue(p.listReviewComments().asList().isEmpty());
p.createReviewComment("Sample review comment", p.getHead().getSha(), "cli/pom.xml", 5);
List<GHPullRequestReviewComment> comments = p.listReviewComments().asList();
assertEquals(1, comments.size());
GHPullRequestReviewComment comment = comments.get(0);
assertEquals("Sample review comment", comment.getBody());
comment.update("Updated review comment");
comments = p.listReviewComments().asList();
assertEquals(1, comments.size());
comment = comments.get(0);
assertEquals("Updated review comment", comment.getBody());
comment.delete();
comments = p.listReviewComments().asList();
assertTrue(comments.isEmpty());
}
@Test
public void testMergeCommitSHA() throws Exception {
String name = rnd.next();
GHRepository repo = gitHub.getMyself().getRepository("website");
GHPullRequest p = repo.createPullRequest(name, "feature5", "master", "## test");
GHRef ref = repo.getRef("pull/" + p.getNumber() + "/merge");
assertTrue(ref.getObject().getSha() == p.getMergeCommitSha());
}
@Test
// Requires push access to the test repo to pass
public void setLabels() throws Exception {
GHPullRequest p = getRepository().createPullRequest(rnd.next(), "stable", "master", "## test");
String label = rnd.next();
p.setLabels(label);
Collection<GHLabel> labels = getRepository().getPullRequest(p.getNumber()).getLabels();
assertEquals(1, labels.size());
assertEquals(label, labels.iterator().next().getName());
}
@Test
// Requires push access to the test repo to pass
public void setAssignee() throws Exception {
GHPullRequest p = getRepository().createPullRequest(rnd.next(), "stable", "master", "## test");
GHMyself user = gitHub.getMyself();
p.assignTo(user);
assertEquals(user, getRepository().getPullRequest(p.getNumber()).getAssignee());
}
@Test
public void testGetUser() throws IOException {
GHPullRequest p = getRepository().createPullRequest(rnd.next(), "stable", "master", "## test");
GHPullRequest prSingle = getRepository().getPullRequest(p.getNumber());
assertNotNull(prSingle.getUser().root);
prSingle.getMergeable();
assertNotNull(prSingle.getUser().root);
PagedIterable<GHPullRequest> ghPullRequests = getRepository().listPullRequests(GHIssueState.OPEN);
for (GHPullRequest pr : ghPullRequests) {
assertNotNull(pr.getUser().root);
pr.getMergeable();
assertNotNull(pr.getUser().root);
}
}
@After
public void cleanUp() throws Exception {
for (GHPullRequest pr : getRepository().getPullRequests(GHIssueState.OPEN)) {
pr.close();
}
}
private GHRepository getRepository() throws IOException {
return gitHub.getOrganization("github-api-test-org").getRepository("jenkins");
}
}
| Added a new test testMergeCommitSHA()
| src/test/java/org/kohsuke/github/PullRequestTest.java | Added a new test testMergeCommitSHA() |
|
Java | mit | 71f83c621fd0e851a32129f233ac09890521dfb2 | 0 | fenfir/mtg-familiar,fenfir/mtg-familiar,fenfir/mtg-familiar | /**
* Copyright 2011 Adam Feinstein
* <p/>
* This file is part of MTG Familiar.
* <p/>
* MTG Familiar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* <p/>
* MTG Familiar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p/>
* You should have received a copy of the GNU General Public License
* along with MTG Familiar. If not, see <http://www.gnu.org/licenses/>.
*/
package com.gelakinetic.mtgfam.fragments;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipDescription;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.Rect;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.text.method.LinkMovementMethod;
import android.util.TypedValue;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import com.alertdialogpro.AlertDialogPro;
import com.gelakinetic.mtgfam.FamiliarActivity;
import com.gelakinetic.mtgfam.R;
import com.gelakinetic.mtgfam.helpers.ImageGetterHelper;
import com.gelakinetic.mtgfam.helpers.PriceFetchRequest;
import com.gelakinetic.mtgfam.helpers.PriceInfo;
import com.gelakinetic.mtgfam.helpers.ToastWrapper;
import com.gelakinetic.mtgfam.helpers.WishlistHelpers;
import com.gelakinetic.mtgfam.helpers.database.CardDbAdapter;
import com.gelakinetic.mtgfam.helpers.database.DatabaseManager;
import com.gelakinetic.mtgfam.helpers.database.FamiliarDbException;
import com.gelakinetic.mtgfam.helpers.lruCache.RecyclingBitmapDrawable;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.octo.android.robospice.persistence.DurationInMillis;
import com.octo.android.robospice.persistence.exception.SpiceException;
import com.octo.android.robospice.request.listener.RequestListener;
import org.jetbrains.annotations.NotNull;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
/**
* This class handles displaying card info
* WARNING! Because this fragment is nested in a CardViewPagerFragment, always get the parent fragment's activity
*/
public class CardViewFragment extends FamiliarFragment {
/* Bundle constant */
public static final String CARD_ID = "card_id";
/* Dialogs */
private static final int GET_PRICE = 1;
private static final int GET_IMAGE = 2;
private static final int CHANGE_SET = 3;
private static final int CARD_RULINGS = 4;
private static final int WISH_LIST_COUNTS = 6;
private static final int GET_LEGALITY = 7;
/* Where the card image is loaded to */
private static final int MAIN_PAGE = 1;
private static final int DIALOG = 2;
private int loadTo = DIALOG; /* where to load the image */
/* Used to store the String when copying to clipboard */
private String mCopyString;
/* UI elements, to be filled in */
private TextView mNameTextView;
private TextView mCostTextView;
private TextView mTypeTextView;
private TextView mSetTextView;
private TextView mAbilityTextView;
private TextView mPowTouTextView;
private TextView mFlavorTextView;
private TextView mArtistTextView;
private Button mTransformButton;
private View mTransformButtonDivider;
private ImageView mCardImageView;
private ScrollView mTextScrollView;
private ScrollView mImageScrollView;
/* the AsyncTask loads stuff off the UI thread, and stores whatever in these local variables */
private AsyncTask<Void, Void, Void> mAsyncTask;
private RecyclingBitmapDrawable mCardBitmap;
private String[] mLegalities;
private String[] mFormats;
private ArrayList<Ruling> mRulingsArrayList;
/* Loaded in a Spice Service */
private PriceInfo mPriceInfo;
/* Card info, used to build the URL to fetch the picture */
private String mCardNumber;
private String mSetCode;
private String mCardName;
private String mMagicCardsInfoSetCode;
private int mMultiverseId;
private String mCardType;
/* Card info used to flip the card */
private String mTransformCardNumber;
private int mTransformId;
/* To switch card between printings */
private LinkedHashSet<String> mSets;
private LinkedHashSet<Long> mCardIds;
/* Easier than calling getActivity() all the time, and handles being nested */
private FamiliarActivity mActivity;
/* State for reporting page views */
private boolean mHasReportedView = false;
private boolean mShouldReportView = false;
private String mDescription;
private String mSetName;
/**
* Kill any AsyncTask if it is still running
*/
@Override
public void onDestroy() {
super.onDestroy();
/* Pass a non-null bundle to the ResultListFragment so it knows to exit if there was a list of 1 card
* If this wasn't launched by a ResultListFragment, it'll get eaten */
Bundle args = new Bundle();
mActivity.setFragmentResult(args);
}
/**
* Called when the Fragment is no longer resumed. Clear the loading bar just in case
*/
@Override
public void onPause() {
super.onPause();
mActivity.clearLoading();
if (mAsyncTask != null) {
mAsyncTask.cancel(true);
}
}
/**
* Called when the fragment stops, attempt to report the close
*/
@Override
public void onStop() {
reportAppIndexEndIfAble();
super.onStop();
}
/**
* Creates and returns the action describing this page view
*
* @return An action describing this page view
*/
private Action getAppIndexAction() {
Thing object = new Thing.Builder()
.setType("http://schema.org/Thing") /* Optional, any valid schema.org type */
.setName(mCardName + " (" + mSetName + ")") /* Required, title field */
.setDescription(mDescription) /* Required, description field */
/* Required, deep link in the android-app:// format */
.setUrl(Uri.parse("android-app://com.gelakinetic.mtgfam/card/multiverseid/" + mMultiverseId))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.build();
}
/**
* Reports this view to the Google app indexing API, once, when the fragment is viewed
*/
private void reportAppIndexViewIfAble() {
/* If this view hasn't been reported yet, and the name exists */
if (!mHasReportedView) {
if (mCardName != null) {
/* Connect your client */
getFamiliarActivity().mGoogleApiClient.connect();
AppIndex.AppIndexApi.start(getFamiliarActivity().mGoogleApiClient, getAppIndexAction());
/* Manage state */
mHasReportedView = true;
mShouldReportView = false;
} else {
mShouldReportView = true;
}
}
}
/**
* Ends the report to the Google app indexing API, once, when the fragment is no longer viewed
*/
private void reportAppIndexEndIfAble() {
/* If the view was previously reported, and the name exists */
if (mHasReportedView && mCardName != null) {
/* Call end() and disconnect the client */
AppIndex.AppIndexApi.end(getFamiliarActivity().mGoogleApiClient, getAppIndexAction());
getFamiliarActivity().mGoogleApiClient.disconnect();
/* manage state */
mHasReportedView = false;
}
}
/**
* Set a hint to the system about whether this fragment's UI is currently visible to the user.
* This hint defaults to true and is persistent across fragment instance state save and restore.
* <p/>
* An app may set this to false to indicate that the fragment's UI is scrolled out of visibility
* or is otherwise not directly visible to the user. This may be used by the system to
* prioritize operations such as fragment lifecycle updates or loader ordering behavior.
* <p/>
* In this case, it's used to report fragment views to Google app indexing
*
* @param isVisibleToUser true if this fragment's UI is currently visible to the user (default),
* false if it is not.
*/
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
/* If the fragment is visible to the user, attempt to report the view */
reportAppIndexViewIfAble();
} else {
/* The view isn't visible anymore, attempt to report it */
reportAppIndexEndIfAble();
}
}
/**
* Inflates the view and saves references to UI elements for later filling
*
* @param savedInstanceState If non-null, this fragment is being re-constructed from a previous saved state as given
* here.
* @param inflater The LayoutInflater object that can be used to inflate any views in the fragment,
* @param container If non-null, this is the parent view that the fragment's UI should be attached to. The
* fragment should not add the view itself, but this can be used to generate the
* LayoutParams of the view.
* @return The inflated view
*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
try {
mActivity = ((FamiliarFragment) getParentFragment()).getFamiliarActivity();
} catch (NullPointerException e) {
mActivity = getFamiliarActivity();
}
View myFragmentView = inflater.inflate(R.layout.card_view_frag, container, false);
assert myFragmentView != null; /* Because Android Studio */
mNameTextView = (TextView) myFragmentView.findViewById(R.id.name);
mCostTextView = (TextView) myFragmentView.findViewById(R.id.cost);
mTypeTextView = (TextView) myFragmentView.findViewById(R.id.type);
mSetTextView = (TextView) myFragmentView.findViewById(R.id.set);
mAbilityTextView = (TextView) myFragmentView.findViewById(R.id.ability);
mFlavorTextView = (TextView) myFragmentView.findViewById(R.id.flavor);
mArtistTextView = (TextView) myFragmentView.findViewById(R.id.artist);
mPowTouTextView = (TextView) myFragmentView.findViewById(R.id.pt);
mTransformButtonDivider = myFragmentView.findViewById(R.id.transform_button_divider);
mTransformButton = (Button) myFragmentView.findViewById(R.id.transformbutton);
mTextScrollView = (ScrollView) myFragmentView.findViewById(R.id.cardTextScrollView);
mImageScrollView = (ScrollView) myFragmentView.findViewById(R.id.cardImageScrollView);
mCardImageView = (ImageView) myFragmentView.findViewById(R.id.cardpic);
registerForContextMenu(mNameTextView);
registerForContextMenu(mCostTextView);
registerForContextMenu(mTypeTextView);
registerForContextMenu(mSetTextView);
registerForContextMenu(mAbilityTextView);
registerForContextMenu(mPowTouTextView);
registerForContextMenu(mFlavorTextView);
registerForContextMenu(mArtistTextView);
mCardImageView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
if (mAsyncTask != null) {
mAsyncTask.cancel(true);
}
mAsyncTask = new saveCardImageTask();
mAsyncTask.execute((Void[]) null);
return true;
}
});
if (mActivity.mPreferenceAdapter.getPicFirst()) {
loadTo = MAIN_PAGE;
} else {
loadTo = DIALOG;
}
setInfoFromBundle(this.getArguments());
return myFragmentView;
}
/**
* This will fill the UI elements with database information about the card specified in the given bundle
*
* @param extras The bundle passed to this fragment
*/
private void setInfoFromBundle(Bundle extras) {
if (extras == null) {
mNameTextView.setText("");
mCostTextView.setText("");
mTypeTextView.setText("");
mSetTextView.setText("");
mAbilityTextView.setText("");
mFlavorTextView.setText("");
mArtistTextView.setText("");
mPowTouTextView.setText("");
mTransformButton.setVisibility(View.GONE);
mTransformButtonDivider.setVisibility(View.GONE);
return;
}
long cardID = extras.getLong(CARD_ID);
/* from onCreateView */
setInfoFromID(cardID);
}
/**
* This will fill the UI elements with information from the database
* It also saves information for AsyncTasks to use later and manages the transform/flip button
*
* @param id the ID of the the card to be displayed
*/
private void setInfoFromID(final long id) {
ImageGetter imgGetter = ImageGetterHelper.GlyphGetter(getActivity());
SQLiteDatabase database = DatabaseManager.getInstance(getActivity(), false).openDatabase(false);
Cursor cCardById;
try {
cCardById = CardDbAdapter.fetchCard(id, database);
} catch (FamiliarDbException e) {
handleFamiliarDbException(true);
DatabaseManager.getInstance(getActivity(), false).closeDatabase(false);
return;
}
/* http://magiccards.info/scans/en/mt/55.jpg */
mCardName = cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_NAME));
mSetCode = cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_SET));
/* Start building a description */
addToDescription(getString(R.string.search_name), mCardName);
try {
mSetName = CardDbAdapter.getSetNameFromCode(mSetCode, database);
addToDescription(getString(R.string.search_set), mSetName);
} catch (FamiliarDbException e) {
/* no set for you */
}
try {
mMagicCardsInfoSetCode =
CardDbAdapter.getCodeMtgi(cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_SET)),
database);
} catch (FamiliarDbException e) {
handleFamiliarDbException(true);
DatabaseManager.getInstance(getActivity(), false).closeDatabase(false);
return;
}
mCardNumber = cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_NUMBER));
switch ((char) cCardById.getInt(cCardById.getColumnIndex(CardDbAdapter.KEY_RARITY))) {
case 'C':
case 'c':
mSetTextView.setTextColor(CardViewFragment.this.getResources().getColor(getResourceIdFromAttr(R.attr.color_common)));
addToDescription(getString(R.string.search_rarity), getString(R.string.search_Common));
break;
case 'U':
case 'u':
mSetTextView.setTextColor(CardViewFragment.this.getResources().getColor(getResourceIdFromAttr(R.attr.color_uncommon)));
addToDescription(getString(R.string.search_rarity), getString(R.string.search_Uncommon));
break;
case 'R':
case 'r':
mSetTextView.setTextColor(CardViewFragment.this.getResources().getColor(getResourceIdFromAttr(R.attr.color_rare)));
addToDescription(getString(R.string.search_rarity), getString(R.string.search_Rare));
break;
case 'M':
case 'm':
mSetTextView.setTextColor(CardViewFragment.this.getResources().getColor(getResourceIdFromAttr(R.attr.color_mythic)));
addToDescription(getString(R.string.search_rarity), getString(R.string.search_Mythic));
break;
case 'T':
case 't':
mSetTextView.setTextColor(CardViewFragment.this.getResources().getColor(getResourceIdFromAttr(R.attr.color_timeshifted)));
addToDescription(getString(R.string.search_rarity), getString(R.string.search_Timeshifted));
break;
}
String sCost = cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_MANACOST));
addToDescription(getString(R.string.search_mana_cost), sCost);
CharSequence csCost = ImageGetterHelper.formatStringWithGlyphs(sCost, imgGetter);
mCostTextView.setText(csCost);
String sAbility = cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_ABILITY));
addToDescription(getString(R.string.search_text), sAbility);
CharSequence csAbility = ImageGetterHelper.formatStringWithGlyphs(sAbility, imgGetter);
mAbilityTextView.setText(csAbility);
String sFlavor = cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_FLAVOR));
addToDescription(getString(R.string.search_flavor_text), sFlavor);
CharSequence csFlavor = ImageGetterHelper.formatStringWithGlyphs(sFlavor, imgGetter);
mFlavorTextView.setText(csFlavor);
mNameTextView.setText(cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_NAME)));
mCardType = cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_TYPE));
mTypeTextView.setText(mCardType);
mSetTextView.setText(cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_SET)));
mArtistTextView.setText(cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_ARTIST)));
addToDescription(getString(R.string.search_type), cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_TYPE)));
addToDescription(getString(R.string.search_artist), cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_ARTIST)));
int loyalty = cCardById.getInt(cCardById.getColumnIndex(CardDbAdapter.KEY_LOYALTY));
float p = cCardById.getFloat(cCardById.getColumnIndex(CardDbAdapter.KEY_POWER));
float t = cCardById.getFloat(cCardById.getColumnIndex(CardDbAdapter.KEY_TOUGHNESS));
if (loyalty != CardDbAdapter.NO_ONE_CARES) {
mPowTouTextView.setText(Integer.valueOf(loyalty).toString());
} else if (p != CardDbAdapter.NO_ONE_CARES && t != CardDbAdapter.NO_ONE_CARES) {
String powTouStr = "";
if (p == CardDbAdapter.STAR)
powTouStr += "*";
else if (p == CardDbAdapter.ONE_PLUS_STAR)
powTouStr += "1+*";
else if (p == CardDbAdapter.TWO_PLUS_STAR)
powTouStr += "2+*";
else if (p == CardDbAdapter.SEVEN_MINUS_STAR)
powTouStr += "7-*";
else if (p == CardDbAdapter.STAR_SQUARED)
powTouStr += "*^2";
else {
if (p == (int) p) {
powTouStr += (int) p;
} else {
powTouStr += p;
}
}
powTouStr += "/";
if (t == CardDbAdapter.STAR)
powTouStr += "*";
else if (t == CardDbAdapter.ONE_PLUS_STAR)
powTouStr += "1+*";
else if (t == CardDbAdapter.TWO_PLUS_STAR)
powTouStr += "2+*";
else if (t == CardDbAdapter.SEVEN_MINUS_STAR)
powTouStr += "7-*";
else if (t == CardDbAdapter.STAR_SQUARED)
powTouStr += "*^2";
else {
if (t == (int) t) {
powTouStr += (int) t;
} else {
powTouStr += t;
}
}
addToDescription(getString(R.string.search_power), powTouStr);
mPowTouTextView.setText(powTouStr);
} else {
mPowTouTextView.setText("");
}
boolean isMultiCard = false;
switch (CardDbAdapter.isMultiCard(mCardNumber,
cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_SET)))) {
case CardDbAdapter.NOPE:
isMultiCard = false;
mTransformButton.setVisibility(View.GONE);
mTransformButtonDivider.setVisibility(View.GONE);
break;
case CardDbAdapter.TRANSFORM:
isMultiCard = true;
mTransformButton.setVisibility(View.VISIBLE);
mTransformButtonDivider.setVisibility(View.VISIBLE);
mTransformButton.setText(R.string.card_view_transform);
break;
case CardDbAdapter.FUSE:
isMultiCard = true;
mTransformButton.setVisibility(View.VISIBLE);
mTransformButtonDivider.setVisibility(View.VISIBLE);
mTransformButton.setText(R.string.card_view_fuse);
break;
case CardDbAdapter.SPLIT:
isMultiCard = true;
mTransformButton.setVisibility(View.VISIBLE);
mTransformButtonDivider.setVisibility(View.VISIBLE);
mTransformButton.setText(R.string.card_view_other_half);
break;
}
if (isMultiCard) {
if (mCardNumber.contains("a")) {
mTransformCardNumber = mCardNumber.replace("a", "b");
} else if (mCardNumber.contains("b")) {
mTransformCardNumber = mCardNumber.replace("b", "a");
}
try {
mTransformId = CardDbAdapter.getTransform(mSetCode, mTransformCardNumber, database);
} catch (FamiliarDbException e) {
handleFamiliarDbException(true);
DatabaseManager.getInstance(getActivity(), false).closeDatabase(false);
return;
}
if (mTransformId == -1) {
mTransformButton.setVisibility(View.GONE);
mTransformButtonDivider.setVisibility(View.GONE);
} else {
mTransformButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mCardBitmap = null;
mCardNumber = mTransformCardNumber;
setInfoFromID(mTransformId);
}
});
}
}
mMultiverseId = cCardById.getInt(cCardById.getColumnIndex(CardDbAdapter.KEY_MULTIVERSEID));
/* Do we load the image immediately to the main page, or do it in a dialog later? */
if (loadTo == MAIN_PAGE) {
mImageScrollView.setVisibility(View.VISIBLE);
mTextScrollView.setVisibility(View.GONE);
mActivity.setLoading();
if (mAsyncTask != null) {
mAsyncTask.cancel(true);
}
mAsyncTask = new FetchPictureTask();
mAsyncTask.execute((Void[]) null);
} else {
mImageScrollView.setVisibility(View.GONE);
mTextScrollView.setVisibility(View.VISIBLE);
}
cCardById.close();
/* Find the other sets this card is in ahead of time, so that it can be remove from the menu if there is only
one set */
Cursor cCardByName;
try {
cCardByName = CardDbAdapter.fetchCardByName(mCardName,
new String[]{
CardDbAdapter.DATABASE_TABLE_CARDS + "." + CardDbAdapter.KEY_SET,
CardDbAdapter.DATABASE_TABLE_CARDS + "." + CardDbAdapter.KEY_ID}, database
);
} catch (FamiliarDbException e) {
handleFamiliarDbException(true);
DatabaseManager.getInstance(getActivity(), false).closeDatabase(false);
return;
}
mSets = new LinkedHashSet<>();
mCardIds = new LinkedHashSet<>();
while (!cCardByName.isAfterLast()) {
try {
if (mSets.add(CardDbAdapter
.getSetNameFromCode(cCardByName.getString(cCardByName.getColumnIndex(CardDbAdapter.KEY_SET)), database))) {
mCardIds.add(cCardByName.getLong(cCardByName.getColumnIndex(CardDbAdapter.KEY_ID)));
}
} catch (FamiliarDbException e) {
handleFamiliarDbException(true);
DatabaseManager.getInstance(getActivity(), false).closeDatabase(false);
return;
}
cCardByName.moveToNext();
}
cCardByName.close();
/* If it exists in only one set, remove the button from the menu */
if (mSets.size() == 1) {
mActivity.supportInvalidateOptionsMenu();
}
DatabaseManager.getInstance(getActivity(), false).closeDatabase(false);
if (mShouldReportView) {
reportAppIndexViewIfAble();
}
}
/**
* Used to build a meta description of this card, for app indexing
*
* @param tag A tag for this data
* @param data The data to add to the description
*/
private void addToDescription(String tag, String data) {
if (mDescription == null) {
mDescription = tag + ": \"" + data + "\"";
} else {
mDescription += "\n" + tag + ": \"" + data + "\"";
}
}
/**
* Remove any showing dialogs, and show the requested one
*
* @param id the ID of the dialog to show
*/
private void showDialog(final int id) throws IllegalStateException {
/* DialogFragment.show() will take care of adding the fragment in a transaction. We also want to remove any
currently showing dialog, so make our own transaction and take care of that here. */
/* If the fragment isn't visible (maybe being loaded by the pager), don't show dialogs */
if (!this.isVisible()) {
return;
}
removeDialog(getFragmentManager());
/* Create and show the dialog. */
final FamiliarDialogFragment newFragment = new FamiliarDialogFragment() {
@NotNull
@Override
@SuppressWarnings("SpellCheckingInspection")
public Dialog onCreateDialog(Bundle savedInstanceState) {
super.onCreateDialog(savedInstanceState);
/* This will be set to false if we are returning a null dialog. It prevents a crash */
setShowsDialog(true);
switch (id) {
case GET_IMAGE: {
if (mCardBitmap == null) {
return DontShowDialog();
}
Dialog dialog = new Dialog(mActivity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.card_view_image_dialog);
ImageView dialogImageView = (ImageView) dialog.findViewById(R.id.cardimage);
dialogImageView.setImageDrawable(mCardBitmap);
dialogImageView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
if (mAsyncTask != null) {
mAsyncTask.cancel(true);
}
mAsyncTask = new saveCardImageTask();
mAsyncTask.execute((Void[]) null);
return true;
}
});
return dialog;
}
case GET_LEGALITY: {
if (mFormats == null || mLegalities == null) {
/* exception handled in AsyncTask */
return DontShowDialog();
}
/* create the item mapping */
String[] from = new String[]{"format", "status"};
int[] to = new int[]{R.id.format, R.id.status};
/* prepare the list of all records */
List<HashMap<String, String>> fillMaps = new ArrayList<>();
for (int i = 0; i < mFormats.length; i++) {
HashMap<String, String> map = new HashMap<>();
map.put(from[0], mFormats[i]);
map.put(from[1], mLegalities[i]);
fillMaps.add(map);
}
SimpleAdapter adapter = new SimpleAdapter(mActivity, fillMaps, R.layout.card_view_legal_row,
from, to);
ListView lv = new ListView(mActivity);
lv.setAdapter(adapter);
AlertDialogPro.Builder builder = new AlertDialogPro.Builder(mActivity);
builder.setView(lv);
builder.setTitle(R.string.card_view_legality);
return builder.create();
}
case GET_PRICE: {
if (mPriceInfo == null) {
return DontShowDialog();
}
View v = mActivity.getLayoutInflater().inflate(R.layout.card_view_price_dialog, null, false);
assert v != null; /* Because Android Studio */
TextView l = (TextView) v.findViewById(R.id.low);
TextView m = (TextView) v.findViewById(R.id.med);
TextView h = (TextView) v.findViewById(R.id.high);
TextView f = (TextView) v.findViewById(R.id.foil);
TextView priceLink = (TextView) v.findViewById(R.id.pricelink);
l.setText(String.format("$%1$,.2f", mPriceInfo.mLow));
m.setText(String.format("$%1$,.2f", mPriceInfo.mAverage));
h.setText(String.format("$%1$,.2f", mPriceInfo.mHigh));
if (mPriceInfo.mFoilAverage != 0) {
f.setText(String.format("$%1$,.2f", mPriceInfo.mFoilAverage));
} else {
f.setVisibility(View.GONE);
v.findViewById(R.id.foil_label).setVisibility(View.GONE);
}
priceLink.setMovementMethod(LinkMovementMethod.getInstance());
priceLink.setText(ImageGetterHelper.formatHtmlString("<a href=\"" + mPriceInfo.mUrl + "\">" +
getString(R.string.card_view_price_dialog_link) + "</a>"));
AlertDialogPro.Builder adb = new AlertDialogPro.Builder(mActivity);
adb.setView(v);
adb.setTitle(R.string.card_view_price_dialog_title);
return adb.create();
}
case CHANGE_SET: {
final String[] aSets = mSets.toArray(new String[mSets.size()]);
final Long[] aIds = mCardIds.toArray(new Long[mCardIds.size()]);
/* Sanity check */
for (String set : aSets) {
if (set == null) {
return DontShowDialog();
}
}
AlertDialogPro.Builder builder = new AlertDialogPro.Builder(mActivity);
builder.setTitle(R.string.card_view_set_dialog_title);
builder.setItems(aSets, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int item) {
setInfoFromID(aIds[item]);
}
});
return builder.create();
}
case CARD_RULINGS: {
if (mRulingsArrayList == null) {
return DontShowDialog();
}
ImageGetter imgGetter = ImageGetterHelper.GlyphGetter(getActivity());
View v = mActivity.getLayoutInflater().inflate(R.layout.card_view_rulings_dialog, null, false);
assert v != null; /* Because Android Studio */
TextView textViewRules = (TextView) v.findViewById(R.id.rules);
TextView textViewUrl = (TextView) v.findViewById(R.id.url);
String message = "";
if (mRulingsArrayList.size() == 0) {
message = getString(R.string.card_view_no_rulings);
} else {
for (Ruling r : mRulingsArrayList) {
message += (r.toString() + "<br><br>");
}
message = message.replace("{Tap}", "{T}");
}
CharSequence messageGlyph = ImageGetterHelper.formatStringWithGlyphs(message, imgGetter);
textViewRules.setText(messageGlyph);
textViewUrl.setMovementMethod(LinkMovementMethod.getInstance());
textViewUrl.setText(Html.fromHtml(
"<a href=http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=" +
mMultiverseId + ">" + getString(R.string.card_view_gatherer_page) + "</a>"
));
AlertDialogPro.Builder builder = new AlertDialogPro.Builder(mActivity);
builder.setTitle(R.string.card_view_rulings_dialog_title);
builder.setView(v);
return builder.create();
}
case WISH_LIST_COUNTS: {
Dialog dialog = WishlistHelpers.getDialog(mCardName, CardViewFragment.this, false);
if (dialog == null) {
handleFamiliarDbException(false);
return DontShowDialog();
}
return dialog;
}
default: {
return DontShowDialog();
}
}
}
};
newFragment.show(getFragmentManager(), FamiliarActivity.DIALOG_TAG);
}
/**
* Called when a registered view is long-pressed. The menu inflated will give different options based on the view class
*
* @param menu The context menu that is being built
* @param v The view for which the context menu is being built
* @param menuInfo Extra information about the item for which the context menu should be shown. This information
* will vary depending on the class of v.
*/
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
TextView tv = (TextView) v;
assert tv.getText() != null;
mCopyString = tv.getText().toString();
android.view.MenuInflater inflater = this.mActivity.getMenuInflater();
inflater.inflate(R.menu.copy_menu, menu);
}
/**
* Copies text to the clipboard
*
* @param item The context menu item that was selected.
* @return boolean Return false to allow normal context menu processing to proceed, true to consume it here.
*/
@Override
public boolean onContextItemSelected(android.view.MenuItem item) {
if (getUserVisibleHint()) {
String copyText;
switch (item.getItemId()) {
case R.id.copy: {
copyText = mCopyString;
break;
}
case R.id.copyall: {
assert mNameTextView.getText() != null; /* Because Android Studio */
assert mCostTextView.getText() != null;
assert mTypeTextView.getText() != null;
assert mSetTextView.getText() != null;
assert mAbilityTextView.getText() != null;
assert mFlavorTextView.getText() != null;
assert mPowTouTextView.getText() != null;
assert mArtistTextView.getText() != null;
copyText = mNameTextView.getText().toString() + '\n' + mCostTextView.getText().toString() + '\n' +
mTypeTextView.getText().toString() + '\n' + mSetTextView.getText().toString() + '\n' +
mAbilityTextView.getText().toString() + '\n' + mFlavorTextView.getText().toString() + '\n' +
mPowTouTextView.getText().toString() + '\n' + mArtistTextView.getText().toString();
break;
}
default: {
return super.onContextItemSelected(item);
}
}
ClipboardManager clipboard = (ClipboardManager) (this.mActivity.
getSystemService(android.content.Context.CLIPBOARD_SERVICE));
String label = getResources().getString(R.string.app_name);
String mimeTypes[] = {ClipDescription.MIMETYPE_TEXT_PLAIN};
ClipData cd = new ClipData(label, mimeTypes, new ClipData.Item(copyText));
clipboard.setPrimaryClip(cd);
return true;
}
return false;
}
/**
* Handles clicks from the ActionBar
*
* @param item the item clicked
* @return true if acted upon, false if otherwise
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mCardName == null) {
/*disable menu buttons if the card isn't initialized */
return false;
}
/* Handle item selection */
switch (item.getItemId()) {
case R.id.image: {
if (getFamiliarActivity().getNetworkState(true) == -1) {
return true;
}
mActivity.setLoading();
if (mAsyncTask != null) {
mAsyncTask.cancel(true);
}
mAsyncTask = new FetchPictureTask();
mAsyncTask.execute((Void[]) null);
return true;
}
case R.id.price: {
mActivity.setLoading();
PriceFetchRequest priceRequest;
priceRequest = new PriceFetchRequest(mCardName, mSetCode, mCardNumber, mMultiverseId, getActivity());
mActivity.mSpiceManager.execute(priceRequest,
mCardName + "-" + mSetCode, DurationInMillis.ONE_DAY, new RequestListener<PriceInfo>() {
@Override
public void onRequestFailure(SpiceException spiceException) {
if (CardViewFragment.this.isAdded()) {
mActivity.clearLoading();
CardViewFragment.this.removeDialog(getFragmentManager());
ToastWrapper.makeText(mActivity, spiceException.getMessage(), ToastWrapper.LENGTH_SHORT).show();
}
}
@Override
public void onRequestSuccess(final PriceInfo result) {
if (CardViewFragment.this.isAdded()) {
mActivity.clearLoading();
if (result != null) {
mPriceInfo = result;
showDialog(GET_PRICE);
} else {
ToastWrapper.makeText(mActivity, R.string.card_view_price_not_found,
ToastWrapper.LENGTH_SHORT).show();
}
}
}
}
);
return true;
}
case R.id.changeset: {
showDialog(CHANGE_SET);
return true;
}
case R.id.legality: {
mActivity.setLoading();
if (mAsyncTask != null) {
mAsyncTask.cancel(true);
}
mAsyncTask = new FetchLegalityTask();
mAsyncTask.execute((Void[]) null);
return true;
}
case R.id.cardrulings: {
if (getFamiliarActivity().getNetworkState(true) == -1) {
return true;
}
mActivity.setLoading();
if (mAsyncTask != null) {
mAsyncTask.cancel(true);
}
mAsyncTask = new FetchRulingsTask();
mAsyncTask.execute((Void[]) null);
return true;
}
case R.id.addtowishlist: {
showDialog(WISH_LIST_COUNTS);
return true;
}
default: {
return super.onOptionsItemSelected(item);
}
}
}
/**
* Inflate the ActionBar items
*
* @param menu The options menu in which you place your items.
* @param inflater The inflater to use to inflate the menu
*/
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.card_menu, menu);
}
/**
* Prepare the Screen's standard options menu to be displayed. This is
* called right before the menu is shown, every time it is shown. You can
* use this method to efficiently enable/disable items or otherwise
* dynamically modify the contents.
*
* @param menu The options menu as last shown or first initialized by
* onCreateOptionsMenu().
* @see #setHasOptionsMenu
* @see #onCreateOptionsMenu
*/
@Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
MenuItem mi;
/* If the image has been loaded to the main page, remove the menu option for image */
if (loadTo == MAIN_PAGE && mCardBitmap != null) {
mi = menu.findItem(R.id.image);
if (mi != null) {
menu.removeItem(mi.getItemId());
}
}
/* This code removes the "change set" button if there is only one set.
* Turns out some users use it to view the full set name when there is only one set/
* I'm leaving it here, but commented, for posterity */
/*
if (mSets != null && mSets.size() == 1) {
mi = menu.findItem(R.id.changeset);
if (mi != null) {
menu.removeItem(mi.getItemId());
}
}
*/
}
/**
* This inner class encapsulates a ruling and the date it was made
*/
private static class Ruling {
public final String date;
public final String ruling;
public Ruling(String d, String r) {
date = d;
ruling = r;
}
public String toString() {
return date + ": " + ruling;
}
}
class saveCardImageTask extends AsyncTask<Void, Void, Void> {
String mToastString;
@Override
protected Void doInBackground(Void... voids) {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
mToastString = getString(R.string.card_view_no_external_storage);
return null;
}
String strPath;
try {
strPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
.getCanonicalPath() + "/MTGFamiliar";
} catch (IOException ex) {
mToastString = getString(R.string.card_view_no_pictures_folder);
return null;
}
File fPath = new File(strPath);
if (!fPath.exists()) {
fPath.mkdir();
if (!fPath.isDirectory()) {
mToastString = getString(R.string.card_view_unable_to_create_dir);
return null;
}
}
fPath = new File(strPath, mCardName + "_" + mSetCode + ".jpg");
if (fPath.exists()) {
fPath.delete();
}
try {
if (!fPath.createNewFile()) {
mToastString = getString(R.string.card_view_unable_to_create_file);
return null;
}
FileOutputStream fStream = new FileOutputStream(fPath);
/* If the card is displayed, there's a real good chance it's cached */
String cardLanguage = mActivity.mPreferenceAdapter.getCardLanguage();
if (cardLanguage == null) {
cardLanguage = "en";
}
String imageKey = Integer.toString(mMultiverseId) + cardLanguage;
Bitmap bmpImage;
try {
bmpImage = getFamiliarActivity().mImageCache.getBitmapFromDiskCache(imageKey);
} catch (NullPointerException e) {
bmpImage = null;
}
/* Check if this is an english only image */
if (bmpImage == null && !cardLanguage.equalsIgnoreCase("en")) {
imageKey = Integer.toString(mMultiverseId) + "en";
try {
bmpImage = getFamiliarActivity().mImageCache.getBitmapFromDiskCache(imageKey);
} catch (NullPointerException e) {
bmpImage = null;
}
}
/* nope, not here */
if (bmpImage == null) {
mToastString = getString(R.string.card_view_no_image);
return null;
}
boolean bCompressed = bmpImage.compress(Bitmap.CompressFormat.JPEG, 90, fStream);
if (!bCompressed) {
mToastString = getString(R.string.card_view_unable_to_save_image);
return null;
}
strPath = fPath.getCanonicalPath();
} catch (IOException ex) {
mToastString = getString(R.string.card_view_save_failure);
return null;
}
mToastString = getString(R.string.card_view_image_saved) + strPath;
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (mToastString != null) {
ToastWrapper.makeText(mActivity, mToastString, ToastWrapper.LENGTH_LONG).show();
}
}
}
/**
* This private class handles asking the database about the legality of a card, and will eventually show the
* information in a Dialog
*/
private class FetchLegalityTask extends AsyncTask<Void, Void, Void> {
/**
* Queries the data in the database to see what sets this card is legal in
*
* @param params unused
* @return unused
*/
@Override
protected Void doInBackground(Void... params) {
SQLiteDatabase database = DatabaseManager.getInstance(getActivity(), false).openDatabase(false);
try {
Cursor cFormats = CardDbAdapter.fetchAllFormats(database);
mFormats = new String[cFormats.getCount()];
mLegalities = new String[cFormats.getCount()];
cFormats.moveToFirst();
for (int i = 0; i < cFormats.getCount(); i++) {
mFormats[i] = cFormats.getString(cFormats.getColumnIndex(CardDbAdapter.KEY_NAME));
switch (CardDbAdapter.checkLegality(mCardName, mFormats[i], database)) {
case CardDbAdapter.LEGAL:
mLegalities[i] = getString(R.string.card_view_legal);
break;
case CardDbAdapter.RESTRICTED:
/* For backwards compatibility, we list cards that are legal
* in commander, but can't be the commander as Restricted in
* the legality file. This prevents older version of the app
* from throwing an IllegalStateException if we try including
* a new legality. */
if (mFormats[i].equalsIgnoreCase("Commander")) {
mLegalities[i] = getString(R.string.card_view_no_commander);
} else {
mLegalities[i] = getString(R.string.card_view_restricted);
}
break;
case CardDbAdapter.BANNED:
mLegalities[i] = getString(R.string.card_view_banned);
break;
default:
mLegalities[i] = getString(R.string.error);
break;
}
cFormats.moveToNext();
}
cFormats.close();
} catch (FamiliarDbException e) {
CardViewFragment.this.handleFamiliarDbException(false);
mLegalities = null;
}
DatabaseManager.getInstance(getActivity(), false).closeDatabase(false);
return null;
}
/**
* After the query, remove the progress dialog and show the legalities
*
* @param result unused
*/
@Override
protected void onPostExecute(Void result) {
try {
showDialog(GET_LEGALITY);
} catch (IllegalStateException e) {
/* eat it */
}
mActivity.clearLoading();
}
}
/**
* This private class retrieves a picture of the card from the internet
*/
private class FetchPictureTask extends AsyncTask<Void, Void, Void> {
private String error;
int mHeight;
int mWidth;
int mBorder;
/* Get the size of the window on the UI thread, not the worker thread */
final Runnable getWindowSize = new Runnable() {
@Override
public void run() {
Rect rectangle = new Rect();
mActivity.getWindow().getDecorView().getWindowVisibleDisplayFrame(rectangle);
assert mActivity.getSupportActionBar() != null; /* Because Android Studio */
mHeight = ((rectangle.bottom - rectangle.top) - mActivity.getSupportActionBar().getHeight()) - mBorder;
mWidth = (rectangle.right - rectangle.left) - mBorder;
synchronized (this) {
this.notify();
}
}
};
/**
* First check www.MagicCards.info for the card image in the user's preferred language
* If that fails, check www.MagicCards.info for the card image in English
* If that fails, check www.gatherer.wizards.com for the card image
* If that fails, give up
* There is non-standard URL building for planes and schemes
* It also re-sizes the image
*
* @param params unused
* @return unused
*/
@SuppressWarnings("SpellCheckingInspection")
@Override
protected Void doInBackground(Void... params) {
String cardLanguage = mActivity.mPreferenceAdapter.getCardLanguage();
if (cardLanguage == null) {
cardLanguage = "en";
}
final String imageKey = Integer.toString(mMultiverseId) + cardLanguage;
/* Check disk cache in background thread */
Bitmap bitmap;
try {
bitmap = getFamiliarActivity().mImageCache.getBitmapFromDiskCache(imageKey);
} catch (NullPointerException e) {
bitmap = null;
}
if (bitmap == null) { /* Not found in disk cache */
boolean bRetry = true;
boolean triedMtgi = false;
boolean triedGatherer = false;
while (bRetry) {
bRetry = false;
error = null;
try {
URL u;
if (!cardLanguage.equalsIgnoreCase("en")) {
u = new URL(getMtgiPicUrl(mCardName, mMagicCardsInfoSetCode, mCardNumber, cardLanguage));
cardLanguage = "en";
} else {
if (!triedMtgi) {
u = new URL(getMtgiPicUrl(mCardName, mMagicCardsInfoSetCode, mCardNumber, cardLanguage));
triedMtgi = true;
} else {
u = new URL("http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid="
+ mMultiverseId + "&type=card");
triedGatherer = true;
}
}
mCardBitmap = new RecyclingBitmapDrawable(mActivity.getResources(), BitmapFactory.decodeStream(u.openStream()));
bitmap = mCardBitmap.getBitmap();
getFamiliarActivity().mImageCache.addBitmapToCache(imageKey, mCardBitmap);
} catch (Exception e) {
/* Something went wrong */
try {
error = getString(R.string.card_view_image_not_found);
} catch (RuntimeException re) {
/* in case the fragment isn't attached to an activity */
error = e.toString();
}
if (!triedGatherer) {
bRetry = true;
}
}
}
}
if (bitmap == null) {
return null;
}
try {
/* 16dp */
mBorder = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 16, getResources().getDisplayMetrics());
if (loadTo == MAIN_PAGE) {
/* Block the worker thread until the size is figured out */
synchronized (getWindowSize) {
getActivity().runOnUiThread(getWindowSize);
getWindowSize.wait();
}
} else if (loadTo == DIALOG) {
Display display = ((WindowManager) mActivity
.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
Point p = new Point();
display.getSize(p);
mHeight = p.y - mBorder;
mWidth = p.x - mBorder;
}
float screenAspectRatio = (float) mHeight / (float) (mWidth);
float cardAspectRatio = (float) bitmap.getHeight() / (float) bitmap.getWidth();
float scale;
if (screenAspectRatio > cardAspectRatio) {
scale = (mWidth) / (float) bitmap.getWidth();
} else {
scale = (mHeight) / (float) bitmap.getHeight();
}
int newWidth = Math.round(bitmap.getWidth() * scale);
int newHeight = Math.round(bitmap.getHeight() * scale);
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true); /* todo this is leaky? */
mCardBitmap = new RecyclingBitmapDrawable(mActivity.getResources(), scaledBitmap);
bitmap.recycle();
} catch (Exception e) {
/* Some error resizing. Out of memory? */
}
return null;
}
/**
* Jumps through hoops and returns a correctly formatted URL for magiccards.info's image
*
* @param cardName The name of the card
* @param magicCardsInfoSetCode The set of the card
* @param cardNumber The number of the card
* @param cardLanguage The language of the card
* @return a URL to the card's image
*/
private String getMtgiPicUrl(String cardName, String magicCardsInfoSetCode, String cardNumber,
String cardLanguage) {
String picURL;
if (mCardType.toLowerCase().contains(getString(R.string.search_Ongoing).toLowerCase()) ||
/* extra space to not confuse with planeswalker */
mCardType.toLowerCase().contains(getString(R.string.search_Plane).toLowerCase() + " ") ||
mCardType.toLowerCase().contains(getString(R.string.search_Phenomenon).toLowerCase()) ||
mCardType.toLowerCase().contains(getString(R.string.search_Scheme).toLowerCase())) {
switch (mSetCode) {
case "PC2":
picURL = "http://magiccards.info/extras/plane/planechase-2012-edition/" + cardName + ".jpg";
picURL = picURL.replace(" ", "-").replace(Character.toChars(0xC6)[0] + "", "Ae")
.replace("?", "").replace(",", "").replace("'", "").replace("!", "");
break;
case "PCH":
if (cardName.equalsIgnoreCase("tazeem")) {
cardName = "tazeem-release-promo";
} else if (cardName.equalsIgnoreCase("celestine reef")) {
cardName = "celestine-reef-pre-release-promo";
} else if (cardName.equalsIgnoreCase("horizon boughs")) {
cardName = "horizon-boughs-gateway-promo";
}
picURL = "http://magiccards.info/extras/plane/planechase/" + cardName + ".jpg";
picURL = picURL.replace(" ", "-").replace(Character.toChars(0xC6)[0] + "", "Ae")
.replace("?", "").replace(",", "").replace("'", "").replace("!", "");
break;
case "ARC":
picURL = "http://magiccards.info/extras/scheme/archenemy/" + cardName + ".jpg";
picURL = picURL.replace(" ", "-").replace(Character.toChars(0xC6)[0] + "", "Ae")
.replace("?", "").replace(",", "").replace("'", "").replace("!", "");
break;
default:
picURL = "http://magiccards.info/scans/" + cardLanguage + "/" + magicCardsInfoSetCode + "/" +
cardNumber + ".jpg";
break;
}
} else {
picURL = "http://magiccards.info/scans/" + cardLanguage + "/" + magicCardsInfoSetCode + "/" +
cardNumber + ".jpg";
}
return picURL.toLowerCase(Locale.ENGLISH);
}
/**
* When the task has finished, if there was no error, remove the progress dialog and show the image
* If the image was supposed to load to the main screen, and it failed to load, fall back to text view
*
* @param result unused
*/
@Override
protected void onPostExecute(Void result) {
if (error == null) {
if (loadTo == DIALOG) {
try {
showDialog(GET_IMAGE);
} catch (IllegalStateException e) {
/* eat it */
}
} else if (loadTo == MAIN_PAGE) {
removeDialog(getFragmentManager());
mCardImageView.setImageDrawable(mCardBitmap);
/* remove the image load button if it is the main page */
mActivity.supportInvalidateOptionsMenu();
}
} else {
removeDialog(getFragmentManager());
if (loadTo == MAIN_PAGE) {
mImageScrollView.setVisibility(View.GONE);
mTextScrollView.setVisibility(View.VISIBLE);
}
ToastWrapper.makeText(mActivity, error, ToastWrapper.LENGTH_LONG).show();
}
mActivity.clearLoading();
}
/**
* If the task is canceled, fall back to text view
*/
@Override
protected void onCancelled() {
if (loadTo == MAIN_PAGE) {
mImageScrollView.setVisibility(View.GONE);
mTextScrollView.setVisibility(View.VISIBLE);
}
}
}
/**
* This private class fetches rulings about this card from gatherer.wizards.com
*/
private class FetchRulingsTask extends AsyncTask<Void, Void, Void> {
String mErrorMessage = null;
/**
* This function downloads the source of the gatherer page, scans it for rulings, and stores them for display
*
* @param params unused
* @return unused
*/
@Override
@SuppressWarnings("SpellCheckingInspection")
protected Void doInBackground(Void... params) {
URL url;
InputStream is = null;
BufferedReader br;
String line;
mRulingsArrayList = new ArrayList<>();
try {
url = new URL("http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=" + mMultiverseId);
is = url.openStream(); /* throws an IOException */
br = new BufferedReader(new InputStreamReader(new BufferedInputStream(is)));
String date = null, ruling;
while ((line = br.readLine()) != null) {
if (line.contains("rulingDate") && line.contains("<td")) {
date = (line.replace("<autocard>", "").replace("</autocard>", ""))
.split(">")[1].split("<")[0];
}
if (line.contains("rulingText") && line.contains("<td")) {
ruling = (line.replace("<autocard>", "").replace("</autocard>", ""))
.split(">")[1].split("<")[0];
Ruling r = new Ruling(date, ruling);
mRulingsArrayList.add(r);
}
}
} catch (IOException ioe) {
mErrorMessage = ioe.getLocalizedMessage();
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException ioe) {
mErrorMessage = ioe.getLocalizedMessage();
}
}
return null;
}
/**
* Hide the progress dialog and show the rulings, if there are no errors
*
* @param result unused
*/
@Override
protected void onPostExecute(Void result) {
if (mErrorMessage == null) {
try {
showDialog(CARD_RULINGS);
} catch (IllegalStateException e) {
/* eat it */
}
} else {
removeDialog(getFragmentManager());
ToastWrapper.makeText(mActivity, mErrorMessage, ToastWrapper.LENGTH_SHORT).show();
}
mActivity.clearLoading();
}
}
} | MTGFamiliar/src/main/java/com/gelakinetic/mtgfam/fragments/CardViewFragment.java | /**
* Copyright 2011 Adam Feinstein
* <p/>
* This file is part of MTG Familiar.
* <p/>
* MTG Familiar is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* <p/>
* MTG Familiar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p/>
* You should have received a copy of the GNU General Public License
* along with MTG Familiar. If not, see <http://www.gnu.org/licenses/>.
*/
package com.gelakinetic.mtgfam.fragments;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipDescription;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.Rect;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.text.method.LinkMovementMethod;
import android.util.TypedValue;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import com.alertdialogpro.AlertDialogPro;
import com.gelakinetic.mtgfam.FamiliarActivity;
import com.gelakinetic.mtgfam.R;
import com.gelakinetic.mtgfam.helpers.ImageGetterHelper;
import com.gelakinetic.mtgfam.helpers.PriceFetchRequest;
import com.gelakinetic.mtgfam.helpers.PriceInfo;
import com.gelakinetic.mtgfam.helpers.ToastWrapper;
import com.gelakinetic.mtgfam.helpers.WishlistHelpers;
import com.gelakinetic.mtgfam.helpers.database.CardDbAdapter;
import com.gelakinetic.mtgfam.helpers.database.DatabaseManager;
import com.gelakinetic.mtgfam.helpers.database.FamiliarDbException;
import com.gelakinetic.mtgfam.helpers.lruCache.RecyclingBitmapDrawable;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.octo.android.robospice.persistence.DurationInMillis;
import com.octo.android.robospice.persistence.exception.SpiceException;
import com.octo.android.robospice.request.listener.RequestListener;
import org.jetbrains.annotations.NotNull;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
/**
* This class handles displaying card info
* WARNING! Because this fragment is nested in a CardViewPagerFragment, always get the parent fragment's activity
*/
public class CardViewFragment extends FamiliarFragment {
/* Bundle constant */
public static final String CARD_ID = "card_id";
/* Dialogs */
private static final int GET_PRICE = 1;
private static final int GET_IMAGE = 2;
private static final int CHANGE_SET = 3;
private static final int CARD_RULINGS = 4;
private static final int WISH_LIST_COUNTS = 6;
private static final int GET_LEGALITY = 7;
/* Where the card image is loaded to */
private static final int MAIN_PAGE = 1;
private static final int DIALOG = 2;
private int loadTo = DIALOG; /* where to load the image */
/* Used to store the String when copying to clipboard */
private String mCopyString;
/* UI elements, to be filled in */
private TextView mNameTextView;
private TextView mCostTextView;
private TextView mTypeTextView;
private TextView mSetTextView;
private TextView mAbilityTextView;
private TextView mPowTouTextView;
private TextView mFlavorTextView;
private TextView mArtistTextView;
private Button mTransformButton;
private View mTransformButtonDivider;
private ImageView mCardImageView;
private ScrollView mTextScrollView;
private ScrollView mImageScrollView;
/* the AsyncTask loads stuff off the UI thread, and stores whatever in these local variables */
private AsyncTask<Void, Void, Void> mAsyncTask;
private RecyclingBitmapDrawable mCardBitmap;
private String[] mLegalities;
private String[] mFormats;
private ArrayList<Ruling> mRulingsArrayList;
/* Loaded in a Spice Service */
private PriceInfo mPriceInfo;
/* Card info, used to build the URL to fetch the picture */
private String mCardNumber;
private String mSetCode;
private String mCardName;
private String mMagicCardsInfoSetCode;
private int mMultiverseId;
private String mCardType;
/* Card info used to flip the card */
private String mTransformCardNumber;
private int mTransformId;
/* To switch card between printings */
private LinkedHashSet<String> mSets;
private LinkedHashSet<Long> mCardIds;
/* Easier than calling getActivity() all the time, and handles being nested */
private FamiliarActivity mActivity;
/* State for reporting page views */
private boolean mHasReportedView = false;
private boolean mShouldReportView = false;
private String mDescription;
private String mSetName;
/**
* Kill any AsyncTask if it is still running
*/
@Override
public void onDestroy() {
super.onDestroy();
/* Pass a non-null bundle to the ResultListFragment so it knows to exit if there was a list of 1 card
* If this wasn't launched by a ResultListFragment, it'll get eaten */
Bundle args = new Bundle();
mActivity.setFragmentResult(args);
}
/**
* Called when the Fragment is no longer resumed. Clear the loading bar just in case
*/
@Override
public void onPause() {
super.onPause();
mActivity.clearLoading();
if (mAsyncTask != null) {
mAsyncTask.cancel(true);
}
}
/**
* Called when the fragment stops, attempt to report the close
*/
@Override
public void onStop() {
reportAppIndexEndIfAble();
super.onStop();
}
/**
* Creates and returns the action describing this page view
*
* @return An action describing this page view
*/
private Action getAppIndexAction() {
Thing object = new Thing.Builder()
.setType("http://schema.org/Thing") /* Optional, any valid schema.org type */
.setName(mCardName + " (" + mSetName + ")") /* Required, title field */
.setDescription(mDescription) /* Required, description field */
/* Required, deep link in the android-app:// format */
.setUrl(Uri.parse("android-app://com.gelakinetic.mtgfam/card/multiverseid/" + mMultiverseId))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.build();
}
/**
* Reports this view to the Google app indexing API, once, when the fragment is viewed
*/
private void reportAppIndexViewIfAble() {
/* If this view hasn't been reported yet, and the name exists */
if (!mHasReportedView) {
if (mCardName != null) {
/* Connect your client */
getFamiliarActivity().mGoogleApiClient.connect();
AppIndex.AppIndexApi.start(getFamiliarActivity().mGoogleApiClient, getAppIndexAction());
/* Manage state */
mHasReportedView = true;
mShouldReportView = false;
} else {
mShouldReportView = true;
}
}
}
/**
* Ends the report to the Google app indexing API, once, when the fragment is no longer viewed
*/
private void reportAppIndexEndIfAble() {
/* If the view was previously reported, and the name exists */
if (mHasReportedView && mCardName != null) {
/* Call end() and disconnect the client */
AppIndex.AppIndexApi.end(getFamiliarActivity().mGoogleApiClient, getAppIndexAction());
getFamiliarActivity().mGoogleApiClient.disconnect();
/* manage state */
mHasReportedView = false;
}
}
/**
* Set a hint to the system about whether this fragment's UI is currently visible to the user.
* This hint defaults to true and is persistent across fragment instance state save and restore.
* <p/>
* An app may set this to false to indicate that the fragment's UI is scrolled out of visibility
* or is otherwise not directly visible to the user. This may be used by the system to
* prioritize operations such as fragment lifecycle updates or loader ordering behavior.
* <p/>
* In this case, it's used to report fragment views to Google app indexing
*
* @param isVisibleToUser true if this fragment's UI is currently visible to the user (default),
* false if it is not.
*/
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
/* If the fragment is visible to the user, attempt to report the view */
reportAppIndexViewIfAble();
} else {
/* The view isn't visible anymore, attempt to report it */
reportAppIndexEndIfAble();
}
}
/**
* Inflates the view and saves references to UI elements for later filling
*
* @param savedInstanceState If non-null, this fragment is being re-constructed from a previous saved state as given
* here.
* @param inflater The LayoutInflater object that can be used to inflate any views in the fragment,
* @param container If non-null, this is the parent view that the fragment's UI should be attached to. The
* fragment should not add the view itself, but this can be used to generate the
* LayoutParams of the view.
* @return The inflated view
*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
try {
mActivity = ((FamiliarFragment) getParentFragment()).getFamiliarActivity();
} catch (NullPointerException e) {
mActivity = getFamiliarActivity();
}
View myFragmentView = inflater.inflate(R.layout.card_view_frag, container, false);
assert myFragmentView != null; /* Because Android Studio */
mNameTextView = (TextView) myFragmentView.findViewById(R.id.name);
mCostTextView = (TextView) myFragmentView.findViewById(R.id.cost);
mTypeTextView = (TextView) myFragmentView.findViewById(R.id.type);
mSetTextView = (TextView) myFragmentView.findViewById(R.id.set);
mAbilityTextView = (TextView) myFragmentView.findViewById(R.id.ability);
mFlavorTextView = (TextView) myFragmentView.findViewById(R.id.flavor);
mArtistTextView = (TextView) myFragmentView.findViewById(R.id.artist);
mPowTouTextView = (TextView) myFragmentView.findViewById(R.id.pt);
mTransformButtonDivider = myFragmentView.findViewById(R.id.transform_button_divider);
mTransformButton = (Button) myFragmentView.findViewById(R.id.transformbutton);
mTextScrollView = (ScrollView) myFragmentView.findViewById(R.id.cardTextScrollView);
mImageScrollView = (ScrollView) myFragmentView.findViewById(R.id.cardImageScrollView);
mCardImageView = (ImageView) myFragmentView.findViewById(R.id.cardpic);
registerForContextMenu(mNameTextView);
registerForContextMenu(mCostTextView);
registerForContextMenu(mTypeTextView);
registerForContextMenu(mSetTextView);
registerForContextMenu(mAbilityTextView);
registerForContextMenu(mPowTouTextView);
registerForContextMenu(mFlavorTextView);
registerForContextMenu(mArtistTextView);
mCardImageView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
if (mAsyncTask != null) {
mAsyncTask.cancel(true);
}
mAsyncTask = new saveCardImageTask();
mAsyncTask.execute((Void[]) null);
return true;
}
});
if (mActivity.mPreferenceAdapter.getPicFirst()) {
loadTo = MAIN_PAGE;
} else {
loadTo = DIALOG;
}
setInfoFromBundle(this.getArguments());
return myFragmentView;
}
/**
* This will fill the UI elements with database information about the card specified in the given bundle
*
* @param extras The bundle passed to this fragment
*/
private void setInfoFromBundle(Bundle extras) {
if (extras == null) {
mNameTextView.setText("");
mCostTextView.setText("");
mTypeTextView.setText("");
mSetTextView.setText("");
mAbilityTextView.setText("");
mFlavorTextView.setText("");
mArtistTextView.setText("");
mPowTouTextView.setText("");
mTransformButton.setVisibility(View.GONE);
mTransformButtonDivider.setVisibility(View.GONE);
return;
}
long cardID = extras.getLong(CARD_ID);
/* from onCreateView */
setInfoFromID(cardID);
}
/**
* This will fill the UI elements with information from the database
* It also saves information for AsyncTasks to use later and manages the transform/flip button
*
* @param id the ID of the the card to be displayed
*/
private void setInfoFromID(final long id) {
ImageGetter imgGetter = ImageGetterHelper.GlyphGetter(getActivity());
SQLiteDatabase database = DatabaseManager.getInstance(getActivity(), false).openDatabase(false);
Cursor cCardById;
try {
cCardById = CardDbAdapter.fetchCard(id, database);
} catch (FamiliarDbException e) {
handleFamiliarDbException(true);
DatabaseManager.getInstance(getActivity(), false).closeDatabase(false);
return;
}
/* http://magiccards.info/scans/en/mt/55.jpg */
mCardName = cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_NAME));
mSetCode = cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_SET));
/* Start building a description */
addToDescription(getString(R.string.search_name), mCardName);
try {
mSetName = CardDbAdapter.getSetNameFromCode(mSetCode, database);
addToDescription(getString(R.string.search_set), mSetName);
} catch (FamiliarDbException e) {
/* no set for you */
}
try {
mMagicCardsInfoSetCode =
CardDbAdapter.getCodeMtgi(cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_SET)),
database);
} catch (FamiliarDbException e) {
handleFamiliarDbException(true);
DatabaseManager.getInstance(getActivity(), false).closeDatabase(false);
return;
}
mCardNumber = cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_NUMBER));
switch ((char) cCardById.getInt(cCardById.getColumnIndex(CardDbAdapter.KEY_RARITY))) {
case 'C':
case 'c':
mSetTextView.setTextColor(CardViewFragment.this.getResources().getColor(getResourceIdFromAttr(R.attr.color_common)));
addToDescription(getString(R.string.search_rarity), getString(R.string.search_Common));
break;
case 'U':
case 'u':
mSetTextView.setTextColor(CardViewFragment.this.getResources().getColor(getResourceIdFromAttr(R.attr.color_uncommon)));
addToDescription(getString(R.string.search_rarity), getString(R.string.search_Uncommon));
break;
case 'R':
case 'r':
mSetTextView.setTextColor(CardViewFragment.this.getResources().getColor(getResourceIdFromAttr(R.attr.color_rare)));
addToDescription(getString(R.string.search_rarity), getString(R.string.search_Rare));
break;
case 'M':
case 'm':
mSetTextView.setTextColor(CardViewFragment.this.getResources().getColor(getResourceIdFromAttr(R.attr.color_mythic)));
addToDescription(getString(R.string.search_rarity), getString(R.string.search_Mythic));
break;
case 'T':
case 't':
mSetTextView.setTextColor(CardViewFragment.this.getResources().getColor(getResourceIdFromAttr(R.attr.color_timeshifted)));
addToDescription(getString(R.string.search_rarity), getString(R.string.search_Timeshifted));
break;
}
String sCost = cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_MANACOST));
addToDescription(getString(R.string.search_mana_cost), sCost);
CharSequence csCost = ImageGetterHelper.formatStringWithGlyphs(sCost, imgGetter);
mCostTextView.setText(csCost);
String sAbility = cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_ABILITY));
addToDescription(getString(R.string.search_text), sAbility);
CharSequence csAbility = ImageGetterHelper.formatStringWithGlyphs(sAbility, imgGetter);
mAbilityTextView.setText(csAbility);
String sFlavor = cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_FLAVOR));
addToDescription(getString(R.string.search_flavor_text), sFlavor);
CharSequence csFlavor = ImageGetterHelper.formatStringWithGlyphs(sFlavor, imgGetter);
mFlavorTextView.setText(csFlavor);
mNameTextView.setText(cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_NAME)));
mCardType = cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_TYPE));
mTypeTextView.setText(mCardType);
mSetTextView.setText(cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_SET)));
mArtistTextView.setText(cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_ARTIST)));
addToDescription(getString(R.string.search_type), cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_TYPE)));
addToDescription(getString(R.string.search_artist), cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_ARTIST)));
int loyalty = cCardById.getInt(cCardById.getColumnIndex(CardDbAdapter.KEY_LOYALTY));
float p = cCardById.getFloat(cCardById.getColumnIndex(CardDbAdapter.KEY_POWER));
float t = cCardById.getFloat(cCardById.getColumnIndex(CardDbAdapter.KEY_TOUGHNESS));
if (loyalty != CardDbAdapter.NO_ONE_CARES) {
mPowTouTextView.setText(Integer.valueOf(loyalty).toString());
} else if (p != CardDbAdapter.NO_ONE_CARES && t != CardDbAdapter.NO_ONE_CARES) {
String powTouStr = "";
if (p == CardDbAdapter.STAR)
powTouStr += "*";
else if (p == CardDbAdapter.ONE_PLUS_STAR)
powTouStr += "1+*";
else if (p == CardDbAdapter.TWO_PLUS_STAR)
powTouStr += "2+*";
else if (p == CardDbAdapter.SEVEN_MINUS_STAR)
powTouStr += "7-*";
else if (p == CardDbAdapter.STAR_SQUARED)
powTouStr += "*^2";
else {
if (p == (int) p) {
powTouStr += (int) p;
} else {
powTouStr += p;
}
}
powTouStr += "/";
if (t == CardDbAdapter.STAR)
powTouStr += "*";
else if (t == CardDbAdapter.ONE_PLUS_STAR)
powTouStr += "1+*";
else if (t == CardDbAdapter.TWO_PLUS_STAR)
powTouStr += "2+*";
else if (t == CardDbAdapter.SEVEN_MINUS_STAR)
powTouStr += "7-*";
else if (t == CardDbAdapter.STAR_SQUARED)
powTouStr += "*^2";
else {
if (t == (int) t) {
powTouStr += (int) t;
} else {
powTouStr += t;
}
}
addToDescription(getString(R.string.search_power), powTouStr);
mPowTouTextView.setText(powTouStr);
} else {
mPowTouTextView.setText("");
}
boolean isMultiCard = false;
switch (CardDbAdapter.isMultiCard(mCardNumber,
cCardById.getString(cCardById.getColumnIndex(CardDbAdapter.KEY_SET)))) {
case CardDbAdapter.NOPE:
isMultiCard = false;
mTransformButton.setVisibility(View.GONE);
mTransformButtonDivider.setVisibility(View.GONE);
break;
case CardDbAdapter.TRANSFORM:
isMultiCard = true;
mTransformButton.setVisibility(View.VISIBLE);
mTransformButtonDivider.setVisibility(View.VISIBLE);
mTransformButton.setText(R.string.card_view_transform);
break;
case CardDbAdapter.FUSE:
isMultiCard = true;
mTransformButton.setVisibility(View.VISIBLE);
mTransformButtonDivider.setVisibility(View.VISIBLE);
mTransformButton.setText(R.string.card_view_fuse);
break;
case CardDbAdapter.SPLIT:
isMultiCard = true;
mTransformButton.setVisibility(View.VISIBLE);
mTransformButtonDivider.setVisibility(View.VISIBLE);
mTransformButton.setText(R.string.card_view_other_half);
break;
}
if (isMultiCard) {
if (mCardNumber.contains("a")) {
mTransformCardNumber = mCardNumber.replace("a", "b");
} else if (mCardNumber.contains("b")) {
mTransformCardNumber = mCardNumber.replace("b", "a");
}
try {
mTransformId = CardDbAdapter.getTransform(mSetCode, mTransformCardNumber, database);
} catch (FamiliarDbException e) {
handleFamiliarDbException(true);
DatabaseManager.getInstance(getActivity(), false).closeDatabase(false);
return;
}
if (mTransformId == -1) {
mTransformButton.setVisibility(View.GONE);
mTransformButtonDivider.setVisibility(View.GONE);
} else {
mTransformButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mCardBitmap = null;
mCardNumber = mTransformCardNumber;
setInfoFromID(mTransformId);
}
});
}
}
mMultiverseId = cCardById.getInt(cCardById.getColumnIndex(CardDbAdapter.KEY_MULTIVERSEID));
/* Do we load the image immediately to the main page, or do it in a dialog later? */
if (loadTo == MAIN_PAGE) {
mImageScrollView.setVisibility(View.VISIBLE);
mTextScrollView.setVisibility(View.GONE);
mActivity.setLoading();
if (mAsyncTask != null) {
mAsyncTask.cancel(true);
}
mAsyncTask = new FetchPictureTask();
mAsyncTask.execute((Void[]) null);
} else {
mImageScrollView.setVisibility(View.GONE);
mTextScrollView.setVisibility(View.VISIBLE);
}
cCardById.close();
/* Find the other sets this card is in ahead of time, so that it can be remove from the menu if there is only
one set */
Cursor cCardByName;
try {
cCardByName = CardDbAdapter.fetchCardByName(mCardName,
new String[]{
CardDbAdapter.DATABASE_TABLE_CARDS + "." + CardDbAdapter.KEY_SET,
CardDbAdapter.DATABASE_TABLE_CARDS + "." + CardDbAdapter.KEY_ID}, database
);
} catch (FamiliarDbException e) {
handleFamiliarDbException(true);
DatabaseManager.getInstance(getActivity(), false).closeDatabase(false);
return;
}
mSets = new LinkedHashSet<>();
mCardIds = new LinkedHashSet<>();
while (!cCardByName.isAfterLast()) {
try {
if (mSets.add(CardDbAdapter
.getSetNameFromCode(cCardByName.getString(cCardByName.getColumnIndex(CardDbAdapter.KEY_SET)), database))) {
mCardIds.add(cCardByName.getLong(cCardByName.getColumnIndex(CardDbAdapter.KEY_ID)));
}
} catch (FamiliarDbException e) {
handleFamiliarDbException(true);
DatabaseManager.getInstance(getActivity(), false).closeDatabase(false);
return;
}
cCardByName.moveToNext();
}
cCardByName.close();
/* If it exists in only one set, remove the button from the menu */
if (mSets.size() == 1) {
mActivity.supportInvalidateOptionsMenu();
}
DatabaseManager.getInstance(getActivity(), false).closeDatabase(false);
if (mShouldReportView) {
reportAppIndexViewIfAble();
}
}
/**
* Used to build a meta description of this card, for app indexing
*
* @param tag A tag for this data
* @param data The data to add to the description
*/
private void addToDescription(String tag, String data) {
if (mDescription == null) {
mDescription = tag + ": \"" + data + "\"";
} else {
mDescription += "\n" + tag + ": \"" + data + "\"";
}
}
/**
* Remove any showing dialogs, and show the requested one
*
* @param id the ID of the dialog to show
*/
private void showDialog(final int id) throws IllegalStateException {
/* DialogFragment.show() will take care of adding the fragment in a transaction. We also want to remove any
currently showing dialog, so make our own transaction and take care of that here. */
/* If the fragment isn't visible (maybe being loaded by the pager), don't show dialogs */
if (!this.isVisible()) {
return;
}
removeDialog(getFragmentManager());
/* Create and show the dialog. */
final FamiliarDialogFragment newFragment = new FamiliarDialogFragment() {
@NotNull
@Override
@SuppressWarnings("SpellCheckingInspection")
public Dialog onCreateDialog(Bundle savedInstanceState) {
super.onCreateDialog(savedInstanceState);
/* This will be set to false if we are returning a null dialog. It prevents a crash */
setShowsDialog(true);
switch (id) {
case GET_IMAGE: {
if (mCardBitmap == null) {
return DontShowDialog();
}
Dialog dialog = new Dialog(mActivity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.card_view_image_dialog);
ImageView dialogImageView = (ImageView) dialog.findViewById(R.id.cardimage);
dialogImageView.setImageDrawable(mCardBitmap);
dialogImageView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
if (mAsyncTask != null) {
mAsyncTask.cancel(true);
}
mAsyncTask = new saveCardImageTask();
mAsyncTask.execute((Void[]) null);
return true;
}
});
return dialog;
}
case GET_LEGALITY: {
if (mFormats == null || mLegalities == null) {
/* exception handled in AsyncTask */
return DontShowDialog();
}
/* create the item mapping */
String[] from = new String[]{"format", "status"};
int[] to = new int[]{R.id.format, R.id.status};
/* prepare the list of all records */
List<HashMap<String, String>> fillMaps = new ArrayList<>();
for (int i = 0; i < mFormats.length; i++) {
HashMap<String, String> map = new HashMap<>();
map.put(from[0], mFormats[i]);
map.put(from[1], mLegalities[i]);
fillMaps.add(map);
}
SimpleAdapter adapter = new SimpleAdapter(mActivity, fillMaps, R.layout.card_view_legal_row,
from, to);
ListView lv = new ListView(mActivity);
lv.setAdapter(adapter);
AlertDialogPro.Builder builder = new AlertDialogPro.Builder(mActivity);
builder.setView(lv);
builder.setTitle(R.string.card_view_legality);
return builder.create();
}
case GET_PRICE: {
if (mPriceInfo == null) {
return DontShowDialog();
}
View v = mActivity.getLayoutInflater().inflate(R.layout.card_view_price_dialog, null, false);
assert v != null; /* Because Android Studio */
TextView l = (TextView) v.findViewById(R.id.low);
TextView m = (TextView) v.findViewById(R.id.med);
TextView h = (TextView) v.findViewById(R.id.high);
TextView f = (TextView) v.findViewById(R.id.foil);
TextView priceLink = (TextView) v.findViewById(R.id.pricelink);
l.setText(String.format("$%1$,.2f", mPriceInfo.mLow));
m.setText(String.format("$%1$,.2f", mPriceInfo.mAverage));
h.setText(String.format("$%1$,.2f", mPriceInfo.mHigh));
if (mPriceInfo.mFoilAverage != 0) {
f.setText(String.format("$%1$,.2f", mPriceInfo.mFoilAverage));
} else {
f.setVisibility(View.GONE);
v.findViewById(R.id.foil_label).setVisibility(View.GONE);
}
priceLink.setMovementMethod(LinkMovementMethod.getInstance());
priceLink.setText(ImageGetterHelper.formatHtmlString("<a href=\"" + mPriceInfo.mUrl + "\">" +
getString(R.string.card_view_price_dialog_link) + "</a>"));
AlertDialogPro.Builder adb = new AlertDialogPro.Builder(mActivity);
adb.setView(v);
adb.setTitle(R.string.card_view_price_dialog_title);
return adb.create();
}
case CHANGE_SET: {
final String[] aSets = mSets.toArray(new String[mSets.size()]);
final Long[] aIds = mCardIds.toArray(new Long[mCardIds.size()]);
/* Sanity check */
for (String set : aSets) {
if (set == null) {
return DontShowDialog();
}
}
AlertDialogPro.Builder builder = new AlertDialogPro.Builder(mActivity);
builder.setTitle(R.string.card_view_set_dialog_title);
builder.setItems(aSets, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int item) {
setInfoFromID(aIds[item]);
}
});
return builder.create();
}
case CARD_RULINGS: {
if (mRulingsArrayList == null) {
return DontShowDialog();
}
ImageGetter imgGetter = ImageGetterHelper.GlyphGetter(getActivity());
View v = mActivity.getLayoutInflater().inflate(R.layout.card_view_rulings_dialog, null, false);
assert v != null; /* Because Android Studio */
TextView textViewRules = (TextView) v.findViewById(R.id.rules);
TextView textViewUrl = (TextView) v.findViewById(R.id.url);
String message = "";
if (mRulingsArrayList.size() == 0) {
message = getString(R.string.card_view_no_rulings);
} else {
for (Ruling r : mRulingsArrayList) {
message += (r.toString() + "<br><br>");
}
message = message.replace("{Tap}", "{T}");
}
CharSequence messageGlyph = ImageGetterHelper.formatStringWithGlyphs(message, imgGetter);
textViewRules.setText(messageGlyph);
textViewUrl.setMovementMethod(LinkMovementMethod.getInstance());
textViewUrl.setText(Html.fromHtml(
"<a href=http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=" +
mMultiverseId + ">" + getString(R.string.card_view_gatherer_page) + "</a>"
));
AlertDialogPro.Builder builder = new AlertDialogPro.Builder(mActivity);
builder.setTitle(R.string.card_view_rulings_dialog_title);
builder.setView(v);
return builder.create();
}
case WISH_LIST_COUNTS: {
Dialog dialog = WishlistHelpers.getDialog(mCardName, CardViewFragment.this, false);
if (dialog == null) {
handleFamiliarDbException(false);
return DontShowDialog();
}
return dialog;
}
default: {
return DontShowDialog();
}
}
}
};
newFragment.show(getFragmentManager(), FamiliarActivity.DIALOG_TAG);
}
/**
* Called when a registered view is long-pressed. The menu inflated will give different options based on the view class
*
* @param menu The context menu that is being built
* @param v The view for which the context menu is being built
* @param menuInfo Extra information about the item for which the context menu should be shown. This information
* will vary depending on the class of v.
*/
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
TextView tv = (TextView) v;
assert tv.getText() != null;
mCopyString = tv.getText().toString();
android.view.MenuInflater inflater = this.mActivity.getMenuInflater();
inflater.inflate(R.menu.copy_menu, menu);
}
/**
* Copies text to the clipboard
*
* @param item The context menu item that was selected.
* @return boolean Return false to allow normal context menu processing to proceed, true to consume it here.
*/
@Override
public boolean onContextItemSelected(android.view.MenuItem item) {
if (getUserVisibleHint()) {
String copyText;
switch (item.getItemId()) {
case R.id.copy: {
copyText = mCopyString;
break;
}
case R.id.copyall: {
assert mNameTextView.getText() != null; /* Because Android Studio */
assert mCostTextView.getText() != null;
assert mTypeTextView.getText() != null;
assert mSetTextView.getText() != null;
assert mAbilityTextView.getText() != null;
assert mFlavorTextView.getText() != null;
assert mPowTouTextView.getText() != null;
assert mArtistTextView.getText() != null;
copyText = mNameTextView.getText().toString() + '\n' + mCostTextView.getText().toString() + '\n' +
mTypeTextView.getText().toString() + '\n' + mSetTextView.getText().toString() + '\n' +
mAbilityTextView.getText().toString() + '\n' + mFlavorTextView.getText().toString() + '\n' +
mPowTouTextView.getText().toString() + '\n' + mArtistTextView.getText().toString();
break;
}
default: {
return super.onContextItemSelected(item);
}
}
ClipboardManager clipboard = (ClipboardManager) (this.mActivity.
getSystemService(android.content.Context.CLIPBOARD_SERVICE));
String label = getResources().getString(R.string.app_name);
String mimeTypes[] = {ClipDescription.MIMETYPE_TEXT_PLAIN};
ClipData cd = new ClipData(label, mimeTypes, new ClipData.Item(copyText));
clipboard.setPrimaryClip(cd);
return true;
}
return false;
}
/**
* Handles clicks from the ActionBar
*
* @param item the item clicked
* @return true if acted upon, false if otherwise
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mCardName == null) {
/*disable menu buttons if the card isn't initialized */
return false;
}
/* Handle item selection */
switch (item.getItemId()) {
case R.id.image: {
if (getFamiliarActivity().getNetworkState(true) == -1) {
return true;
}
mActivity.setLoading();
if (mAsyncTask != null) {
mAsyncTask.cancel(true);
}
mAsyncTask = new FetchPictureTask();
mAsyncTask.execute((Void[]) null);
return true;
}
case R.id.price: {
mActivity.setLoading();
PriceFetchRequest priceRequest;
priceRequest = new PriceFetchRequest(mCardName, mSetCode, mCardNumber, mMultiverseId, getActivity());
mActivity.mSpiceManager.execute(priceRequest,
mCardName + "-" + mSetCode, DurationInMillis.ONE_DAY, new RequestListener<PriceInfo>() {
@Override
public void onRequestFailure(SpiceException spiceException) {
if (CardViewFragment.this.isAdded()) {
mActivity.clearLoading();
CardViewFragment.this.removeDialog(getFragmentManager());
ToastWrapper.makeText(mActivity, spiceException.getMessage(), ToastWrapper.LENGTH_SHORT).show();
}
}
@Override
public void onRequestSuccess(final PriceInfo result) {
if (CardViewFragment.this.isAdded()) {
mActivity.clearLoading();
if (result != null) {
mPriceInfo = result;
showDialog(GET_PRICE);
} else {
ToastWrapper.makeText(mActivity, R.string.card_view_price_not_found,
ToastWrapper.LENGTH_SHORT).show();
}
}
}
}
);
return true;
}
case R.id.changeset: {
showDialog(CHANGE_SET);
return true;
}
case R.id.legality: {
mActivity.setLoading();
if (mAsyncTask != null) {
mAsyncTask.cancel(true);
}
mAsyncTask = new FetchLegalityTask();
mAsyncTask.execute((Void[]) null);
return true;
}
case R.id.cardrulings: {
if (getFamiliarActivity().getNetworkState(true) == -1) {
return true;
}
mActivity.setLoading();
if (mAsyncTask != null) {
mAsyncTask.cancel(true);
}
mAsyncTask = new FetchRulingsTask();
mAsyncTask.execute((Void[]) null);
return true;
}
case R.id.addtowishlist: {
showDialog(WISH_LIST_COUNTS);
return true;
}
default: {
return super.onOptionsItemSelected(item);
}
}
}
/**
* Inflate the ActionBar items
*
* @param menu The options menu in which you place your items.
* @param inflater The inflater to use to inflate the menu
*/
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.card_menu, menu);
}
/**
* Prepare the Screen's standard options menu to be displayed. This is
* called right before the menu is shown, every time it is shown. You can
* use this method to efficiently enable/disable items or otherwise
* dynamically modify the contents.
*
* @param menu The options menu as last shown or first initialized by
* onCreateOptionsMenu().
* @see #setHasOptionsMenu
* @see #onCreateOptionsMenu
*/
@Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
MenuItem mi;
/* If the image has been loaded to the main page, remove the menu option for image */
if (loadTo == MAIN_PAGE && mCardBitmap != null) {
mi = menu.findItem(R.id.image);
if (mi != null) {
menu.removeItem(mi.getItemId());
}
}
/* This code removes the "change set" button if there is only one set.
* Turns out some users use it to view the full set name when there is only one set/
* I'm leaving it here, but commented, for posterity */
/*
if (mSets != null && mSets.size() == 1) {
mi = menu.findItem(R.id.changeset);
if (mi != null) {
menu.removeItem(mi.getItemId());
}
}
*/
}
/**
* This inner class encapsulates a ruling and the date it was made
*/
private static class Ruling {
public final String date;
public final String ruling;
public Ruling(String d, String r) {
date = d;
ruling = r;
}
public String toString() {
return date + ": " + ruling;
}
}
class saveCardImageTask extends AsyncTask<Void, Void, Void> {
String mToastString;
@Override
protected Void doInBackground(Void... voids) {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
mToastString = getString(R.string.card_view_no_external_storage);
return null;
}
String strPath;
try {
strPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
.getCanonicalPath() + "/MTGFamiliar";
} catch (IOException ex) {
mToastString = getString(R.string.card_view_no_pictures_folder);
return null;
}
File fPath = new File(strPath);
if (!fPath.exists()) {
fPath.mkdir();
if (!fPath.isDirectory()) {
mToastString = getString(R.string.card_view_unable_to_create_dir);
return null;
}
}
fPath = new File(strPath, mCardName + "_" + mSetCode + ".jpg");
if (fPath.exists()) {
fPath.delete();
}
try {
if (!fPath.createNewFile()) {
mToastString = getString(R.string.card_view_unable_to_create_file);
return null;
}
FileOutputStream fStream = new FileOutputStream(fPath);
/* If the card is displayed, there's a real good chance it's cached */
String cardLanguage = mActivity.mPreferenceAdapter.getCardLanguage();
if (cardLanguage == null) {
cardLanguage = "en";
}
String imageKey = Integer.toString(mMultiverseId) + cardLanguage;
Bitmap bmpImage;
try {
bmpImage = getFamiliarActivity().mImageCache.getBitmapFromDiskCache(imageKey);
} catch (NullPointerException e) {
bmpImage = null;
}
/* Check if this is an english only image */
if (bmpImage == null && !cardLanguage.equalsIgnoreCase("en")) {
imageKey = Integer.toString(mMultiverseId) + "en";
try {
bmpImage = getFamiliarActivity().mImageCache.getBitmapFromDiskCache(imageKey);
} catch (NullPointerException e) {
bmpImage = null;
}
}
/* nope, not here */
if (bmpImage == null) {
mToastString = getString(R.string.card_view_no_image);
return null;
}
boolean bCompressed = bmpImage.compress(Bitmap.CompressFormat.JPEG, 90, fStream);
if (!bCompressed) {
mToastString = getString(R.string.card_view_unable_to_save_image);
return null;
}
strPath = fPath.getCanonicalPath();
} catch (IOException ex) {
mToastString = getString(R.string.card_view_save_failure);
return null;
}
mToastString = getString(R.string.card_view_image_saved) + strPath;
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (mToastString != null) {
ToastWrapper.makeText(mActivity, mToastString, ToastWrapper.LENGTH_LONG).show();
}
}
}
/**
* This private class handles asking the database about the legality of a card, and will eventually show the
* information in a Dialog
*/
private class FetchLegalityTask extends AsyncTask<Void, Void, Void> {
/**
* Queries the data in the database to see what sets this card is legal in
*
* @param params unused
* @return unused
*/
@Override
protected Void doInBackground(Void... params) {
SQLiteDatabase database = DatabaseManager.getInstance(getActivity(), false).openDatabase(false);
try {
Cursor cFormats = CardDbAdapter.fetchAllFormats(database);
mFormats = new String[cFormats.getCount()];
mLegalities = new String[cFormats.getCount()];
cFormats.moveToFirst();
for (int i = 0; i < cFormats.getCount(); i++) {
mFormats[i] = cFormats.getString(cFormats.getColumnIndex(CardDbAdapter.KEY_NAME));
switch (CardDbAdapter.checkLegality(mCardName, mFormats[i], database)) {
case CardDbAdapter.LEGAL:
mLegalities[i] = getString(R.string.card_view_legal);
break;
case CardDbAdapter.RESTRICTED:
/* For backwards compatibility, we list cards that are legal
* in commander, but can't be the commander as Restricted in
* the legality file. This prevents older version of the app
* from throwing an IllegalStateException if we try including
* a new legality. */
if (mFormats[i].equalsIgnoreCase("Commander")) {
mLegalities[i] = getString(R.string.card_view_no_commander);
} else {
mLegalities[i] = getString(R.string.card_view_restricted);
}
break;
case CardDbAdapter.BANNED:
mLegalities[i] = getString(R.string.card_view_banned);
break;
default:
mLegalities[i] = getString(R.string.error);
break;
}
cFormats.moveToNext();
}
cFormats.close();
} catch (FamiliarDbException e) {
CardViewFragment.this.handleFamiliarDbException(false);
mLegalities = null;
}
DatabaseManager.getInstance(getActivity(), false).closeDatabase(false);
return null;
}
/**
* After the query, remove the progress dialog and show the legalities
*
* @param result unused
*/
@Override
protected void onPostExecute(Void result) {
try {
showDialog(GET_LEGALITY);
} catch (IllegalStateException e) {
/* eat it */
}
mActivity.clearLoading();
}
}
/**
* This private class retrieves a picture of the card from the internet
*/
private class FetchPictureTask extends AsyncTask<Void, Void, Void> {
private String error;
int mHeight;
int mWidth;
int mBorder;
/* Get the size of the window on the UI thread, not the worker thread */
final Runnable getWindowSize = new Runnable() {
@Override
public void run() {
Rect rectangle = new Rect();
mActivity.getWindow().getDecorView().getWindowVisibleDisplayFrame(rectangle);
assert mActivity.getSupportActionBar() != null; /* Because Android Studio */
mHeight = ((rectangle.bottom - rectangle.top) - mActivity.getSupportActionBar().getHeight()) - mBorder;
mWidth = (rectangle.right - rectangle.left) - mBorder;
synchronized (this) {
this.notify();
}
}
};
/**
* First check www.MagicCards.info for the card image in the user's preferred language
* If that fails, check www.MagicCards.info for the card image in English
* If that fails, check www.gatherer.wizards.com for the card image
* If that fails, give up
* There is non-standard URL building for planes and schemes
* It also re-sizes the image
*
* @param params unused
* @return unused
*/
@SuppressWarnings("SpellCheckingInspection")
@Override
protected Void doInBackground(Void... params) {
String cardLanguage = mActivity.mPreferenceAdapter.getCardLanguage();
if (cardLanguage == null) {
cardLanguage = "en";
}
final String imageKey = Integer.toString(mMultiverseId) + cardLanguage;
/* Check disk cache in background thread */
Bitmap bitmap;
try {
bitmap = getFamiliarActivity().mImageCache.getBitmapFromDiskCache(imageKey);
} catch (NullPointerException e) {
bitmap = null;
}
if (bitmap == null) { /* Not found in disk cache */
boolean bRetry = true;
boolean triedMtgi = false;
boolean triedGatherer = false;
while (bRetry) {
bRetry = false;
error = null;
try {
URL u;
if (!cardLanguage.equalsIgnoreCase("en")) {
u = new URL(getMtgiPicUrl(mCardName, mMagicCardsInfoSetCode, mCardNumber, cardLanguage));
cardLanguage = "en";
} else {
if (!triedMtgi) {
u = new URL(getMtgiPicUrl(mCardName, mMagicCardsInfoSetCode, mCardNumber, cardLanguage));
triedMtgi = true;
} else {
u = new URL("http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid="
+ mMultiverseId + "&type=card");
triedGatherer = true;
}
}
mCardBitmap = new RecyclingBitmapDrawable(mActivity.getResources(), BitmapFactory.decodeStream(u.openStream()));
bitmap = mCardBitmap.getBitmap();
getFamiliarActivity().mImageCache.addBitmapToCache(imageKey, mCardBitmap);
} catch (Exception e) {
/* Something went wrong */
error = getString(R.string.card_view_image_not_found);
if (!triedGatherer) {
bRetry = true;
}
}
}
}
if (bitmap == null) {
return null;
}
try {
/* 16dp */
mBorder = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 16, getResources().getDisplayMetrics());
if (loadTo == MAIN_PAGE) {
/* Block the worker thread until the size is figured out */
synchronized (getWindowSize) {
getActivity().runOnUiThread(getWindowSize);
getWindowSize.wait();
}
} else if (loadTo == DIALOG) {
Display display = ((WindowManager) mActivity
.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
Point p = new Point();
display.getSize(p);
mHeight = p.y - mBorder;
mWidth = p.x - mBorder;
}
float screenAspectRatio = (float) mHeight / (float) (mWidth);
float cardAspectRatio = (float) bitmap.getHeight() / (float) bitmap.getWidth();
float scale;
if (screenAspectRatio > cardAspectRatio) {
scale = (mWidth) / (float) bitmap.getWidth();
} else {
scale = (mHeight) / (float) bitmap.getHeight();
}
int newWidth = Math.round(bitmap.getWidth() * scale);
int newHeight = Math.round(bitmap.getHeight() * scale);
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true); /* todo this is leaky? */
mCardBitmap = new RecyclingBitmapDrawable(mActivity.getResources(), scaledBitmap);
bitmap.recycle();
} catch (Exception e) {
/* Some error resizing. Out of memory? */
}
return null;
}
/**
* Jumps through hoops and returns a correctly formatted URL for magiccards.info's image
*
* @param cardName The name of the card
* @param magicCardsInfoSetCode The set of the card
* @param cardNumber The number of the card
* @param cardLanguage The language of the card
* @return a URL to the card's image
*/
private String getMtgiPicUrl(String cardName, String magicCardsInfoSetCode, String cardNumber,
String cardLanguage) {
String picURL;
if (mCardType.toLowerCase().contains(getString(R.string.search_Ongoing).toLowerCase()) ||
/* extra space to not confuse with planeswalker */
mCardType.toLowerCase().contains(getString(R.string.search_Plane).toLowerCase() + " ") ||
mCardType.toLowerCase().contains(getString(R.string.search_Phenomenon).toLowerCase()) ||
mCardType.toLowerCase().contains(getString(R.string.search_Scheme).toLowerCase())) {
switch (mSetCode) {
case "PC2":
picURL = "http://magiccards.info/extras/plane/planechase-2012-edition/" + cardName + ".jpg";
picURL = picURL.replace(" ", "-").replace(Character.toChars(0xC6)[0] + "", "Ae")
.replace("?", "").replace(",", "").replace("'", "").replace("!", "");
break;
case "PCH":
if (cardName.equalsIgnoreCase("tazeem")) {
cardName = "tazeem-release-promo";
} else if (cardName.equalsIgnoreCase("celestine reef")) {
cardName = "celestine-reef-pre-release-promo";
} else if (cardName.equalsIgnoreCase("horizon boughs")) {
cardName = "horizon-boughs-gateway-promo";
}
picURL = "http://magiccards.info/extras/plane/planechase/" + cardName + ".jpg";
picURL = picURL.replace(" ", "-").replace(Character.toChars(0xC6)[0] + "", "Ae")
.replace("?", "").replace(",", "").replace("'", "").replace("!", "");
break;
case "ARC":
picURL = "http://magiccards.info/extras/scheme/archenemy/" + cardName + ".jpg";
picURL = picURL.replace(" ", "-").replace(Character.toChars(0xC6)[0] + "", "Ae")
.replace("?", "").replace(",", "").replace("'", "").replace("!", "");
break;
default:
picURL = "http://magiccards.info/scans/" + cardLanguage + "/" + magicCardsInfoSetCode + "/" +
cardNumber + ".jpg";
break;
}
} else {
picURL = "http://magiccards.info/scans/" + cardLanguage + "/" + magicCardsInfoSetCode + "/" +
cardNumber + ".jpg";
}
return picURL.toLowerCase(Locale.ENGLISH);
}
/**
* When the task has finished, if there was no error, remove the progress dialog and show the image
* If the image was supposed to load to the main screen, and it failed to load, fall back to text view
*
* @param result unused
*/
@Override
protected void onPostExecute(Void result) {
if (error == null) {
if (loadTo == DIALOG) {
try {
showDialog(GET_IMAGE);
} catch (IllegalStateException e) {
/* eat it */
}
} else if (loadTo == MAIN_PAGE) {
removeDialog(getFragmentManager());
mCardImageView.setImageDrawable(mCardBitmap);
/* remove the image load button if it is the main page */
mActivity.supportInvalidateOptionsMenu();
}
} else {
removeDialog(getFragmentManager());
if (loadTo == MAIN_PAGE) {
mImageScrollView.setVisibility(View.GONE);
mTextScrollView.setVisibility(View.VISIBLE);
}
ToastWrapper.makeText(mActivity, error, ToastWrapper.LENGTH_LONG).show();
}
mActivity.clearLoading();
}
/**
* If the task is canceled, fall back to text view
*/
@Override
protected void onCancelled() {
if (loadTo == MAIN_PAGE) {
mImageScrollView.setVisibility(View.GONE);
mTextScrollView.setVisibility(View.VISIBLE);
}
}
}
/**
* This private class fetches rulings about this card from gatherer.wizards.com
*/
private class FetchRulingsTask extends AsyncTask<Void, Void, Void> {
String mErrorMessage = null;
/**
* This function downloads the source of the gatherer page, scans it for rulings, and stores them for display
*
* @param params unused
* @return unused
*/
@Override
@SuppressWarnings("SpellCheckingInspection")
protected Void doInBackground(Void... params) {
URL url;
InputStream is = null;
BufferedReader br;
String line;
mRulingsArrayList = new ArrayList<>();
try {
url = new URL("http://gatherer.wizards.com/Pages/Card/Details.aspx?multiverseid=" + mMultiverseId);
is = url.openStream(); /* throws an IOException */
br = new BufferedReader(new InputStreamReader(new BufferedInputStream(is)));
String date = null, ruling;
while ((line = br.readLine()) != null) {
if (line.contains("rulingDate") && line.contains("<td")) {
date = (line.replace("<autocard>", "").replace("</autocard>", ""))
.split(">")[1].split("<")[0];
}
if (line.contains("rulingText") && line.contains("<td")) {
ruling = (line.replace("<autocard>", "").replace("</autocard>", ""))
.split(">")[1].split("<")[0];
Ruling r = new Ruling(date, ruling);
mRulingsArrayList.add(r);
}
}
} catch (IOException ioe) {
mErrorMessage = ioe.getLocalizedMessage();
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException ioe) {
mErrorMessage = ioe.getLocalizedMessage();
}
}
return null;
}
/**
* Hide the progress dialog and show the rulings, if there are no errors
*
* @param result unused
*/
@Override
protected void onPostExecute(Void result) {
if (mErrorMessage == null) {
try {
showDialog(CARD_RULINGS);
} catch (IllegalStateException e) {
/* eat it */
}
} else {
removeDialog(getFragmentManager());
ToastWrapper.makeText(mActivity, mErrorMessage, ToastWrapper.LENGTH_SHORT).show();
}
mActivity.clearLoading();
}
}
} | Catch exception if a fragment is unattached
| MTGFamiliar/src/main/java/com/gelakinetic/mtgfam/fragments/CardViewFragment.java | Catch exception if a fragment is unattached |
|
Java | mit | f68638a8fa05fcf665faf4dde926d3ea0e9d36bd | 0 | azweb76/jenkins,jk47/jenkins,jcarrothers-sap/jenkins,FarmGeek4Life/jenkins,singh88/jenkins,lordofthejars/jenkins,h4ck3rm1k3/jenkins,khmarbaise/jenkins,jpederzolli/jenkins-1,duzifang/my-jenkins,Vlatombe/jenkins,khmarbaise/jenkins,singh88/jenkins,amuniz/jenkins,amruthsoft9/Jenkis,elkingtonmcb/jenkins,rsandell/jenkins,samatdav/jenkins,dariver/jenkins,dariver/jenkins,hemantojhaa/jenkins,mattclark/jenkins,FTG-003/jenkins,thomassuckow/jenkins,Jimilian/jenkins,CodeShane/jenkins,samatdav/jenkins,vvv444/jenkins,DanielWeber/jenkins,FTG-003/jenkins,NehemiahMi/jenkins,dennisjlee/jenkins,fbelzunc/jenkins,everyonce/jenkins,varmenise/jenkins,huybrechts/hudson,huybrechts/hudson,jzjzjzj/jenkins,daspilker/jenkins,verbitan/jenkins,SenolOzer/jenkins,albers/jenkins,andresrc/jenkins,DanielWeber/jenkins,godfath3r/jenkins,arcivanov/jenkins,dbroady1/jenkins,mcanthony/jenkins,seanlin816/jenkins,escoem/jenkins,mcanthony/jenkins,github-api-test-org/jenkins,andresrc/jenkins,KostyaSha/jenkins,ChrisA89/jenkins,pjanouse/jenkins,292388900/jenkins,SebastienGllmt/jenkins,Vlatombe/jenkins,ikedam/jenkins,rashmikanta-1984/jenkins,verbitan/jenkins,hashar/jenkins,DanielWeber/jenkins,h4ck3rm1k3/jenkins,KostyaSha/jenkins,msrb/jenkins,kohsuke/hudson,paulwellnerbou/jenkins,github-api-test-org/jenkins,Vlatombe/jenkins,aquarellian/jenkins,morficus/jenkins,Krasnyanskiy/jenkins,NehemiahMi/jenkins,liorhson/jenkins,6WIND/jenkins,liorhson/jenkins,jpbriend/jenkins,synopsys-arc-oss/jenkins,akshayabd/jenkins,DanielWeber/jenkins,gusreiber/jenkins,hplatou/jenkins,ndeloof/jenkins,Jochen-A-Fuerbacher/jenkins,jpederzolli/jenkins-1,brunocvcunha/jenkins,deadmoose/jenkins,NehemiahMi/jenkins,maikeffi/hudson,rlugojr/jenkins,gitaccountforprashant/gittest,petermarcoen/jenkins,jglick/jenkins,everyonce/jenkins,KostyaSha/jenkins,patbos/jenkins,lindzh/jenkins,oleg-nenashev/jenkins,seanlin816/jenkins,msrb/jenkins,KostyaSha/jenkins,azweb76/jenkins,maikeffi/hudson,SenolOzer/jenkins,iqstack/jenkins,paulmillar/jenkins,aquarellian/jenkins,liorhson/jenkins,thomassuckow/jenkins,andresrc/jenkins,fbelzunc/jenkins,my7seven/jenkins,Krasnyanskiy/jenkins,gorcz/jenkins,vvv444/jenkins,paulmillar/jenkins,dbroady1/jenkins,MichaelPranovich/jenkins_sc,vvv444/jenkins,jglick/jenkins,amuniz/jenkins,escoem/jenkins,elkingtonmcb/jenkins,Wilfred/jenkins,varmenise/jenkins,sathiya-mit/jenkins,hemantojhaa/jenkins,samatdav/jenkins,stephenc/jenkins,hplatou/jenkins,azweb76/jenkins,akshayabd/jenkins,nandan4/Jenkins,scoheb/jenkins,vijayto/jenkins,akshayabd/jenkins,lilyJi/jenkins,MarkEWaite/jenkins,deadmoose/jenkins,ydubreuil/jenkins,intelchen/jenkins,jglick/jenkins,CodeShane/jenkins,daspilker/jenkins,bkmeneguello/jenkins,292388900/jenkins,tfennelly/jenkins,seanlin816/jenkins,gusreiber/jenkins,deadmoose/jenkins,huybrechts/hudson,NehemiahMi/jenkins,arunsingh/jenkins,jenkinsci/jenkins,jk47/jenkins,KostyaSha/jenkins,csimons/jenkins,petermarcoen/jenkins,olivergondza/jenkins,FarmGeek4Life/jenkins,vvv444/jenkins,hemantojhaa/jenkins,batmat/jenkins,arcivanov/jenkins,aldaris/jenkins,vjuranek/jenkins,pjanouse/jenkins,h4ck3rm1k3/jenkins,DanielWeber/jenkins,msrb/jenkins,tangkun75/jenkins,paulwellnerbou/jenkins,deadmoose/jenkins,MarkEWaite/jenkins,my7seven/jenkins,lindzh/jenkins,tfennelly/jenkins,MarkEWaite/jenkins,1and1/jenkins,gitaccountforprashant/gittest,ikedam/jenkins,rashmikanta-1984/jenkins,Jimilian/jenkins,arunsingh/jenkins,wangyikai/jenkins,lindzh/jenkins,SenolOzer/jenkins,synopsys-arc-oss/jenkins,hemantojhaa/jenkins,guoxu0514/jenkins,SebastienGllmt/jenkins,kohsuke/hudson,hplatou/jenkins,fbelzunc/jenkins,mdonohue/jenkins,bpzhang/jenkins,Ykus/jenkins,daniel-beck/jenkins,recena/jenkins,protazy/jenkins,protazy/jenkins,intelchen/jenkins,oleg-nenashev/jenkins,FarmGeek4Life/jenkins,vijayto/jenkins,jcsirot/jenkins,khmarbaise/jenkins,jzjzjzj/jenkins,soenter/jenkins,Ykus/jenkins,ikedam/jenkins,recena/jenkins,noikiy/jenkins,ndeloof/jenkins,varmenise/jenkins,jhoblitt/jenkins,ikedam/jenkins,scoheb/jenkins,292388900/jenkins,wangyikai/jenkins,jenkinsci/jenkins,jglick/jenkins,goldchang/jenkins,intelchen/jenkins,olivergondza/jenkins,v1v/jenkins,morficus/jenkins,noikiy/jenkins,csimons/jenkins,tangkun75/jenkins,jenkinsci/jenkins,pselle/jenkins,aduprat/jenkins,seanlin816/jenkins,AustinKwang/jenkins,wuwen5/jenkins,wangyikai/jenkins,jenkinsci/jenkins,escoem/jenkins,jcsirot/jenkins,soenter/jenkins,bkmeneguello/jenkins,scoheb/jenkins,kohsuke/hudson,guoxu0514/jenkins,jenkinsci/jenkins,keyurpatankar/hudson,jcsirot/jenkins,vjuranek/jenkins,evernat/jenkins,KostyaSha/jenkins,dennisjlee/jenkins,bpzhang/jenkins,aduprat/jenkins,aquarellian/jenkins,soenter/jenkins,tfennelly/jenkins,duzifang/my-jenkins,oleg-nenashev/jenkins,alvarolobato/jenkins,ikedam/jenkins,chbiel/jenkins,mcanthony/jenkins,varmenise/jenkins,liupugong/jenkins,luoqii/jenkins,v1v/jenkins,v1v/jenkins,liupugong/jenkins,luoqii/jenkins,FarmGeek4Life/jenkins,AustinKwang/jenkins,soenter/jenkins,everyonce/jenkins,gorcz/jenkins,stephenc/jenkins,arcivanov/jenkins,SebastienGllmt/jenkins,jcarrothers-sap/jenkins,tastatur/jenkins,arcivanov/jenkins,svanoort/jenkins,ChrisA89/jenkins,CodeShane/jenkins,dariver/jenkins,daniel-beck/jenkins,maikeffi/hudson,sathiya-mit/jenkins,andresrc/jenkins,seanlin816/jenkins,shahharsh/jenkins,Vlatombe/jenkins,Jochen-A-Fuerbacher/jenkins,tastatur/jenkins,kzantow/jenkins,daniel-beck/jenkins,gorcz/jenkins,Ykus/jenkins,azweb76/jenkins,recena/jenkins,Jimilian/jenkins,6WIND/jenkins,batmat/jenkins,lilyJi/jenkins,Jochen-A-Fuerbacher/jenkins,albers/jenkins,elkingtonmcb/jenkins,jhoblitt/jenkins,andresrc/jenkins,thomassuckow/jenkins,mcanthony/jenkins,mrooney/jenkins,albers/jenkins,CodeShane/jenkins,elkingtonmcb/jenkins,rsandell/jenkins,CodeShane/jenkins,v1v/jenkins,arcivanov/jenkins,shahharsh/jenkins,mcanthony/jenkins,amruthsoft9/Jenkis,christ66/jenkins,fbelzunc/jenkins,jpbriend/jenkins,DanielWeber/jenkins,h4ck3rm1k3/jenkins,mrooney/jenkins,godfath3r/jenkins,albers/jenkins,aquarellian/jenkins,jhoblitt/jenkins,dennisjlee/jenkins,rsandell/jenkins,petermarcoen/jenkins,albers/jenkins,akshayabd/jenkins,christ66/jenkins,DoctorQ/jenkins,aldaris/jenkins,tangkun75/jenkins,rsandell/jenkins,Jimilian/jenkins,my7seven/jenkins,iqstack/jenkins,samatdav/jenkins,gitaccountforprashant/gittest,rashmikanta-1984/jenkins,rsandell/jenkins,ErikVerheul/jenkins,protazy/jenkins,hashar/jenkins,kzantow/jenkins,verbitan/jenkins,wuwen5/jenkins,christ66/jenkins,intelchen/jenkins,thomassuckow/jenkins,bkmeneguello/jenkins,Jochen-A-Fuerbacher/jenkins,ajshastri/jenkins,gusreiber/jenkins,gitaccountforprashant/gittest,1and1/jenkins,tastatur/jenkins,mattclark/jenkins,duzifang/my-jenkins,goldchang/jenkins,liupugong/jenkins,vjuranek/jenkins,arunsingh/jenkins,jpederzolli/jenkins-1,ndeloof/jenkins,ydubreuil/jenkins,aduprat/jenkins,morficus/jenkins,maikeffi/hudson,NehemiahMi/jenkins,bpzhang/jenkins,jk47/jenkins,lilyJi/jenkins,Vlatombe/jenkins,SenolOzer/jenkins,patbos/jenkins,sathiya-mit/jenkins,gitaccountforprashant/gittest,my7seven/jenkins,ErikVerheul/jenkins,mcanthony/jenkins,jcsirot/jenkins,Krasnyanskiy/jenkins,DoctorQ/jenkins,nandan4/Jenkins,my7seven/jenkins,petermarcoen/jenkins,synopsys-arc-oss/jenkins,godfath3r/jenkins,duzifang/my-jenkins,gitaccountforprashant/gittest,huybrechts/hudson,christ66/jenkins,recena/jenkins,fbelzunc/jenkins,FarmGeek4Life/jenkins,daspilker/jenkins,1and1/jenkins,wuwen5/jenkins,jzjzjzj/jenkins,maikeffi/hudson,jpederzolli/jenkins-1,aduprat/jenkins,rashmikanta-1984/jenkins,godfath3r/jenkins,lindzh/jenkins,noikiy/jenkins,luoqii/jenkins,daspilker/jenkins,viqueen/jenkins,albers/jenkins,stephenc/jenkins,MadsNielsen/jtemp,bkmeneguello/jenkins,batmat/jenkins,yonglehou/jenkins,v1v/jenkins,huybrechts/hudson,ajshastri/jenkins,KostyaSha/jenkins,paulwellnerbou/jenkins,aldaris/jenkins,kohsuke/hudson,alvarolobato/jenkins,Ykus/jenkins,kohsuke/hudson,damianszczepanik/jenkins,Jimilian/jenkins,goldchang/jenkins,dariver/jenkins,MarkEWaite/jenkins,vlajos/jenkins,scoheb/jenkins,wuwen5/jenkins,dariver/jenkins,Wilfred/jenkins,shahharsh/jenkins,christ66/jenkins,paulmillar/jenkins,SenolOzer/jenkins,everyonce/jenkins,Vlatombe/jenkins,protazy/jenkins,arunsingh/jenkins,pjanouse/jenkins,samatdav/jenkins,keyurpatankar/hudson,alvarolobato/jenkins,amuniz/jenkins,aldaris/jenkins,mdonohue/jenkins,jpederzolli/jenkins-1,csimons/jenkins,olivergondza/jenkins,intelchen/jenkins,tfennelly/jenkins,ydubreuil/jenkins,vlajos/jenkins,wangyikai/jenkins,nandan4/Jenkins,chbiel/jenkins,duzifang/my-jenkins,everyonce/jenkins,vijayto/jenkins,dennisjlee/jenkins,shahharsh/jenkins,rashmikanta-1984/jenkins,guoxu0514/jenkins,goldchang/jenkins,evernat/jenkins,christ66/jenkins,verbitan/jenkins,dbroady1/jenkins,ChrisA89/jenkins,liorhson/jenkins,verbitan/jenkins,singh88/jenkins,github-api-test-org/jenkins,dbroady1/jenkins,ydubreuil/jenkins,goldchang/jenkins,vlajos/jenkins,khmarbaise/jenkins,tangkun75/jenkins,hashar/jenkins,github-api-test-org/jenkins,albers/jenkins,tangkun75/jenkins,github-api-test-org/jenkins,wuwen5/jenkins,jhoblitt/jenkins,rashmikanta-1984/jenkins,ErikVerheul/jenkins,pselle/jenkins,patbos/jenkins,ns163/jenkins,mdonohue/jenkins,maikeffi/hudson,alvarolobato/jenkins,morficus/jenkins,hashar/jenkins,sathiya-mit/jenkins,viqueen/jenkins,yonglehou/jenkins,mcanthony/jenkins,Wilfred/jenkins,lilyJi/jenkins,damianszczepanik/jenkins,rsandell/jenkins,godfath3r/jenkins,liorhson/jenkins,huybrechts/hudson,oleg-nenashev/jenkins,iqstack/jenkins,soenter/jenkins,kzantow/jenkins,lordofthejars/jenkins,deadmoose/jenkins,lordofthejars/jenkins,amruthsoft9/Jenkis,paulwellnerbou/jenkins,mrooney/jenkins,svanoort/jenkins,MadsNielsen/jtemp,tastatur/jenkins,pjanouse/jenkins,jk47/jenkins,vjuranek/jenkins,jpederzolli/jenkins-1,shahharsh/jenkins,scoheb/jenkins,pselle/jenkins,mdonohue/jenkins,petermarcoen/jenkins,stephenc/jenkins,sathiya-mit/jenkins,gorcz/jenkins,batmat/jenkins,lordofthejars/jenkins,ydubreuil/jenkins,batmat/jenkins,paulwellnerbou/jenkins,gorcz/jenkins,Ykus/jenkins,kohsuke/hudson,nandan4/Jenkins,ikedam/jenkins,tfennelly/jenkins,brunocvcunha/jenkins,AustinKwang/jenkins,damianszczepanik/jenkins,6WIND/jenkins,tastatur/jenkins,paulmillar/jenkins,nandan4/Jenkins,morficus/jenkins,dariver/jenkins,protazy/jenkins,lilyJi/jenkins,noikiy/jenkins,DoctorQ/jenkins,mrooney/jenkins,varmenise/jenkins,MarkEWaite/jenkins,6WIND/jenkins,akshayabd/jenkins,ns163/jenkins,ajshastri/jenkins,oleg-nenashev/jenkins,1and1/jenkins,brunocvcunha/jenkins,292388900/jenkins,dennisjlee/jenkins,github-api-test-org/jenkins,FTG-003/jenkins,hplatou/jenkins,protazy/jenkins,recena/jenkins,tfennelly/jenkins,rashmikanta-1984/jenkins,ChrisA89/jenkins,svanoort/jenkins,jenkinsci/jenkins,singh88/jenkins,MadsNielsen/jtemp,pselle/jenkins,daniel-beck/jenkins,fbelzunc/jenkins,h4ck3rm1k3/jenkins,hashar/jenkins,MichaelPranovich/jenkins_sc,soenter/jenkins,jenkinsci/jenkins,ChrisA89/jenkins,vjuranek/jenkins,ErikVerheul/jenkins,kzantow/jenkins,batmat/jenkins,verbitan/jenkins,ns163/jenkins,pjanouse/jenkins,oleg-nenashev/jenkins,1and1/jenkins,nandan4/Jenkins,andresrc/jenkins,vlajos/jenkins,ydubreuil/jenkins,amuniz/jenkins,christ66/jenkins,pselle/jenkins,Wilfred/jenkins,hemantojhaa/jenkins,ikedam/jenkins,csimons/jenkins,MichaelPranovich/jenkins_sc,dariver/jenkins,jk47/jenkins,jpederzolli/jenkins-1,brunocvcunha/jenkins,6WIND/jenkins,goldchang/jenkins,nandan4/Jenkins,chbiel/jenkins,paulwellnerbou/jenkins,lordofthejars/jenkins,dbroady1/jenkins,jzjzjzj/jenkins,arunsingh/jenkins,singh88/jenkins,svanoort/jenkins,deadmoose/jenkins,thomassuckow/jenkins,protazy/jenkins,fbelzunc/jenkins,jpbriend/jenkins,verbitan/jenkins,mrooney/jenkins,rlugojr/jenkins,Jochen-A-Fuerbacher/jenkins,viqueen/jenkins,everyonce/jenkins,DoctorQ/jenkins,iqstack/jenkins,jcsirot/jenkins,viqueen/jenkins,vijayto/jenkins,pjanouse/jenkins,hplatou/jenkins,my7seven/jenkins,SenolOzer/jenkins,gusreiber/jenkins,mattclark/jenkins,FTG-003/jenkins,evernat/jenkins,amuniz/jenkins,stephenc/jenkins,khmarbaise/jenkins,samatdav/jenkins,wangyikai/jenkins,MarkEWaite/jenkins,gusreiber/jenkins,DoctorQ/jenkins,stephenc/jenkins,svanoort/jenkins,SebastienGllmt/jenkins,yonglehou/jenkins,morficus/jenkins,jpbriend/jenkins,liupugong/jenkins,keyurpatankar/hudson,Jochen-A-Fuerbacher/jenkins,duzifang/my-jenkins,daspilker/jenkins,kzantow/jenkins,chbiel/jenkins,lindzh/jenkins,jcarrothers-sap/jenkins,Jochen-A-Fuerbacher/jenkins,ndeloof/jenkins,jglick/jenkins,msrb/jenkins,samatdav/jenkins,gorcz/jenkins,godfath3r/jenkins,jzjzjzj/jenkins,FTG-003/jenkins,rsandell/jenkins,Vlatombe/jenkins,msrb/jenkins,arcivanov/jenkins,olivergondza/jenkins,msrb/jenkins,NehemiahMi/jenkins,amuniz/jenkins,h4ck3rm1k3/jenkins,DoctorQ/jenkins,hplatou/jenkins,vvv444/jenkins,luoqii/jenkins,jhoblitt/jenkins,huybrechts/hudson,keyurpatankar/hudson,kzantow/jenkins,vjuranek/jenkins,chbiel/jenkins,292388900/jenkins,amruthsoft9/Jenkis,ErikVerheul/jenkins,github-api-test-org/jenkins,jcsirot/jenkins,sathiya-mit/jenkins,singh88/jenkins,dbroady1/jenkins,ndeloof/jenkins,h4ck3rm1k3/jenkins,DanielWeber/jenkins,escoem/jenkins,wangyikai/jenkins,viqueen/jenkins,kohsuke/hudson,synopsys-arc-oss/jenkins,wuwen5/jenkins,jcarrothers-sap/jenkins,ajshastri/jenkins,sathiya-mit/jenkins,intelchen/jenkins,keyurpatankar/hudson,vlajos/jenkins,ikedam/jenkins,mdonohue/jenkins,csimons/jenkins,ns163/jenkins,keyurpatankar/hudson,batmat/jenkins,aquarellian/jenkins,ErikVerheul/jenkins,MichaelPranovich/jenkins_sc,tangkun75/jenkins,guoxu0514/jenkins,ajshastri/jenkins,rlugojr/jenkins,duzifang/my-jenkins,hemantojhaa/jenkins,patbos/jenkins,olivergondza/jenkins,MarkEWaite/jenkins,292388900/jenkins,Krasnyanskiy/jenkins,lilyJi/jenkins,1and1/jenkins,vjuranek/jenkins,AustinKwang/jenkins,SebastienGllmt/jenkins,evernat/jenkins,svanoort/jenkins,pselle/jenkins,mdonohue/jenkins,khmarbaise/jenkins,viqueen/jenkins,csimons/jenkins,vlajos/jenkins,Wilfred/jenkins,ndeloof/jenkins,brunocvcunha/jenkins,lordofthejars/jenkins,brunocvcunha/jenkins,ajshastri/jenkins,amruthsoft9/Jenkis,azweb76/jenkins,evernat/jenkins,tfennelly/jenkins,bpzhang/jenkins,synopsys-arc-oss/jenkins,hashar/jenkins,alvarolobato/jenkins,FarmGeek4Life/jenkins,shahharsh/jenkins,mattclark/jenkins,damianszczepanik/jenkins,MadsNielsen/jtemp,ChrisA89/jenkins,jglick/jenkins,patbos/jenkins,hemantojhaa/jenkins,seanlin816/jenkins,maikeffi/hudson,rlugojr/jenkins,vlajos/jenkins,yonglehou/jenkins,liupugong/jenkins,FTG-003/jenkins,yonglehou/jenkins,6WIND/jenkins,scoheb/jenkins,Krasnyanskiy/jenkins,iqstack/jenkins,CodeShane/jenkins,pselle/jenkins,jzjzjzj/jenkins,jpbriend/jenkins,mattclark/jenkins,aduprat/jenkins,MichaelPranovich/jenkins_sc,mattclark/jenkins,MadsNielsen/jtemp,ndeloof/jenkins,Wilfred/jenkins,iqstack/jenkins,vijayto/jenkins,arunsingh/jenkins,kzantow/jenkins,evernat/jenkins,Jimilian/jenkins,jcarrothers-sap/jenkins,synopsys-arc-oss/jenkins,MichaelPranovich/jenkins_sc,liupugong/jenkins,Ykus/jenkins,keyurpatankar/hudson,morficus/jenkins,viqueen/jenkins,alvarolobato/jenkins,NehemiahMi/jenkins,daniel-beck/jenkins,Krasnyanskiy/jenkins,svanoort/jenkins,vvv444/jenkins,SenolOzer/jenkins,elkingtonmcb/jenkins,escoem/jenkins,DoctorQ/jenkins,chbiel/jenkins,azweb76/jenkins,recena/jenkins,v1v/jenkins,rsandell/jenkins,daniel-beck/jenkins,dennisjlee/jenkins,lindzh/jenkins,jk47/jenkins,ns163/jenkins,olivergondza/jenkins,Ykus/jenkins,iqstack/jenkins,gusreiber/jenkins,everyonce/jenkins,ajshastri/jenkins,intelchen/jenkins,aquarellian/jenkins,escoem/jenkins,thomassuckow/jenkins,ns163/jenkins,Jimilian/jenkins,v1v/jenkins,noikiy/jenkins,jzjzjzj/jenkins,petermarcoen/jenkins,vijayto/jenkins,daniel-beck/jenkins,6WIND/jenkins,guoxu0514/jenkins,olivergondza/jenkins,DoctorQ/jenkins,guoxu0514/jenkins,elkingtonmcb/jenkins,arcivanov/jenkins,akshayabd/jenkins,singh88/jenkins,ns163/jenkins,rlugojr/jenkins,lindzh/jenkins,scoheb/jenkins,daspilker/jenkins,github-api-test-org/jenkins,jpbriend/jenkins,kohsuke/hudson,arunsingh/jenkins,azweb76/jenkins,alvarolobato/jenkins,evernat/jenkins,paulmillar/jenkins,damianszczepanik/jenkins,chbiel/jenkins,khmarbaise/jenkins,maikeffi/hudson,luoqii/jenkins,luoqii/jenkins,AustinKwang/jenkins,mrooney/jenkins,jhoblitt/jenkins,bpzhang/jenkins,292388900/jenkins,jenkinsci/jenkins,gorcz/jenkins,paulmillar/jenkins,aldaris/jenkins,brunocvcunha/jenkins,ErikVerheul/jenkins,AustinKwang/jenkins,CodeShane/jenkins,SebastienGllmt/jenkins,lilyJi/jenkins,tangkun75/jenkins,rlugojr/jenkins,MadsNielsen/jtemp,luoqii/jenkins,noikiy/jenkins,csimons/jenkins,AustinKwang/jenkins,akshayabd/jenkins,andresrc/jenkins,goldchang/jenkins,jhoblitt/jenkins,MarkEWaite/jenkins,patbos/jenkins,recena/jenkins,mrooney/jenkins,oleg-nenashev/jenkins,damianszczepanik/jenkins,varmenise/jenkins,bpzhang/jenkins,bpzhang/jenkins,jcarrothers-sap/jenkins,wangyikai/jenkins,wuwen5/jenkins,tastatur/jenkins,1and1/jenkins,rlugojr/jenkins,hplatou/jenkins,SebastienGllmt/jenkins,keyurpatankar/hudson,daspilker/jenkins,jpbriend/jenkins,aldaris/jenkins,vijayto/jenkins,aquarellian/jenkins,shahharsh/jenkins,msrb/jenkins,aduprat/jenkins,ydubreuil/jenkins,petermarcoen/jenkins,paulwellnerbou/jenkins,Wilfred/jenkins,patbos/jenkins,goldchang/jenkins,MichaelPranovich/jenkins_sc,thomassuckow/jenkins,amuniz/jenkins,FTG-003/jenkins,jcarrothers-sap/jenkins,liorhson/jenkins,amruthsoft9/Jenkis,yonglehou/jenkins,guoxu0514/jenkins,dbroady1/jenkins,noikiy/jenkins,KostyaSha/jenkins,gitaccountforprashant/gittest,elkingtonmcb/jenkins,gusreiber/jenkins,gorcz/jenkins,jglick/jenkins,seanlin816/jenkins,tastatur/jenkins,jzjzjzj/jenkins,damianszczepanik/jenkins,Krasnyanskiy/jenkins,FarmGeek4Life/jenkins,varmenise/jenkins,bkmeneguello/jenkins,deadmoose/jenkins,aduprat/jenkins,dennisjlee/jenkins,jcsirot/jenkins,jcarrothers-sap/jenkins,jk47/jenkins,aldaris/jenkins,amruthsoft9/Jenkis,liupugong/jenkins,soenter/jenkins,mdonohue/jenkins,bkmeneguello/jenkins,ChrisA89/jenkins,mattclark/jenkins,yonglehou/jenkins,damianszczepanik/jenkins,stephenc/jenkins,escoem/jenkins,my7seven/jenkins,shahharsh/jenkins,synopsys-arc-oss/jenkins,daniel-beck/jenkins,hashar/jenkins,pjanouse/jenkins,vvv444/jenkins,paulmillar/jenkins,MadsNielsen/jtemp,liorhson/jenkins,lordofthejars/jenkins,bkmeneguello/jenkins,godfath3r/jenkins | /*
* The MIT License
*
* Copyright (c) 2010, InfraDNA, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.model.labels;
import antlr.ANTLRException;
import hudson.Launcher;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.FreeStyleBuild;
import hudson.model.FreeStyleProject;
import hudson.model.FreeStyleProject.DescriptorImpl;
import hudson.model.Label;
import hudson.model.Node.Mode;
import hudson.slaves.DumbSlave;
import hudson.slaves.RetentionStrategy;
import org.jvnet.hudson.test.Bug;
import org.jvnet.hudson.test.HudsonTestCase;
import org.jvnet.hudson.test.SequenceLock;
import org.jvnet.hudson.test.TestBuilder;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
/**
* @author Kohsuke Kawaguchi
*/
public class LabelExpressionTest extends HudsonTestCase {
/**
* Verifies the queueing behavior in the presence of the expression.
*/
public void testQueueBehavior() throws Exception {
DumbSlave w32 = createSlave("win 32bit",null);
DumbSlave w64 = createSlave("win 64bit",null);
createSlave("linux 32bit",null);
final SequenceLock seq = new SequenceLock();
FreeStyleProject p1 = createFreeStyleProject();
p1.getBuildersList().add(new TestBuilder() {
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
seq.phase(0); // first, make sure the w32 slave is occupied
seq.phase(2);
seq.done();
return true;
}
});
p1.setAssignedLabel(jenkins.getLabel("win && 32bit"));
FreeStyleProject p2 = createFreeStyleProject();
p2.setAssignedLabel(jenkins.getLabel("win && 32bit"));
FreeStyleProject p3 = createFreeStyleProject();
p3.setAssignedLabel(jenkins.getLabel("win"));
Future<FreeStyleBuild> f1 = p1.scheduleBuild2(0);
seq.phase(1); // we schedule p2 build after w32 slave is occupied
Future<FreeStyleBuild> f2 = p2.scheduleBuild2(0);
Thread.sleep(1000); // time window to ensure queue has tried to assign f2 build
// p3 is tied to 'win', so even though p1 is busy, this should still go ahead and complete
FreeStyleBuild b3 = assertBuildStatusSuccess(p3.scheduleBuild2(0));
assertSame(w64,b3.getBuiltOn());
seq.phase(3); // once we confirm that p3 build is over, we let p1 proceed
// p1 should have been built on w32
FreeStyleBuild b1 = assertBuildStatusSuccess(f1);
assertSame(w32,b1.getBuiltOn());
// and so is p2
FreeStyleBuild b2 = assertBuildStatusSuccess(f2);
assertSame(w32,b2.getBuiltOn());
}
/**
* Push the build around to different nodes via the assignment
* to make sure it gets where we need it to.
*/
public void testQueueBehavior2() throws Exception {
DumbSlave s = createSlave("win",null);
FreeStyleProject p = createFreeStyleProject();
p.setAssignedLabel(jenkins.getLabel("!win"));
FreeStyleBuild b = assertBuildStatusSuccess(p.scheduleBuild2(0));
assertSame(jenkins,b.getBuiltOn());
p.setAssignedLabel(jenkins.getLabel("win"));
b = assertBuildStatusSuccess(p.scheduleBuild2(0));
assertSame(s,b.getBuiltOn());
p.setAssignedLabel(jenkins.getLabel("!win"));
b = assertBuildStatusSuccess(p.scheduleBuild2(0));
assertSame(jenkins,b.getBuiltOn());
}
/**
* Make sure we can reset the label of an existing slave.
*/
public void testSetLabelString() throws Exception {
DumbSlave s = createSlave("foo","",null);
assertSame(s.getLabelString(), "");
s.setLabelString("bar");
assertSame(s.getLabelString(), "bar");
}
/**
* Tests the expression parser.
*/
public void testParser() throws Exception {
parseAndVerify("foo", "foo");
parseAndVerify("32bit.dot", "32bit.dot");
parseAndVerify("foo||bar", "foo || bar");
// user-given parenthesis is preserved
parseAndVerify("foo||bar&&zot", "foo||bar&&zot");
parseAndVerify("foo||(bar&&zot)", "foo||(bar&&zot)");
parseAndVerify("(foo||bar)&&zot", "(foo||bar)&&zot");
parseAndVerify("foo->bar", "foo ->\tbar");
parseAndVerify("!foo<->bar", "!foo <-> bar");
}
@Bug(8537)
public void testParser2() throws Exception {
parseAndVerify("aaa&&bbb&&ccc","aaa&&bbb&&ccc");
}
private void parseAndVerify(String expected, String expr) throws ANTLRException {
assertEquals(expected, LabelExpression.parseExpression(expr).getName());
}
public void testParserError() throws Exception {
parseShouldFail("foo bar");
parseShouldFail("foo (bar)");
}
public void testLaxParsing() {
// this should parse as an atom
LabelAtom l = (LabelAtom) jenkins.getLabel("lucene.zones.apache.org (Solaris 10)");
assertEquals(l.getName(),"lucene.zones.apache.org (Solaris 10)");
assertEquals(l.getExpression(),"\"lucene.zones.apache.org (Solaris 10)\"");
}
public void testDataCompatibilityWithHostNameWithWhitespace() throws Exception {
DumbSlave slave = new DumbSlave("abc def (xyz) : test", "dummy",
createTmpDir().getPath(), "1", Mode.NORMAL, "", createComputerLauncher(null), RetentionStrategy.NOOP, Collections.EMPTY_LIST);
jenkins.addNode(slave);
FreeStyleProject p = createFreeStyleProject();
p.setAssignedLabel(jenkins.getLabel("abc def"));
assertEquals("abc def",p.getAssignedLabel().getName());
assertEquals("\"abc def\"",p.getAssignedLabel().getExpression());
// expression should be persisted, not the name
Field f = AbstractProject.class.getDeclaredField("assignedNode");
f.setAccessible(true);
assertEquals("\"abc def\"",f.get(p));
// but if the name is set, we'd still like to parse it
f.set(p,"a:b c");
assertEquals("a:b c",p.getAssignedLabel().getName());
}
public void testQuote() {
Label l = jenkins.getLabel("\"abc\\\\\\\"def\"");
assertEquals("abc\\\"def",l.getName());
l = jenkins.getLabel("label1||label2"); // create label expression
l = jenkins.getLabel("\"label1||label2\"");
assertEquals("label1||label2",l.getName());
}
/**
* The name should have parenthesis at the right place to preserve the tree structure.
*/
public void testComposite() {
LabelAtom x = jenkins.getLabelAtom("x");
assertEquals("!!x",x.not().not().getName());
assertEquals("(x||x)&&x",x.or(x).and(x).getName());
assertEquals("x&&x||x",x.and(x).or(x).getName());
}
public void testDash() {
jenkins.getLabelAtom("solaris-x86");
}
private void parseShouldFail(String expr) {
try {
LabelExpression.parseExpression(expr);
fail(expr + " should fail to parse");
} catch (ANTLRException e) {
// expected
}
}
public void testFormValidation() throws Exception {
executeOnServer(new Callable<Object>() {
public Object call() throws Exception {
DescriptorImpl d = jenkins.getDescriptorByType(DescriptorImpl.class);
Label l = jenkins.getLabel("foo");
DumbSlave s = createSlave(l);
String msg = d.doCheckAssignedLabelString(null, "goo").renderHtml();
assertTrue(msg.contains("foo"));
assertTrue(msg.contains("goo"));
msg = d.doCheckAssignedLabelString(null, "master && goo").renderHtml();
assertTrue(msg.contains("foo"));
assertTrue(msg.contains("goo"));
return null;
}
});
}
}
| test/src/test/java/hudson/model/labels/LabelExpressionTest.java | /*
* The MIT License
*
* Copyright (c) 2010, InfraDNA, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.model.labels;
import antlr.ANTLRException;
import hudson.Launcher;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.FreeStyleBuild;
import hudson.model.FreeStyleProject;
import hudson.model.FreeStyleProject.DescriptorImpl;
import hudson.model.Label;
import hudson.model.Node.Mode;
import hudson.slaves.DumbSlave;
import hudson.slaves.RetentionStrategy;
import org.jvnet.hudson.test.Bug;
import org.jvnet.hudson.test.HudsonTestCase;
import org.jvnet.hudson.test.SequenceLock;
import org.jvnet.hudson.test.TestBuilder;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
/**
* @author Kohsuke Kawaguchi
*/
public class LabelExpressionTest extends HudsonTestCase {
/**
* Verifies the queueing behavior in the presence of the expression.
*/
public void testQueueBehavior() throws Exception {
DumbSlave w32 = createSlave("win 32bit",null);
DumbSlave w64 = createSlave("win 64bit",null);
createSlave("linux 32bit",null);
final SequenceLock seq = new SequenceLock();
FreeStyleProject p1 = createFreeStyleProject();
p1.getBuildersList().add(new TestBuilder() {
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
seq.phase(0); // first, make sure the w32 slave is occupied
seq.phase(2);
seq.done();
return true;
}
});
p1.setAssignedLabel(jenkins.getLabel("win && 32bit"));
FreeStyleProject p2 = createFreeStyleProject();
p2.setAssignedLabel(jenkins.getLabel("win && 32bit"));
FreeStyleProject p3 = createFreeStyleProject();
p3.setAssignedLabel(jenkins.getLabel("win"));
Future<FreeStyleBuild> f1 = p1.scheduleBuild2(0);
seq.phase(1); // we schedule p2 build after w32 slave is occupied
Future<FreeStyleBuild> f2 = p2.scheduleBuild2(0);
Thread.sleep(1000); // time window to ensure queue has tried to assign f2 build
// p3 is tied to 'win', so even though p1 is busy, this should still go ahead and complete
FreeStyleBuild b3 = assertBuildStatusSuccess(p3.scheduleBuild2(0));
assertSame(w64,b3.getBuiltOn());
seq.phase(3); // once we confirm that p3 build is over, we let p1 proceed
// p1 should have been built on w32
FreeStyleBuild b1 = assertBuildStatusSuccess(f1);
assertSame(w32,b1.getBuiltOn());
// and so is p2
FreeStyleBuild b2 = assertBuildStatusSuccess(f2);
assertSame(w32,b2.getBuiltOn());
}
/**
* Push the build around to different nodes via the assignment
* to make sure it gets where we need it to.
*/
public void testQueueBehavior2() throws Exception {
DumbSlave s = createSlave("win",null);
FreeStyleProject p = createFreeStyleProject();
p.setAssignedLabel(jenkins.getLabel("!win"));
FreeStyleBuild b = assertBuildStatusSuccess(p.scheduleBuild2(0));
assertSame(jenkins,b.getBuiltOn());
p.setAssignedLabel(jenkins.getLabel("win"));
b = assertBuildStatusSuccess(p.scheduleBuild2(0));
assertSame(s,b.getBuiltOn());
p.setAssignedLabel(jenkins.getLabel("!win"));
b = assertBuildStatusSuccess(p.scheduleBuild2(0));
assertSame(jenkins,b.getBuiltOn());
}
/**
* Make sure we can reset the label of an existing slave.
*/
public void testSetLabelString() throws Exception {
DumbSlave s = createSlave("foo","",null);
assertSame(s.getLabelString(), "");
s.setLabelString("bar");
assertSame(s.getLabelString(), "bar");
}
/**
* Tests the expression parser.
*/
public void testParser() throws Exception {
parseAndVerify("foo", "foo");
parseAndVerify("32bit.dot", "32bit.dot");
parseAndVerify("foo||bar", "foo || bar");
// user-given parenthesis is preserved
parseAndVerify("foo||bar&&zot", "foo||bar&&zot");
parseAndVerify("foo||(bar&&zot)", "foo||(bar&&zot)");
parseAndVerify("(foo||bar)&&zot", "(foo||bar)&&zot");
parseAndVerify("foo->bar", "foo ->\tbar");
parseAndVerify("!foo<->bar", "!foo <-> bar");
}
@Bug(8537)
public void testParser2() throws Exception {
parseAndVerify("aaa&&bbb&&ccc","aaa&&bbb&&ccc");
}
private void parseAndVerify(String expected, String expr) throws ANTLRException {
assertEquals(expected, LabelExpression.parseExpression(expr).getName());
}
public void testParserError() throws Exception {
parseShouldFail("foo bar");
parseShouldFail("foo (bar)");
}
public void testLaxParsing() {
// this should parse as an atom
LabelAtom l = (LabelAtom) jenkins.getLabel("lucene.zones.apache.org (Solaris 10)");
assertEquals(l.getName(),"lucene.zones.apache.org (Solaris 10)");
assertEquals(l.getExpression(),"\"lucene.zones.apache.org (Solaris 10)\"");
}
public void testDataCompatibilityWithHostNameWithWhitespace() throws Exception {
DumbSlave slave = new DumbSlave("abc def (xyz) : test", "dummy",
createTmpDir().getPath(), "1", Mode.NORMAL, "", createComputerLauncher(null), RetentionStrategy.NOOP, Collections.EMPTY_LIST);
jenkins.addNode(slave);
FreeStyleProject p = createFreeStyleProject();
p.setAssignedLabel(jenkins.getLabel("abc def"));
assertEquals("abc def",p.getAssignedLabel().getName());
assertEquals("\"abc def\"",p.getAssignedLabel().getExpression());
// expression should be persisted, not the name
Field f = AbstractProject.class.getDeclaredField("assignedNode");
f.setAccessible(true);
assertEquals("\"abc def\"",f.get(p));
// but if the name is set, we'd still like to parse it
f.set(p,"a:b c");
assertEquals("a:b c",p.getAssignedLabel().getName());
}
public void testQuote() {
Label l = jenkins.getLabel("\"abc\\\\\\\"def\"");
assertEquals("abc\\\"def",l.getName());
l = jenkins.getLabel("label1||label2"); // create label expression
l = jenkins.getLabel("\"label1||label2\"");
assertEquals("label1||label2",l.getName());
}
/**
* The name should have parenthesis at the right place to preserve the tree structure.
*/
public void testComposite() {
LabelAtom x = jenkins.getLabelAtom("x");
assertEquals("!!x",x.not().not().getName());
assertEquals("(x||x)&&x",x.or(x).and(x).getName());
assertEquals("x&&x||x",x.and(x).or(x).getName());
}
public void testDash() {
jenkins.getLabelAtom("solaris-x86");
}
private void parseShouldFail(String expr) {
try {
LabelExpression.parseExpression(expr);
fail(expr + " should fail to parse");
} catch (ANTLRException e) {
// expected
}
}
public void testFormValidation() throws Exception {
executeOnServer(new Callable<Object>() {
public Object call() throws Exception {
DescriptorImpl d = jenkins.getDescriptorByType(DescriptorImpl.class);
Label l = jenkins.getLabel("foo");
DumbSlave s = createSlave(l);
String msg = d.doCheckAssignedLabelString("goo").renderHtml();
assertTrue(msg.contains("foo"));
assertTrue(msg.contains("goo"));
msg = d.doCheckAssignedLabelString("master && goo").renderHtml();
assertTrue(msg.contains("foo"));
assertTrue(msg.contains("goo"));
return null;
}
});
}
}
| Fix compiler error
| test/src/test/java/hudson/model/labels/LabelExpressionTest.java | Fix compiler error |
|
Java | mit | 1a8b4cc94af9bc3de860c8587c09915d23c71ca4 | 0 | B-Lach/HTW_Programmierung_2_Beleg_3 | package logic;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.io.OutputStreamWriter;
/**
* binary tree class
*
* @author Rico
*
*/
public class BinaryTree {
/**
* Enum to identify which rotation has to be performed to re-balance the tree,
* @author Benny Lach
*
*/
private enum RotationType {
// +2 +1
ClockwiseSmall,
// -2 +1
ClockwiseBig,
// -2 -1
CounterClockwiseSmall,
// +2 -1
CounterClockwiseBig
}
// path to the file the tree was loaded from/saved to
private String stringPath;
// root node
private Node root;
// Boolean to identify if the tree behaves as an AVL tree
private Boolean useAvl;
// Encoding identifier for the file
final static Charset ENCODING = StandardCharsets.UTF_8;
// File extension type
public final static String FILE_EXTENSION = "btv";
/**
* Static Function to initialize a new Tree from a given file
* @param stringPath Path to the file to use
* @return Instance of BinaryTree if the file is valid. Otherwise null
*/
public static BinaryTree loadTreeFromFile(String stringPath) {
// check if the file to load is valid
if(pathIsValid(stringPath)) {
Path path = Paths.get(stringPath);
if (Files.isReadable(path)) {
try {
// fetch data as List<String> from file
List<String> treeList = Files.readAllLines(path, ENCODING);
// validate content
if (validateFileContent(treeList)) {
// create new tree
BinaryTree tree = new BinaryTree(treeList);
// store the current used path to be able to save to that file in the future again
tree.stringPath = stringPath;
return tree;
}
} catch (IOException e) {
return null;
}
}
}
return null;
}
/**
* Function to check if a given string is a valid file path
* @param path The path to check
* @return True if the path is valid. Otherwise false
*/
private static Boolean pathIsValid(String path) {
return path.endsWith("." + FILE_EXTENSION);
}
/**
* Function to validate content of a loaded file
* @param content The content to validate
* @return True if content is valid. Otherwise false
*/
private static Boolean validateFileContent(List<String> content) {
for(int i = 0; i < content.size(); i++) {
String s = content.get(i);
// fist string has to be an string representation of the AVL option
if (i == 0) {
if (s.compareTo("false") != 0 && s.compareTo("true") != 0) {
return false;
}
// rest of the strings are nodes to load
} else {
if (s.length() < 1 || s.length() > 3) {
return false;
}
}
}
return true;
}
/**
* Constructor to initialize a new BinaryTree instance
* @param useAvl Option to identify if the tree has to behave as AVL Tree
*/
public BinaryTree(Boolean useAvl) {
this.useAvl = useAvl;
}
/**
* Constructor to initialize a new BinaryTree instance with content from a file
* @param fileContent The content of the file
*/
public BinaryTree(List<String> fileContent) {
this.useAvl = fileContent.get(0).compareTo("true") == 0 ;
for(String data: fileContent.subList(1, fileContent.size())) {
addNode(data);
}
}
/**
* Method to get the current path of the used file
* @return The path to the current used file. Is null, if there is no path available
*/
public String getStringPath(){
return stringPath;
}
/**
* Method to re-balance the tree if needed.
*/
private void replaceTreeIfNeeded(Node subRoot) {
// Reached end of iteration
if (subRoot == null) { return;}
// current subtree is balanced
if (Math.abs(subRoot.getBalance()) < 2) {
// check right subtree
replaceTreeIfNeeded(subRoot.getRightChild());
// check left subtree
replaceTreeIfNeeded(subRoot.getLeftChild());
} else {
// subtree is unbalanced
if (Math.abs(subRoot.getBalance()) == 2) {
// right side is unbalanced
if (subRoot.getBalance() > 0) {
// found criterion for rotation => sub-root == 2 && rightChild == |1| || 0
if (Math.abs(subRoot.getRightChild().getBalance()) == 1 || subRoot.getRightChild().getBalance() == 0) {
// clockwise small rotation found
if (subRoot.getRightChild().getBalance() >= 0) {
makeRotation(subRoot,RotationType.ClockwiseSmall);
} else {
makeRotation(subRoot, RotationType.CounterClockwiseBig);
}
// time to re-balance and iterate again over the tree, start with root
calculateBalance(root);
replaceTreeIfNeeded(root);
return;
}
} else {
// // found criterion for rotation => sub-root == -2 && leftChild == |1| || 0
if (Math.abs(subRoot.getLeftChild().getBalance()) == 1 || subRoot.getLeftChild().getBalance() == 0) {
// counter clockwise small rotation found
if (subRoot.getLeftChild().getBalance() <= 0) {
makeRotation(subRoot,RotationType.CounterClockwiseSmall);
} else {
makeRotation(subRoot,RotationType.ClockwiseBig);
}
// time to re-balance and iterate again over the tree, start with root
calculateBalance(root);
replaceTreeIfNeeded(root);
return;
}
}
}
// reaching this line means tree is unbalanced but criteria was not found
replaceTreeIfNeeded(subRoot.getRightChild());
replaceTreeIfNeeded(subRoot.getLeftChild());
}
}
/**
* Method to rotate a subtree. Used to validate balance of an AVL tree
* @param node The root of the subtree to rotate
* @param type The type of rotation to use
*/
private void makeRotation(Node node, RotationType type) {
Node newParent;
switch(type) {
case ClockwiseSmall:
// right child will become new parent, parent will become left child
newParent = node.getRightChild();
// left child of new node will become right child of old root
node.setRightChild(newParent.getLeftChild());
if (node.getRightChild() != null) {
node.getRightChild().setParentNode(node);
}
newParent.setParentNode(node.getParentNode());
// if parent is not null update it's child
// otherwise old parent is root node of the whole tree
if(newParent.getParentNode() != null) {
if (newParent.getData().compareTo(newParent.getParentNode().getData()) > 0) {
newParent.getParentNode().setRightChild(newParent);
} else {
newParent.getParentNode().setLeftChild(newParent);
}
} else {
root = newParent;
}
// old parent will become left child of new Parent
node.setParentNode(newParent);
newParent.setLeftChild(node);
break;
case ClockwiseBig:
// 1. step: rotate clockwise small node.leftChild
// 2. step: rotate counter clockwise node
makeRotation(node.getLeftChild(), RotationType.ClockwiseSmall);
makeRotation(node, RotationType.CounterClockwiseSmall);
break;
case CounterClockwiseSmall:
// left child will become new parent, parent will become right child
newParent = node.getLeftChild();
// right child of new parent will become left child of old parent
node.setLeftChild(newParent.getRightChild());
if (node.getLeftChild() != null) {
node.getLeftChild().setParentNode(node);
}
newParent.setParentNode(node.getParentNode());
// if parent is not null update left child
// otherwise old parent is root node of the whole tree
if (newParent.getParentNode() != null) {
if (newParent.getData().compareTo(newParent.getParentNode().getData()) > 0) {
newParent.getParentNode().setRightChild(newParent);
} else {
newParent.getParentNode().setLeftChild(newParent);
}
} else {
root = newParent;
}
// old parent will become right child of new parent
node.setParentNode(newParent);
newParent.setRightChild(node);
break;
case CounterClockwiseBig:
// 1. step: rotate counter clockwise small node.rightChild
// 2. step: rotate clockwise small node
makeRotation(node.getRightChild(), RotationType.CounterClockwiseSmall);
makeRotation(node, RotationType.ClockwiseSmall);
break;
default:
return;
}
}
/**
* Method to calculate the balance of the tree and all its subtrees
* @param node The root node of the tree
*/
private void calculateBalance(Node node) {
// nothing to calculate at this point
if (node == null) { return; }
int right = getDepthOfSubtree(node.getRightChild());
int left = getDepthOfSubtree(node.getLeftChild());
node.setBalance(right - left);
// System.out.println("Node with data: " + node.getData() + " has balance: " + node.getBalance());
calculateBalance(node.getRightChild());
calculateBalance(node.getLeftChild());
}
/**
* Method to calculate the depth of a subtree based on a given root node
* @param node The root node of the subtree
* @return The depth of the subtree as Integer
*/
private int getDepthOfSubtree(Node node) {
// nothing to calculate at this point
if (node == null) { return 0; }
int leftHeight = getDepthOfSubtree(node.getLeftChild());
int rightHeight = getDepthOfSubtree(node.getRightChild());
if (leftHeight == 0 && rightHeight == 0) { return 1; }
return leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1;
}
/**
* Public method to add a new Node. Returns a boolean to identify if the new node was added. Returns false if the data is already part of the node.
* @param data The data of the node to add
* @return Boolean identifier if the node was added
*/
public Boolean addNode(String data) {
// without a root node this will become root
if (root == null) {
Node newNode = new Node(data);
root = newNode;
newNode.setBalance(0);
return true;
} else {
Boolean wasAdded = _addNode(data);
if (wasAdded) {
// calculate the new balance
calculateBalance(root);
if (useAvl) {
// if AVL is active, re-balance the tree if needed
replaceTreeIfNeeded(root);
}
}
return wasAdded;
}
}
/**
* Private method to add a new node. Return value is a boolean to identify if the new node was added. Returns false if the data is already part of the node.
* @param data The data of the node to add
* @return Boolean Identifier if the node was added
*/
private Boolean _addNode(String data) {
// init new node
Node newNode = new Node(data);
// sets root as starting point for traversing the tree
Node focusNode = root;
// future parent for new node
Node parent;
while (true) {
// start at top with root
parent = focusNode;
// check whether new node goes on left or right side
if (data.compareTo(focusNode.getData()) < 0) {
focusNode = focusNode.getLeftChild();
// if left child has no children
if (focusNode == null) {
// places new node on the left
parent.setLeftChild(newNode);
newNode.setParentNode(parent);
return true;
}
} else if (data.compareTo(focusNode.getData()) > 0) {
// puts node on right side
focusNode = focusNode.getRightChild();
// if right child has no children
if (focusNode == null) {
// place new node on the right
parent.setRightChild(newNode);
newNode.setParentNode(parent);
return true;
}
// check if a duplicate node is being added
} else {
if (data.compareTo(focusNode.getData()) == 0) {
System.out.println("add: no duplicate nodes allowed");
return false;
}
}
}
}
public boolean deleteAll() {
root = null;
if (root == null) {
return true;
}
return false;
}
/**
* public delete method for nodes
*
* @param data
* the node that the user wants to delete
* @return returns true if deletion was successful and false if it was not
*/
public boolean deleteNode(String data) {
Boolean deleted = _deleteNode(data);
if (deleted) {
// calculate the new balance
calculateBalance(root);
if (useAvl) {
// if AVL is active, re-balance the tree if needed
replaceTreeIfNeeded(root);
}
}
return deleted;
}
/**
* private delete method for nodes
*
* @param data
* the node that the user wants to delete
* @return returns true if deletion was successful and false if it was not
*/
private boolean _deleteNode(String data) {
Node focusNode = root;
Node parent = root;
boolean isItLeftChild = true;
if (root != null) {
while (focusNode.getData().compareTo(data) != 0) {
parent = focusNode;
if (data.compareTo(focusNode.getData()) < 0) {
isItLeftChild = true;
focusNode = focusNode.getLeftChild();
} else if (data.compareTo(focusNode.getData()) > 0) {
isItLeftChild = false;
focusNode = focusNode.getRightChild();
}
if (focusNode == null) {
return false;
}
}
// leaf node
if (focusNode.getLeftChild() == null && focusNode.getRightChild() == null) {
if (focusNode == root) {
root = null;
} else if (isItLeftChild) {
parent.setLeftChild(null);
} else {
parent.setRightChild(null);
}
// only left child
} else if (focusNode.getRightChild() == null) {
if (focusNode == root) {
root = focusNode.getLeftChild();
root.setParentNode(null);
} else if (isItLeftChild) {
parent.setLeftChild(focusNode.getLeftChild());
parent.getLeftChild().setParentNode(parent);
} else {
parent.setRightChild(focusNode.getLeftChild());
parent.getRightChild().setParentNode(parent);
}
// only right child
} else if (focusNode.getLeftChild() == null) {
if (focusNode == root) {
root = focusNode.getRightChild();
root.setParentNode(null);
} else if (isItLeftChild) {
parent.setLeftChild(focusNode.getRightChild());
parent.getLeftChild().setParentNode(parent);
} else {
parent.setRightChild(focusNode.getRightChild());
parent.getRightChild().setParentNode(parent);
}
// left and right child
} else {
Node replacement = getReplacementNode(focusNode);
if (focusNode == root) {
root = replacement;
root.setParentNode(null);
} else if (isItLeftChild) {
parent.setLeftChild(replacement);
replacement.setParentNode(parent);
} else {
parent.setRightChild(replacement);
replacement.setParentNode(parent);
}
replacement.setLeftChild(focusNode.getLeftChild());
replacement.getLeftChild().setParentNode(replacement);
}
return true;
}
System.out.println("delete: node not found");
return false;
}
public Node findNode(String data) {
// starts at top of the tree
Node focusNode = root;
while (focusNode.getData().compareTo(data) != 0) {
if (data.compareTo(focusNode.getData()) < 0) {
focusNode = focusNode.getLeftChild();
} else if (data.compareTo(focusNode.getData()) > 0) {
focusNode = focusNode.getRightChild();
}
// if node is not found
if (focusNode == null) {
return null;
}
}
return focusNode;
}
public Node getRootNode() {
return root;
}
public Boolean saveTreeToFile(String stringPath) {
// check if the given path is valid
// if it isn't add the valid file extension
if(!pathIsValid(stringPath)) {
stringPath = addValidFileExtension(stringPath);
}
Node focusNode = root;
ArrayList<String> treeArray = new ArrayList<String>();
preorderTraverseTree(focusNode, treeArray);
Path storePath = Paths.get(stringPath);
// add the AVL option to the content
treeArray.add(0, useAvl == true? "true": "false");
if (!Files.isWritable(storePath)) {
try {
Files.createFile(storePath);
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
try {
PrintWriter writer = new PrintWriter(new FileWriter(storePath.toString()));
for (String s : treeArray) {
writer.println(s);
}
writer.close();
// store the current used path to be able to save to that file in the future again
this.stringPath = stringPath;
} catch (IOException e) {
System.out.println("Failed to create FileWriter: " + e);
e.printStackTrace();
return false;
}
return true;
}
public boolean avlSort(){
ArrayList<String> treeArray = new ArrayList<String>();
Node focusNode = root;
preorderTraverseTree(focusNode, treeArray);
return true;
}
/**
* Method to add a valid file extension to a given path
* @param path The path to add the file extension
* @return The path with valid extension
*/
private String addValidFileExtension(String path) {
return path += "." + FILE_EXTENSION;
}
private void preorderTraverseTree(Node focusNode, ArrayList<String> list) {
if (focusNode != null && list != null) {
list.add(focusNode.getData());
preorderTraverseTree(focusNode.getLeftChild(), list);
preorderTraverseTree(focusNode.getRightChild(), list);
}
System.out.println(list.toString());
}
private Node getReplacementNode(Node replacedNode) {
Node replacementParent = replacedNode;
Node replacement = replacedNode;
Node focusNode = replacedNode.getRightChild();
while (focusNode != null) {
replacementParent = replacement;
replacement = focusNode;
focusNode = focusNode.getLeftChild();
}
if (replacement != replacedNode.getRightChild()) {
replacementParent.setLeftChild(replacement.getRightChild());
if (replacementParent.getLeftChild() != null) {
replacementParent.getLeftChild().setParentNode(replacementParent);
}
replacement.setRightChild(replacedNode.getRightChild());
if (replacement.getRightChild() != null ) {
replacement.getRightChild().setParentNode(replacement);
}
}
return replacement;
}
/**
* Method to print the tree on console
* Inspired by http://stackoverflow.com/questions/4965335/how-to-print-binary-tree-diagram
*/
public void printTree() {
System.out.println("\n\n\n");
// empty tree found
if (root == null) {
System.out.println("Tree is empty");
} else {
OutputStreamWriter writer = new OutputStreamWriter(System.out);
if (root.getRightChild() != null) {
printTree(writer, root.getRightChild(), true, "");
}
printNodeValue(writer, root);
if (root.getLeftChild() != null) {
printTree(writer, root.getLeftChild(), false, "");
}
}
System.out.println("\n\n\n");
}
// use string and not stringbuffer on purpose as we need to change the indent at each recursion
/**
* Private Method to print the tree on console using an OutputStreamWriter
* @param writer The OutputStreamWriter object to use
* @param root The current root node to print
* @param isRight Boolean value to identify if the current node is right child
* @param indent The current indent string
*/
private void printTree(OutputStreamWriter writer, Node root, boolean isRight, String indent) {
// right child not null
if (root.getRightChild() != null) {
printTree(writer, root.getRightChild(), true, indent + (isRight ? " " : " | "));
}
// write current node
try {
writer.write(indent);
if (isRight) {
writer.write(" /");
} else {
writer.write(" \\");
}
writer.write("----- ");
writer.flush();
} catch (Exception e) {}
printNodeValue(writer, root);
// left child not null
if (root.getLeftChild() != null) {
printTree(writer, root.getLeftChild(), false, indent + (isRight ? " | " : " "));
}
}
/**
* Private method to print a node's value to an OutputStreamWriter
* @param out The OutputStreamWriter to use
* @param node The node to print
*/
private void printNodeValue(OutputStreamWriter out, Node node) {
try {
// node is null
if (node == null) {
out.write("<null>");
} else {
out.write(node.getData());
}
out.write('\n');
out.flush();
} catch (Exception e) {}
}
}
| src/logic/BinaryTree.java | package logic;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.io.OutputStreamWriter;
/**
* binary tree class
*
* @author Rico
*
*/
public class BinaryTree {
/**
* Enum to identify which rotation has to be performed to re-balance the tree,
* @author Benny Lach
*
*/
private enum RotationType {
// +2 +1
ClockwiseSmall,
// -2 +1
ClockwiseBig,
// -2 -1
CounterClockwiseSmall,
// +2 -1
CounterClockwiseBig
}
// path to the file the tree was loaded from/saved to
private String stringPath;
// root node
private Node root;
// Boolean to identify if the tree behaves as an AVL tree
private Boolean useAvl;
// Encoding identifier for the file
final static Charset ENCODING = StandardCharsets.UTF_8;
// File extension type
public final static String FILE_EXTENSION = "btv";
/**
* Static Function to initialize a new Tree from a given file
* @param stringPath Path to the file to use
* @return Instance of BinaryTree if the file is valid. Otherwise null
*/
public static BinaryTree loadTreeFromFile(String stringPath) {
// check if the file to load is valid
if(pathIsValid(stringPath)) {
Path path = Paths.get(stringPath);
if (Files.isReadable(path)) {
try {
// fetch data as List<String> from file
List<String> treeList = Files.readAllLines(path, ENCODING);
// validate content
if (validateFileContent(treeList)) {
// create new tree
BinaryTree tree = new BinaryTree(treeList);
// store the current used path to be able to save to that file in the future again
tree.stringPath = stringPath;
return tree;
}
} catch (IOException e) {
return null;
}
}
}
return null;
}
/**
* Function to check if a given string is a valid file path
* @param path The path to check
* @return True if the path is valid. Otherwise false
*/
private static Boolean pathIsValid(String path) {
return path.endsWith("." + FILE_EXTENSION);
}
/**
* Function to validate content of a loaded file
* @param content The content to validate
* @return True if content is valid. Otherwise false
*/
private static Boolean validateFileContent(List<String> content) {
for(int i = 0; i < content.size(); i++) {
String s = content.get(i);
// fist string has to be an string representation of the AVL option
if (i == 0) {
if (s != "false" && s != "true") {
return false;
}
// rest of the strings are nodes to load
} else {
if (s.length() < 1 || s.length() > 3) {
return false;
}
}
}
return true;
}
/**
* Constructor to initialize a new BinaryTree instance
* @param useAvl Option to identify if the tree has to behave as AVL Tree
*/
public BinaryTree(Boolean useAvl) {
this.useAvl = useAvl;
}
/**
* Constructor to initialize a new BinaryTree instance with content from a file
* @param fileContent The content of the file
*/
public BinaryTree(List<String> fileContent) {
this.useAvl = fileContent.get(0) == "true";
for(String data: fileContent.subList(1, fileContent.size() - 1)) {
addNode(data);
}
}
/**
* Method to get the current path of the used file
* @return The path to the current used file. Is null, if there is no path available
*/
public String getStringPath(){
return stringPath;
}
/**
* Method to re-balance the tree if needed.
*/
private void replaceTreeIfNeeded(Node subRoot) {
// Reached end of iteration
if (subRoot == null) { return;}
// current subtree is balanced
if (Math.abs(subRoot.getBalance()) < 2) {
// check right subtree
replaceTreeIfNeeded(subRoot.getRightChild());
// check left subtree
replaceTreeIfNeeded(subRoot.getLeftChild());
} else {
// subtree is unbalanced
if (Math.abs(subRoot.getBalance()) == 2) {
// right side is unbalanced
if (subRoot.getBalance() > 0) {
// found criterion for rotation => sub-root == 2 && rightChild == |1| || 0
if (Math.abs(subRoot.getRightChild().getBalance()) == 1 || subRoot.getRightChild().getBalance() == 0) {
// clockwise small rotation found
if (subRoot.getRightChild().getBalance() >= 0) {
makeRotation(subRoot,RotationType.ClockwiseSmall);
} else {
makeRotation(subRoot, RotationType.CounterClockwiseBig);
}
// time to re-balance and iterate again over the tree, start with root
calculateBalance(root);
replaceTreeIfNeeded(root);
return;
}
} else {
// // found criterion for rotation => sub-root == -2 && leftChild == |1| || 0
if (Math.abs(subRoot.getLeftChild().getBalance()) == 1 || subRoot.getLeftChild().getBalance() == 0) {
// counter clockwise small rotation found
if (subRoot.getLeftChild().getBalance() <= 0) {
makeRotation(subRoot,RotationType.CounterClockwiseSmall);
} else {
makeRotation(subRoot,RotationType.ClockwiseBig);
}
// time to re-balance and iterate again over the tree, start with root
calculateBalance(root);
replaceTreeIfNeeded(root);
return;
}
}
}
// reaching this line means tree is unbalanced but criteria was not found
replaceTreeIfNeeded(subRoot.getRightChild());
replaceTreeIfNeeded(subRoot.getLeftChild());
}
}
private void makeRotation(Node node, RotationType type) {
Node newParent;
switch(type) {
case ClockwiseSmall:
// right child will become new parent, parent will become left child
newParent = node.getRightChild();
// left child of new node will become right child of old root
node.setRightChild(newParent.getLeftChild());
if (node.getRightChild() != null) {
node.getRightChild().setParentNode(node);
}
newParent.setParentNode(node.getParentNode());
// if parent is not null update it's child
// otherwise old parent is root node of the whole tree
if(newParent.getParentNode() != null) {
if (newParent.getData().compareTo(newParent.getParentNode().getData()) > 0) {
newParent.getParentNode().setRightChild(newParent);
} else {
newParent.getParentNode().setLeftChild(newParent);
}
} else {
root = newParent;
}
// old parent will become left child of new Parent
node.setParentNode(newParent);
newParent.setLeftChild(node);
break;
case ClockwiseBig:
// 1. step: rotate clockwise small node.leftChild
// 2. step: rotate counter clockwise node
makeRotation(node.getLeftChild(), RotationType.ClockwiseSmall);
makeRotation(node, RotationType.CounterClockwiseSmall);
break;
case CounterClockwiseSmall:
// left child will become new parent, parent will become right child
newParent = node.getLeftChild();
// right child of new parent will become left child of old parent
node.setLeftChild(newParent.getRightChild());
if (node.getLeftChild() != null) {
node.getLeftChild().setParentNode(node);
}
newParent.setParentNode(node.getParentNode());
// if parent is not null update left child
// otherwise old parent is root node of the whole tree
if (newParent.getParentNode() != null) {
if (newParent.getData().compareTo(newParent.getParentNode().getData()) > 0) {
newParent.getParentNode().setRightChild(newParent);
} else {
newParent.getParentNode().setLeftChild(newParent);
}
} else {
root = newParent;
}
// old parent will become right child of new parent
node.setParentNode(newParent);
newParent.setRightChild(node);
break;
case CounterClockwiseBig:
// 1. step: rotate counter clockwise small node.rightChild
// 2. step: rotate clockwise small node
makeRotation(node.getRightChild(), RotationType.CounterClockwiseSmall);
makeRotation(node, RotationType.ClockwiseSmall);
break;
default:
return;
}
}
/**
* Method to calculate the balance of the tree and all its subtrees
* @param node The root node of the tree
*/
private void calculateBalance(Node node) {
// nothing to calculate at this point
if (node == null) { return; }
int right = getDepthOfSubtree(node.getRightChild());
int left = getDepthOfSubtree(node.getLeftChild());
node.setBalance(right - left);
// System.out.println("Node with data: " + node.getData() + " has balance: " + node.getBalance());
calculateBalance(node.getRightChild());
calculateBalance(node.getLeftChild());
}
/**
* Method to calculate the depth of a subtree based on a given root node
* @param node The root node of the subtree
* @return The depth of the subtree as Integer
*/
private int getDepthOfSubtree(Node node) {
// nothing to calculate at this point
if (node == null) { return 0; }
int leftHeight = getDepthOfSubtree(node.getLeftChild());
int rightHeight = getDepthOfSubtree(node.getRightChild());
if (leftHeight == 0 && rightHeight == 0) { return 1; }
return leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1;
}
/**
* Public method to add a new Node. Returns a boolean to identify if the new node was added. Returns false if the data is already part of the node.
* @param data The data of the node to add
* @return Boolean identifier if the node was added
*/
public Boolean addNode(String data) {
// without a root node this will become root
if (root == null) {
Node newNode = new Node(data);
root = newNode;
newNode.setBalance(0);
return true;
} else {
Boolean wasAdded = _addNode(data);
if (wasAdded) {
// calculate the new balance
calculateBalance(root);
if (useAvl) {
// if AVL is active, re-balance the tree if needed
replaceTreeIfNeeded(root);
}
}
return wasAdded;
}
}
/**
* Private method to add a new node. Return value is a boolean to identify if the new node was added. Returns false if the data is already part of the node.
* @param data The data of the node to add
* @return Boolean Identifier if the node was added
*/
private Boolean _addNode(String data) {
// init new node
Node newNode = new Node(data);
// sets root as starting point for traversing the tree
Node focusNode = root;
// future parent for new node
Node parent;
while (true) {
// start at top with root
parent = focusNode;
// check whether new node goes on left or right side
if (data.compareTo(focusNode.getData()) < 0) {
focusNode = focusNode.getLeftChild();
// if left child has no children
if (focusNode == null) {
// places new node on the left
parent.setLeftChild(newNode);
newNode.setParentNode(parent);
return true;
}
} else if (data.compareTo(focusNode.getData()) > 0) {
// puts node on right side
focusNode = focusNode.getRightChild();
// if right child has no children
if (focusNode == null) {
// place new node on the right
parent.setRightChild(newNode);
newNode.setParentNode(parent);
return true;
}
// check if a duplicate node is being added
} else {
if (data.compareTo(focusNode.getData()) == 0) {
System.out.println("add: no duplicate nodes allowed");
return false;
}
}
}
}
public boolean deleteAll() {
root = null;
if (root == null) {
return true;
}
return false;
}
/**
* public delete method for nodes
*
* @param data
* the node that the user wants to delete
* @return returns true if deletion was successful and false if it was not
*/
public boolean deleteNode(String data) {
Boolean deleted = _deleteNode(data);
if (deleted) {
// calculate the new balance
calculateBalance(root);
if (useAvl) {
// if AVL is active, re-balance the tree if needed
replaceTreeIfNeeded(root);
}
}
return deleted;
}
/**
* private delete method for nodes
*
* @param data
* the node that the user wants to delete
* @return returns true if deletion was successful and false if it was not
*/
private boolean _deleteNode(String data) {
Node focusNode = root;
Node parent = root;
boolean isItLeftChild = true;
if (root != null) {
while (focusNode.getData().compareTo(data) != 0) {
parent = focusNode;
if (data.compareTo(focusNode.getData()) < 0) {
isItLeftChild = true;
focusNode = focusNode.getLeftChild();
} else if (data.compareTo(focusNode.getData()) > 0) {
isItLeftChild = false;
focusNode = focusNode.getRightChild();
}
if (focusNode == null) {
return false;
}
}
// leaf node
if (focusNode.getLeftChild() == null && focusNode.getRightChild() == null) {
if (focusNode == root) {
root = null;
} else if (isItLeftChild) {
parent.setLeftChild(null);
} else {
parent.setRightChild(null);
}
// only left child
} else if (focusNode.getRightChild() == null) {
if (focusNode == root) {
root = focusNode.getLeftChild();
root.setParentNode(null);
} else if (isItLeftChild) {
parent.setLeftChild(focusNode.getLeftChild());
parent.getLeftChild().setParentNode(parent);
} else {
parent.setRightChild(focusNode.getLeftChild());
parent.getRightChild().setParentNode(parent);
}
// only right child
} else if (focusNode.getLeftChild() == null) {
if (focusNode == root) {
root = focusNode.getRightChild();
root.setParentNode(null);
} else if (isItLeftChild) {
parent.setLeftChild(focusNode.getRightChild());
parent.getLeftChild().setParentNode(parent);
} else {
parent.setRightChild(focusNode.getRightChild());
parent.getRightChild().setParentNode(parent);
}
// left and right child
} else {
Node replacement = getReplacementNode(focusNode);
if (focusNode == root) {
root = replacement;
root.setParentNode(null);
} else if (isItLeftChild) {
parent.setLeftChild(replacement);
replacement.setParentNode(parent);
} else {
parent.setRightChild(replacement);
replacement.setParentNode(parent);
}
replacement.setLeftChild(focusNode.getLeftChild());
replacement.getLeftChild().setParentNode(replacement);
}
return true;
}
System.out.println("delete: node not found");
return false;
}
public Node findNode(String data) {
// starts at top of the tree
Node focusNode = root;
while (focusNode.getData().compareTo(data) != 0) {
if (data.compareTo(focusNode.getData()) < 0) {
focusNode = focusNode.getLeftChild();
} else if (data.compareTo(focusNode.getData()) > 0) {
focusNode = focusNode.getRightChild();
}
// if node is not found
if (focusNode == null) {
return null;
}
}
return focusNode;
}
public Node getRootNode() {
return root;
}
public Boolean saveTreeToFile(String stringPath) {
// check if the given path is valid
// if it isn't add the valid file extension
if(!pathIsValid(stringPath)) {
stringPath = addValidFileExtension(stringPath);
}
Node focusNode = root;
ArrayList<String> treeArray = new ArrayList<String>();
preorderTraverseTree(focusNode, treeArray);
Path storePath = Paths.get(stringPath);
if (!Files.isWritable(storePath)) {
try {
Files.createFile(storePath);
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
try {
PrintWriter writer = new PrintWriter(new FileWriter(storePath.toString()));
for (String s : treeArray) {
writer.println(s);
}
writer.close();
// store the current used path to be able to save to that file in the future again
this.stringPath = stringPath;
} catch (IOException e) {
System.out.println("Failed to create FileWriter: " + e);
e.printStackTrace();
return false;
}
return true;
}
public boolean avlSort(){
ArrayList<String> treeArray = new ArrayList<String>();
Node focusNode = root;
preorderTraverseTree(focusNode, treeArray);
return true;
}
/**
* Method to add a valid file extension to a given path
* @param path The path to add the file extension
* @return The path with valid extension
*/
private String addValidFileExtension(String path) {
return path += "." + FILE_EXTENSION;
}
private void preorderTraverseTree(Node focusNode, ArrayList<String> list) {
if (focusNode != null && list != null) {
list.add(focusNode.getData());
preorderTraverseTree(focusNode.getLeftChild(), list);
preorderTraverseTree(focusNode.getRightChild(), list);
}
System.out.println(list.toString());
}
private Node getReplacementNode(Node replacedNode) {
Node replacementParent = replacedNode;
Node replacement = replacedNode;
Node focusNode = replacedNode.getRightChild();
while (focusNode != null) {
replacementParent = replacement;
replacement = focusNode;
focusNode = focusNode.getLeftChild();
}
if (replacement != replacedNode.getRightChild()) {
replacementParent.setLeftChild(replacement.getRightChild());
if (replacementParent.getLeftChild() != null) {
replacementParent.getLeftChild().setParentNode(replacementParent);
}
replacement.setRightChild(replacedNode.getRightChild());
if (replacement.getRightChild() != null ) {
replacement.getRightChild().setParentNode(replacement);
}
}
return replacement;
}
/**
* Method to print the tree on console
* Inspired by http://stackoverflow.com/questions/4965335/how-to-print-binary-tree-diagram
*/
public void printTree() {
System.out.println("\n\n\n");
// empty tree found
if (root == null) {
System.out.println("Tree is empty");
} else {
OutputStreamWriter writer = new OutputStreamWriter(System.out);
if (root.getRightChild() != null) {
printTree(writer, root.getRightChild(), true, "");
}
printNodeValue(writer, root);
if (root.getLeftChild() != null) {
printTree(writer, root.getLeftChild(), false, "");
}
}
System.out.println("\n\n\n");
}
// use string and not stringbuffer on purpose as we need to change the indent at each recursion
/**
* Private Method to print the tree on console using an OutputStreamWriter
* @param writer The OutputStreamWriter object to use
* @param root The current root node to print
* @param isRight Boolean value to identify if the current node is right child
* @param indent The current indent string
*/
private void printTree(OutputStreamWriter writer, Node root, boolean isRight, String indent) {
// right child not null
if (root.getRightChild() != null) {
printTree(writer, root.getRightChild(), true, indent + (isRight ? " " : " | "));
}
// write current node
try {
writer.write(indent);
if (isRight) {
writer.write(" /");
} else {
writer.write(" \\");
}
writer.write("----- ");
writer.flush();
} catch (Exception e) {}
printNodeValue(writer, root);
// left child not null
if (root.getLeftChild() != null) {
printTree(writer, root.getLeftChild(), false, indent + (isRight ? " | " : " "));
}
}
/**
* Private method to print a node's value to an OutputStreamWriter
* @param out The OutputStreamWriter to use
* @param node The node to print
*/
private void printNodeValue(OutputStreamWriter out, Node node) {
try {
// node is null
if (node == null) {
out.write("<null>");
} else {
out.write(node.getData());
}
out.write('\n');
out.flush();
} catch (Exception e) {}
}
}
| Fixed loading from file issue
| src/logic/BinaryTree.java | Fixed loading from file issue |
|
Java | mit | 99f5278bc32b34e33011c519441ef7cd50c9d89e | 0 | langerhans/multidoge,GroestlCoin/MultiGroestl,langerhans/multidoge,GroestlCoin/MultiGroestl | /**
* Copyright 2011 multibit.org
*
* Licensed under the MIT license (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/mit-license.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.multibit.viewsystem.swing.view.panels;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.ComponentOrientation;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.CharBuffer;
import java.text.DateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Locale;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.SwingConstants;
import javax.swing.filechooser.FileFilter;
import org.multibit.controller.Controller;
import org.multibit.controller.bitcoin.BitcoinController;
import org.multibit.crypto.KeyCrypterOpenSSL;
import org.multibit.file.PrivateKeyAndDate;
import org.multibit.file.PrivateKeysHandler;
import org.multibit.file.PrivateKeysHandlerException;
import org.multibit.model.bitcoin.BitcoinModel;
import org.multibit.model.bitcoin.WalletBusyListener;
import org.multibit.model.core.CoreModel;
import org.multibit.utils.ImageLoader;
import org.multibit.viewsystem.DisplayHint;
import org.multibit.viewsystem.View;
import org.multibit.viewsystem.Viewable;
import org.multibit.viewsystem.swing.ColorAndFontConstants;
import org.multibit.viewsystem.swing.MultiBitFrame;
import org.multibit.viewsystem.swing.action.HelpContextAction;
import org.multibit.viewsystem.swing.action.ImportPrivateKeysSubmitAction;
import org.multibit.viewsystem.swing.view.PrivateKeyFileFilter;
import org.multibit.viewsystem.swing.view.components.FontSizer;
import org.multibit.viewsystem.swing.view.components.HelpButton;
import org.multibit.viewsystem.swing.view.components.MultiBitButton;
import org.multibit.viewsystem.swing.view.components.MultiBitLabel;
import org.multibit.viewsystem.swing.view.components.MultiBitTitledPanel;
import com.google.dogecoin.crypto.KeyCrypterException;
import org.bitcoinj.wallet.Protos.Wallet.EncryptionType;
import com.piuk.blockchain.MyWallet;
import com.piuk.blockchain.MyWalletEncryptedKeyFileFilter;
import com.piuk.blockchain.MyWalletPlainKeyFileFilter;
/**
* The import private keys view.
*/
public class ImportPrivateKeysPanel extends JPanel implements Viewable, WalletBusyListener {
private static final long serialVersionUID = 444992294329957705L;
private final Controller controller;
private final BitcoinController bitcoinController;
private MultiBitFrame mainFrame;
private MultiBitLabel walletFilenameLabel;
private MultiBitLabel walletDescriptionLabel;
private MultiBitButton chooseFilenameButton;
private String chooseFilenameButtonText;
private JFileChooser fileChooser;
private MultiBitLabel outputFilenameLabel;
private MultiBitLabel messageLabel1;
private MultiBitLabel messageLabel2;
private String outputFilename;
private MultiBitLabel passwordInfoLabel;
private JPasswordField passwordField1;
private MultiBitLabel passwordPromptLabel1;
private MultiBitButton unlockButton;
private JPasswordField passwordField2;
private MultiBitLabel passwordPromptLabel2;
private JPasswordField walletPasswordField;
private MultiBitLabel walletPasswordPromptLabel;
private JLabel numberOfKeysLabel;
private JLabel replayDateLabel;
private ImportPrivateKeysSubmitAction importPrivateKeysSubmitAction;
private KeyCrypterOpenSSL encrypterDecrypter;
public FileFilter multiBitFileChooser;
public FileFilter myWalletPlainFileChooser;
public FileFilter myWalletEncryptedFileChooser;
private Font adjustedFont;
/**
* Creates a new {@link ImportPrivateKeysPanel}.
*/
public ImportPrivateKeysPanel(BitcoinController bitcoinController, MultiBitFrame mainFrame) {
this.bitcoinController = bitcoinController;
this.controller = this.bitcoinController;
this.mainFrame = mainFrame;
setBackground(ColorAndFontConstants.VERY_LIGHT_BACKGROUND_COLOR);
applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
outputFilename = "";
initUI();
walletBusyChange(this.bitcoinController.getModel().getActivePerWalletModelData().isBusy());
this.bitcoinController.registerWalletBusyListener(this);
enableImportFilePasswordPanel(false);
passwordField1.setText("");
passwordField2.setText("");
boolean walletPasswordRequired = false;
if (this.bitcoinController.getModel().getActiveWallet() != null && this.bitcoinController.getModel().getActiveWallet().getEncryptionType() == EncryptionType.ENCRYPTED_SCRYPT_AES) {
walletPasswordRequired = true;
}
enableWalletPassword(walletPasswordRequired);
encrypterDecrypter = new KeyCrypterOpenSSL();
multiBitFileChooser = new PrivateKeyFileFilter(controller);
myWalletPlainFileChooser = new MyWalletPlainKeyFileFilter();
myWalletEncryptedFileChooser = new MyWalletEncryptedKeyFileFilter();
}
private void initUI() {
setLayout(new BorderLayout());
JPanel mainPanel = new JPanel();
mainPanel.setMinimumSize(new Dimension(550, 160));
mainPanel.setLayout(new GridBagLayout());
mainPanel.setOpaque(false);
mainPanel.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
String[] keys = new String[] { "resetTransactionsPanel.walletDescriptionLabel",
"resetTransactionsPanel.walletFilenameLabel", "showExportPrivateKeysPanel.passwordPrompt",
"showExportPrivateKeysPanel.repeatPasswordPrompt", "showImportPrivateKeysPanel.numberOfKeys.text",
"showImportPrivateKeysPanel.replayDate.text" };
int stentWidth = MultiBitTitledPanel.calculateStentWidthForKeys(controller.getLocaliser(), keys, this)
+ ExportPrivateKeysPanel.STENT_DELTA;
GridBagConstraints constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 0;
constraints.gridy = 0;
constraints.gridwidth = 2;
constraints.weightx = 1;
constraints.weighty = 1;
constraints.anchor = GridBagConstraints.LINE_START;
JPanel walletPanel = createWalletPanel(stentWidth);
mainPanel.add(walletPanel, constraints);
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 0;
constraints.gridy = 1;
constraints.gridwidth = 2;
constraints.weightx = 1;
constraints.weighty = 1;
constraints.anchor = GridBagConstraints.LINE_START;
JPanel filenamePanel = createFilenamePanel(stentWidth);
mainPanel.add(filenamePanel, constraints);
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 0;
constraints.gridy = 2;
constraints.gridwidth = 2;
constraints.weightx = 1;
constraints.weighty = 0.2;
constraints.anchor = GridBagConstraints.LINE_START;
JPanel passwordPanel = createPasswordPanel(stentWidth);
mainPanel.add(passwordPanel, constraints);
JLabel filler1 = new JLabel();
filler1.setOpaque(false);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 0;
constraints.gridy = 3;
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.weightx = 1;
constraints.weighty = 0.1;
constraints.anchor = GridBagConstraints.CENTER;
mainPanel.add(filler1, constraints);
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 0;
constraints.gridy = 4;
constraints.gridwidth = 1;
constraints.weightx = 0.4;
constraints.weighty = 0.06;
constraints.anchor = GridBagConstraints.LINE_START;
JPanel buttonPanel = createButtonPanel();
mainPanel.add(buttonPanel, constraints);
messageLabel1 = new MultiBitLabel("");
messageLabel1.setOpaque(false);
messageLabel1.setBorder(BorderFactory.createEmptyBorder(0, 30, 0, 0));
messageLabel1.setHorizontalAlignment(JLabel.LEADING);
messageLabel1.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 0;
constraints.gridy = 5;
constraints.gridwidth = 3;
constraints.weightx = 1;
constraints.weighty = 0.06;
constraints.anchor = GridBagConstraints.LINE_START;
mainPanel.add(messageLabel1, constraints);
messageLabel2 = new MultiBitLabel("");
messageLabel2.setOpaque(false);
messageLabel2.setBorder(BorderFactory.createEmptyBorder(0, 30, 0, 0));
messageLabel2.setHorizontalAlignment(JLabel.LEADING);
messageLabel2.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 0;
constraints.gridy = 6;
constraints.gridwidth = 3;
constraints.weightx = 1;
constraints.weighty = 0.06;
constraints.anchor = GridBagConstraints.LINE_START;
mainPanel.add(messageLabel2, constraints);
Action helpAction;
if (ComponentOrientation.LEFT_TO_RIGHT == ComponentOrientation.getOrientation(controller.getLocaliser().getLocale())) {
helpAction = new HelpContextAction(controller, ImageLoader.HELP_CONTENTS_BIG_ICON_FILE,
"multiBitFrame.helpMenuText", "multiBitFrame.helpMenuTooltip", "multiBitFrame.helpMenuText",
HelpContentsPanel.HELP_IMPORTING_PRIVATE_KEYS_URL);
} else {
helpAction = new HelpContextAction(controller, ImageLoader.HELP_CONTENTS_BIG_RTL_ICON_FILE,
"multiBitFrame.helpMenuText", "multiBitFrame.helpMenuTooltip", "multiBitFrame.helpMenuText",
HelpContentsPanel.HELP_IMPORTING_PRIVATE_KEYS_URL);
}
HelpButton helpButton = new HelpButton(helpAction, controller);
helpButton.setText("");
String tooltipText = HelpContentsPanel.createMultilineTooltipText(new String[] { controller.getLocaliser().getString(
"multiBitFrame.helpMenuTooltip") });
helpButton.setToolTipText(tooltipText);
helpButton.setHorizontalAlignment(SwingConstants.LEADING);
helpButton.setBorder(BorderFactory.createEmptyBorder(0, AbstractTradePanel.HELP_BUTTON_INDENT,
AbstractTradePanel.HELP_BUTTON_INDENT, AbstractTradePanel.HELP_BUTTON_INDENT));
helpButton.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.NONE;
constraints.gridx = 0;
constraints.gridy = 7;
constraints.weightx = 1;
constraints.weighty = 0.1;
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.anchor = GridBagConstraints.BASELINE_LEADING;
mainPanel.add(helpButton, constraints);
JLabel filler2 = new JLabel();
filler2.setOpaque(false);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 0;
constraints.gridy = 8;
constraints.gridwidth = 1;
constraints.weightx = 1;
constraints.weighty = 100;
constraints.anchor = GridBagConstraints.CENTER;
mainPanel.add(filler2, constraints);
JScrollPane mainScrollPane = new JScrollPane(mainPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
mainScrollPane.setBorder(BorderFactory.createEmptyBorder());
mainScrollPane.getViewport().setBackground(ColorAndFontConstants.VERY_LIGHT_BACKGROUND_COLOR);
mainScrollPane.getViewport().setOpaque(true);
mainScrollPane.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
mainScrollPane.getHorizontalScrollBar().setUnitIncrement(CoreModel.SCROLL_INCREMENT);
mainScrollPane.getVerticalScrollBar().setUnitIncrement(CoreModel.SCROLL_INCREMENT);
add(mainScrollPane, BorderLayout.CENTER);
}
private JPanel createWalletPanel(int stentWidth) {
MultiBitTitledPanel inputWalletPanel = new MultiBitTitledPanel(controller.getLocaliser().getString(
"showImportPrivateKeysPanel.wallet.title"), ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
GridBagConstraints constraints = new GridBagConstraints();
MultiBitTitledPanel.addLeftJustifiedTextAtIndent(
controller.getLocaliser().getString("showImportPrivateKeysPanel.wallet.text"), 3, inputWalletPanel);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 1;
constraints.gridy = 4;
constraints.weightx = 0.3;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_START;
inputWalletPanel.add(MultiBitTitledPanel.createStent(stentWidth, ExportPrivateKeysPanel.STENT_HEIGHT), constraints);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 2;
constraints.gridy = 5;
constraints.weightx = 0.05;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.CENTER;
inputWalletPanel.add(MultiBitTitledPanel.createStent(MultiBitTitledPanel.SEPARATION_BETWEEN_NAME_VALUE_PAIRS), constraints);
MultiBitLabel walletDescriptionLabelLabel = new MultiBitLabel(controller.getLocaliser().getString(
"resetTransactionsPanel.walletDescriptionLabel"));
walletDescriptionLabelLabel.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.NONE;
constraints.gridx = 1;
constraints.gridy = 5;
constraints.weightx = 0.5;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_END;
inputWalletPanel.add(walletDescriptionLabelLabel, constraints);
walletDescriptionLabel = new MultiBitLabel(this.bitcoinController.getModel().getActivePerWalletModelData().getWalletDescription());
walletDescriptionLabel.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.NONE;
constraints.gridx = 3;
constraints.gridy = 5;
constraints.weightx = 0.5;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_START;
inputWalletPanel.add(walletDescriptionLabel, constraints);
MultiBitLabel walletFilenameLabelLabel = new MultiBitLabel(controller.getLocaliser().getString(
"resetTransactionsPanel.walletFilenameLabel"));
walletFilenameLabelLabel.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.NONE;
constraints.gridx = 1;
constraints.gridy = 6;
constraints.weightx = 0.5;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_END;
inputWalletPanel.add(walletFilenameLabelLabel, constraints);
walletFilenameLabel = new MultiBitLabel(this.bitcoinController.getModel().getActiveWalletFilename());
walletFilenameLabel.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.NONE;
constraints.gridx = 3;
constraints.gridy = 6;
constraints.weightx = 0.5;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_START;
inputWalletPanel.add(walletFilenameLabel, constraints);
JPanel filler3 = new JPanel();
filler3.setOpaque(false);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 1;
constraints.gridy = 7;
constraints.weightx = 0.3;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_START;
inputWalletPanel.add(filler3, constraints);
walletPasswordPromptLabel = new MultiBitLabel(controller.getLocaliser().getString("showExportPrivateKeysPanel.walletPasswordPrompt"));
walletPasswordPromptLabel.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.NONE;
constraints.gridx = 1;
constraints.gridy = 8;
constraints.weightx = 0.3;
constraints.weighty = 0.1;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_END;
inputWalletPanel.add(walletPasswordPromptLabel, constraints);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 2;
constraints.gridy = 8;
constraints.weightx = 0.05;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.CENTER;
inputWalletPanel.add(MultiBitTitledPanel.createStent(MultiBitTitledPanel.SEPARATION_BETWEEN_NAME_VALUE_PAIRS),
constraints);
walletPasswordField = new JPasswordField(24);
walletPasswordField.setMinimumSize(new Dimension(200, 20));
walletPasswordField.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.NONE;
constraints.gridx = 3;
constraints.gridy = 8;
constraints.weightx = 0.3;
constraints.weighty = 0.6;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_START;
inputWalletPanel.add(walletPasswordField, constraints);
JPanel filler4 = new JPanel();
filler4.setOpaque(false);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 1;
constraints.gridy = 9;
constraints.weightx = 0.3;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_START;
inputWalletPanel.add(filler4, constraints);
return inputWalletPanel;
}
private JPanel createFilenamePanel(int stentWidth) {
MultiBitTitledPanel outputFilenamePanel = new MultiBitTitledPanel(controller.getLocaliser().getString(
"showImportPrivateKeysPanel.filename.title"), ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
MultiBitTitledPanel.addLeftJustifiedTextAtIndent(" ", 1, outputFilenamePanel);
GridBagConstraints constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 0;
constraints.gridy = 2;
constraints.weightx = 0.3;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_START;
outputFilenamePanel.add(MultiBitTitledPanel.getIndentPanel(1), constraints);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 1;
constraints.gridy = 3;
constraints.weightx = 0.3;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_START;
outputFilenamePanel.add(MultiBitTitledPanel.createStent(stentWidth, ExportPrivateKeysPanel.STENT_HEIGHT), constraints);
chooseFilenameButtonText = "";
String chooseFilenameButtonText1 = controller.getLocaliser().getString("showImportPrivateKeysPanel.filename.text");
String chooseFilenameButtonText2 = controller.getLocaliser().getString("showImportPrivateKeysPanel.filename.text.2");
// If the second term is localised, use that, otherwise the first.
if (controller.getLocaliser().getLocale().equals(Locale.ENGLISH)) {
chooseFilenameButtonText = chooseFilenameButtonText2;
} else {
if (!"Import from ...".equals(chooseFilenameButtonText2)) {
chooseFilenameButtonText = chooseFilenameButtonText2;
} else {
chooseFilenameButtonText = chooseFilenameButtonText1;
}
}
chooseFilenameButton = new MultiBitButton(chooseFilenameButtonText);
chooseFilenameButton.setToolTipText(HelpContentsPanel.createTooltipText(controller.getLocaliser().getString("showImportPrivateKeysPanel.filename.tooltip")));
chooseFilenameButton.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
final MultiBitButton finalChooseFilenameButton = chooseFilenameButton;
chooseFilenameButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
chooseFile(finalChooseFilenameButton);
}
});
MultiBitLabel walletFilenameLabelLabel = new MultiBitLabel(controller.getLocaliser().getString(
"resetTransactionsPanel.walletFilenameLabel"));
walletFilenameLabelLabel.setHorizontalAlignment(JLabel.TRAILING);
walletFilenameLabelLabel.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 1;
constraints.gridy = 4;
constraints.weightx = 0.5;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_END;
outputFilenamePanel.add(walletFilenameLabelLabel, constraints);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 2;
constraints.gridy = 5;
constraints.weightx = 0.05;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.CENTER;
outputFilenamePanel.add(MultiBitTitledPanel.createStent(MultiBitTitledPanel.SEPARATION_BETWEEN_NAME_VALUE_PAIRS),
constraints);
outputFilenameLabel = new MultiBitLabel(outputFilename);
outputFilenameLabel.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 3;
constraints.gridy = 4;
constraints.weightx = 0.5;
constraints.weighty = 0.3;
constraints.gridwidth = 2;
constraints.anchor = GridBagConstraints.LINE_START;
outputFilenamePanel.add(outputFilenameLabel, constraints);
JPanel filler0 = new JPanel();
filler0.setOpaque(false);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 5;
constraints.gridy = 4;
constraints.weightx = 100;
constraints.weighty = 1;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_END;
outputFilenamePanel.add(filler0, constraints);
JPanel filler2 = new JPanel();
filler2.setOpaque(false);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 1;
constraints.gridy = 5;
constraints.weightx = 0.3;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_START;
outputFilenamePanel.add(filler2, constraints);
MultiBitLabel numberOfKeysLabelLabel = new MultiBitLabel(controller.getLocaliser().getString(
"showImportPrivateKeysPanel.numberOfKeys.text"));
numberOfKeysLabelLabel.setToolTipText(HelpContentsPanel.createTooltipText(controller.getLocaliser()
.getString("showImportPrivateKeysPanel.numberOfKeys.tooltip")));
numberOfKeysLabelLabel.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.NONE;
constraints.gridx = 1;
constraints.gridy = 6;
constraints.weightx = 0.5;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_END;
outputFilenamePanel.add(numberOfKeysLabelLabel, constraints);
JPanel filler3 = new JPanel();
filler3.setOpaque(false);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 2;
constraints.gridy = 6;
constraints.weightx = 0.1;
constraints.weighty = 0.1;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_START;
outputFilenamePanel.add(filler3, constraints);
numberOfKeysLabel = new MultiBitLabel(" ");
numberOfKeysLabel.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 3;
constraints.gridy = 6;
constraints.weightx = 0.5;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_START;
outputFilenamePanel.add(numberOfKeysLabel, constraints);
MultiBitLabel replayDateLabelLabel = new MultiBitLabel(controller.getLocaliser().getString(
"showImportPrivateKeysPanel.replayDate.text"));
replayDateLabelLabel.setToolTipText(HelpContentsPanel.createTooltipText(controller.getLocaliser().getString("showImportPrivateKeysPanel.replayDate.tooltip")));
replayDateLabelLabel.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.NONE;
constraints.gridx = 1;
constraints.gridy = 7;
constraints.weightx = 0.5;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_END;
outputFilenamePanel.add(replayDateLabelLabel, constraints);
replayDateLabel = new MultiBitLabel(" ");
replayDateLabel.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 3;
constraints.gridy = 7;
constraints.weightx = 0.5;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_START;
outputFilenamePanel.add(replayDateLabel, constraints);
JPanel filler4 = new JPanel();
filler4.setOpaque(false);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 1;
constraints.gridy = 8;
constraints.weightx = 0.3;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_START;
outputFilenamePanel.add(filler4, constraints);
constraints.fill = GridBagConstraints.NONE;
constraints.gridx = 3;
constraints.gridy = 9;
constraints.weightx = 0.5;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_START;
outputFilenamePanel.add(chooseFilenameButton, constraints);
JPanel filler5 = new JPanel();
filler5.setOpaque(false);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 1;
constraints.gridy = 10;
constraints.weightx = 0.3;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_START;
outputFilenamePanel.add(filler5, constraints);
return outputFilenamePanel;
}
private JPanel createPasswordPanel(int stentWidth) {
// Do/do not password protect radios.
MultiBitTitledPanel passwordProtectPanel = new MultiBitTitledPanel(controller.getLocaliser().getString(
"showImportPrivateKeysPanel.password.title"), ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
GridBagConstraints constraints = new GridBagConstraints();
passwordInfoLabel = MultiBitTitledPanel.addLeftJustifiedTextAtIndent(
controller.getLocaliser().getString("showImportPrivateKeysPanel.enterPassword"), 3, passwordProtectPanel);
passwordInfoLabel.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 1;
constraints.gridy = 4;
constraints.weightx = 0.3;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_START;
passwordProtectPanel.add(MultiBitTitledPanel.createStent(stentWidth, ExportPrivateKeysPanel.STENT_HEIGHT), constraints);
passwordPromptLabel1 = new MultiBitLabel(controller.getLocaliser().getString("showExportPrivateKeysPanel.passwordPrompt"));
passwordPromptLabel1.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.NONE;
constraints.gridx = 1;
constraints.gridy = 5;
constraints.weightx = 0.3;
constraints.weighty = 0.1;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_END;
passwordProtectPanel.add(passwordPromptLabel1, constraints);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 2;
constraints.gridy = 5;
constraints.weightx = 0.05;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.CENTER;
passwordProtectPanel.add(MultiBitTitledPanel.createStent(MultiBitTitledPanel.SEPARATION_BETWEEN_NAME_VALUE_PAIRS),
constraints);
passwordField1 = new JPasswordField(24);
passwordField1.setMinimumSize(new Dimension(200, 20));
passwordField1.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.NONE;
constraints.gridx = 3;
constraints.gridy = 5;
constraints.weightx = 0.3;
constraints.weighty = 0.6;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_START;
passwordProtectPanel.add(passwordField1, constraints);
passwordPromptLabel2 = new MultiBitLabel(controller.getLocaliser().getString("showImportPrivateKeysPanel.secondPassword"));
passwordPromptLabel2.setVisible(false);
passwordPromptLabel2.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.NONE;
constraints.gridx = 1;
constraints.gridy = 6;
constraints.weightx = 0.3;
constraints.weighty = 0.1;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_END;
passwordProtectPanel.add(passwordPromptLabel2, constraints);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 2;
constraints.gridy = 6;
constraints.weightx = 0.05;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.CENTER;
passwordProtectPanel.add(MultiBitTitledPanel.createStent(MultiBitTitledPanel.SEPARATION_BETWEEN_NAME_VALUE_PAIRS),
constraints);
passwordField2 = new JPasswordField(24);
passwordField2.setMinimumSize(new Dimension(200, 20));
passwordField2.setVisible(false);
passwordField2.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.NONE;
constraints.gridx = 3;
constraints.gridy = 6;
constraints.weightx = 0.3;
constraints.weighty = 0.6;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_START;
passwordProtectPanel.add(passwordField2, constraints);
JLabel filler3 = new JLabel();
filler3.setMinimumSize(new Dimension(3, 3));
filler3.setMaximumSize(new Dimension(3, 3));
filler3.setPreferredSize(new Dimension(3, 3));
filler3.setOpaque(false);
constraints.fill = GridBagConstraints.NONE;
constraints.gridx = 1;
constraints.gridy = 7;
constraints.weightx = 0.1;
constraints.weighty = 0.1;
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.anchor = GridBagConstraints.CENTER;
passwordProtectPanel.add(filler3, constraints);
unlockButton = new MultiBitButton(controller.getLocaliser().getString("showImportPrivateKeysPanel.unlock.text"));
unlockButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
setMessageText1(" ");
try {
readInImportFileAndUpdateDetails();
} catch (KeyCrypterException ede) {
setMessageText1(controller.getLocaliser().getString("importPrivateKeysSubmitAction.privateKeysUnlockFailure",
new Object[] { ede.getMessage() }));
}
}
});
unlockButton.setToolTipText(HelpContentsPanel.createTooltipText(controller.getLocaliser().getString("showImportPrivateKeysPanel.unlock.tooltip")));
unlockButton.setEnabled(false);
unlockButton.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.NONE;
constraints.gridx = 3;
constraints.gridy = 8;
constraints.weightx = 0.3;
constraints.weighty = 0.6;
constraints.gridwidth = 3;
constraints.anchor = GridBagConstraints.LINE_START;
passwordProtectPanel.add(unlockButton, constraints);
JPanel filler5 = new JPanel();
filler5.setOpaque(false);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 1;
constraints.gridy = 9;
constraints.weightx = 0.3;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_START;
passwordProtectPanel.add(filler3, constraints);
return passwordProtectPanel;
}
private JPanel createButtonPanel() {
JPanel buttonPanel = new JPanel();
buttonPanel.setOpaque(false);
FlowLayout flowLayout = new FlowLayout();
flowLayout.setAlignment(FlowLayout.LEADING);
buttonPanel.setLayout(flowLayout);
buttonPanel.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
importPrivateKeysSubmitAction = new ImportPrivateKeysSubmitAction(this.bitcoinController, mainFrame, this,
ImageLoader.createImageIcon(ImageLoader.IMPORT_PRIVATE_KEYS_ICON_FILE), walletPasswordField, passwordField1, passwordField2);
MultiBitButton submitButton = new MultiBitButton(importPrivateKeysSubmitAction, controller);
submitButton.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
buttonPanel.add(submitButton);
return buttonPanel;
}
@Override
public void displayView(DisplayHint displayHint) {
// If it is a wallet transaction change no need to update.
if (DisplayHint.WALLET_TRANSACTIONS_HAVE_CHANGED == displayHint) {
return;
}
walletFilenameLabel.setText(this.bitcoinController.getModel().getActiveWalletFilename());
walletDescriptionLabel.setText(this.bitcoinController.getModel().getActivePerWalletModelData().getWalletDescription());
boolean walletPasswordRequired = false;
if (this.bitcoinController.getModel().getActiveWallet() != null && this.bitcoinController.getModel().getActiveWallet().getEncryptionType() == EncryptionType.ENCRYPTED_SCRYPT_AES) {
walletPasswordRequired = true;
}
enableWalletPassword(walletPasswordRequired);
walletBusyChange(this.bitcoinController.getModel().getActivePerWalletModelData().isBusy());
if (outputFilename == null || "".equals(outputFilename)) {
outputFilenameLabel.setText(controller.getLocaliser().getString("showImportPrivateKeysPanel.noFileSelected"));
}
messageLabel1.setText(" ");
messageLabel2.setText(" ");
}
@Override
public void navigateAwayFromView() {
}
private void chooseFile(MultiBitButton callingButton) {
JFileChooser.setDefaultLocale(controller.getLocaliser().getLocale());
fileChooser = new JFileChooser();
fileChooser.setLocale(controller.getLocaliser().getLocale());
fileChooser.setDialogTitle(chooseFilenameButtonText);
adjustedFont = FontSizer.INSTANCE.getAdjustedDefaultFont();
if (adjustedFont != null) {
setFileChooserFont(new Container[] {fileChooser});
}
fileChooser.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.addChoosableFileFilter(multiBitFileChooser);
// fileChooser.addChoosableFileFilter(myWalletPlainFileChooser);
// fileChooser.addChoosableFileFilter(myWalletEncryptedFileChooser);
fileChooser.setAcceptAllFileFilterUsed(false);
fileChooser.setFileFilter(multiBitFileChooser);
if (outputFilename != null && !"".equals(outputFilename)) {
fileChooser.setCurrentDirectory(new File(outputFilename));
fileChooser.setSelectedFile(new File(outputFilename));
} else {
if (this.bitcoinController.getModel().getActiveWalletFilename() != null) {
fileChooser.setCurrentDirectory(new File(this.bitcoinController.getModel().getActiveWalletFilename()));
}
String defaultFileName = fileChooser.getCurrentDirectory().getAbsoluteFile() + File.separator
+ controller.getLocaliser().getString("saveWalletAsView.untitled") + "."
+ BitcoinModel.PRIVATE_KEY_FILE_EXTENSION;
fileChooser.setSelectedFile(new File(defaultFileName));
}
try {
callingButton.setEnabled(false);
mainFrame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
fileChooser.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
int returnVal = fileChooser.showOpenDialog(mainFrame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
numberOfKeysLabel.setText(" ");
replayDateLabel.setText(" ");
passwordField1.setText("");
File file = fileChooser.getSelectedFile();
if (file != null) {
outputFilename = file.getAbsolutePath();
outputFilenameLabel.setText(outputFilename);
if (multiBitFileChooser.accept(file)) {
try {
String firstLine = readFirstLineInFile(file);
if (firstLine != null && firstLine.startsWith(encrypterDecrypter.getOpenSSLMagicText())) {
// File is encrypted.
enableImportFilePasswordPanel(true);
passwordField1.requestFocusInWindow();
} else {
// File is not encrypted.
enableImportFilePasswordPanel(false);
readInImportFileAndUpdateDetails();
}
} catch (IOException e) {
setMessageText1(controller.getLocaliser().getString(
"importPrivateKeysSubmitAction.privateKeysImportFailure",
new Object[] { e.getClass().getName() + " " + e.getMessage() }));
} catch (KeyCrypterException e) {
// TODO User may not have entered a password yet so
// password incorrect is ok at this stage.
// Other errors indicate a more general problem with
// the
// import.
setMessageText1(controller.getLocaliser().getString(
"importPrivateKeysSubmitAction.privateKeysImportFailure",
new Object[] { e.getClass().getName() + " " + e.getMessage() }));
}
} else if (myWalletEncryptedFileChooser.accept(file)) {
enableImportFilePasswordPanel(true);
passwordField1.requestFocusInWindow();
} else if (myWalletPlainFileChooser.accept(file)) {
// File is not encrypted.
enableImportFilePasswordPanel(false);
try {
readInImportFileAndUpdateDetails();
} catch (KeyCrypterException e) {
setMessageText1(controller.getLocaliser().getString(
"importPrivateKeysSubmitAction.privateKeysImportFailure",
new Object[] { e.getClass().getName() + " " + e.getMessage() }));
}
}
}
}
} finally {
mainFrame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
callingButton.setEnabled(true);
}
}
private void enableSecondPasswordPanel(boolean enablePanel) {
passwordField2.setEnabled(enablePanel);
passwordPromptLabel2.setEnabled(enablePanel);
passwordField2.setVisible(enablePanel);
passwordPromptLabel2.setVisible(enablePanel);
}
private void enableImportFilePasswordPanel(boolean enableImportFilePanel) {
if (enableImportFilePanel) {
// Enable the import file password panel.
passwordPromptLabel1.setEnabled(true);
passwordField1.setEnabled(true);
unlockButton.setEnabled(true);
passwordInfoLabel.setForeground(Color.BLACK);
} else {
// Disable the import file password panel.
passwordPromptLabel1.setEnabled(false);
passwordField1.setEnabled(false);
unlockButton.setEnabled(false);
passwordInfoLabel.setForeground(Color.GRAY);
}
}
private void enableWalletPassword(boolean enableWalletPassword) {
if (enableWalletPassword) {
// Enable the wallet password.
walletPasswordField.setEnabled(true);
walletPasswordPromptLabel.setEnabled(true);
} else {
// Disable the wallet password.
walletPasswordField.setEnabled(false);
walletPasswordPromptLabel.setEnabled(false);
}
}
/**
* Read in the import file and show the file details.
* @throws EncrypterDecrypterException
* @throws PrivateKeysHandlerException
*/
private void readInImportFileAndUpdateDetails() throws PrivateKeysHandlerException, KeyCrypterException {
// Update number of keys and earliest date.
try {
File file = new File(outputFilename);
if (multiBitFileChooser.accept(file)) {
// Read in contents of file.
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
PrivateKeysHandler privateKeysHandler = new PrivateKeysHandler(this.bitcoinController.getModel().getNetworkParameters());
Collection<PrivateKeyAndDate> privateKeyAndDates = privateKeysHandler.readInPrivateKeys(new File(outputFilename),
CharBuffer.wrap(passwordField1.getPassword()));
numberOfKeysLabel.setText("" + privateKeyAndDates.size());
Date replayDate = privateKeysHandler.calculateReplayDate(privateKeyAndDates, this.bitcoinController.getModel()
.getActiveWallet());
if (replayDate == null) {
replayDateLabel.setText(controller.getLocaliser().getString(
"showImportPrivateKeysPanel.thereWereMissingKeyDates"));
} else {
replayDateLabel.setText(DateFormat.getDateInstance(DateFormat.MEDIUM, controller.getLocaliser().getLocale())
.format(replayDate));
}
setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
} else if (myWalletEncryptedFileChooser.accept(file)) {
try {
String importFileContents = PrivateKeysHandler.readFile(file);
String mainPassword = new String(passwordField1.getPassword());
String secondPassword = new String(passwordField2.getPassword());
MyWallet wallet = new MyWallet(importFileContents, mainPassword);
boolean needSecondPassword = false;
if (wallet.isDoubleEncrypted()) {
if ("".equals(secondPassword)) {
needSecondPassword = true;
requestSecondPassword();
}
}
if (!needSecondPassword) {
wallet.setTemporySecondPassword(secondPassword);
int numberOfKeys = 0;
if (wallet.getBitcoinJWallet() != null && wallet.getBitcoinJWallet().getKeychain() != null) {
numberOfKeys = wallet.getBitcoinJWallet().getKeychainSize();
}
numberOfKeysLabel.setText("" + numberOfKeys);
replayDateLabel.setText(controller.getLocaliser().getString(
"showImportPrivateKeysPanel.thereWereMissingKeyDates"));
}
} catch (Exception e) {
throw new KeyCrypterException("Error Decrypting Wallet");
}
} else if (myWalletPlainFileChooser.accept(file)) {
try {
String importFileContents = PrivateKeysHandler.readFile(file);
MyWallet wallet = new MyWallet(importFileContents);
int numberOfKeys = 0;
if (wallet.getBitcoinJWallet() != null && wallet.getBitcoinJWallet().getKeychain() != null) {
numberOfKeys = wallet.getBitcoinJWallet().getKeychainSize();
}
numberOfKeysLabel.setText("" + numberOfKeys);
replayDateLabel.setText(controller.getLocaliser().getString(
"showImportPrivateKeysPanel.thereWereMissingKeyDates"));
} catch (Exception e) {
throw new KeyCrypterException("Error Opening Wallet");
}
}
} finally {
setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
}
public void requestSecondPassword() {
enableSecondPasswordPanel(true);
setMessageText1(controller.getLocaliser().getString("importPrivateKeysSubmitAction.enterTheSecondPassword"));
}
public String getOutputFilename() {
return outputFilename;
}
public void clearPasswords() {
walletPasswordField.setText("");
passwordField1.setText("");
if (passwordField2 != null) {
passwordField2.setText("");
}
}
public void setMessageText1(String message1) {
if (messageLabel1 != null) {
messageLabel1.setText(message1);
}
}
public String getMessageText1() {
if (messageLabel1 != null) {
return messageLabel1.getText();
} else {
return "";
}
}
public void setMessageText2(String message2) {
if (messageLabel2 != null) {
messageLabel2.setText(message2);
}
}
public String getMessageText2() {
if (messageLabel2 != null) {
return messageLabel2.getText();
} else {
return "";
}
}
private String readFirstLineInFile(File file) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(file));
return reader.readLine();
}
@Override
public Icon getViewIcon() {
return ImageLoader.createImageIcon(ImageLoader.IMPORT_PRIVATE_KEYS_ICON_FILE);
}
@Override
public String getViewTitle() {
return controller.getLocaliser().getString("showImportPrivateKeysAction.text");
}
@Override
public String getViewTooltip() {
return controller.getLocaliser().getString("showImportPrivateKeysAction.tooltip");
}
@Override
public View getViewId() {
return View.SHOW_IMPORT_PRIVATE_KEYS_VIEW;
}
// Used in testing.
public MultiBitButton getUnlockButton() {
return unlockButton;
}
public ImportPrivateKeysSubmitAction getImportPrivateKeysSubmitAction() {
return importPrivateKeysSubmitAction;
}
public void setOutputFilename(String outputFilename) {
this.outputFilename = outputFilename;
}
public void setImportFilePassword(CharSequence password) {
passwordField1.setText(password.toString());
}
public void setWalletPassword(CharSequence password) {
walletPasswordField.setText(password.toString());
}
public boolean isWalletPasswordFieldEnabled() {
return walletPasswordField.isEnabled();
}
@Override
public void walletBusyChange(boolean newWalletIsBusy) {
// Update the enable status of the action to match the wallet busy status.
if (this.bitcoinController.getModel().getActivePerWalletModelData().isBusy()) {
// Wallet is busy with another operation that may change the private keys - Action is disabled.
importPrivateKeysSubmitAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipText(controller.getLocaliser().getString("multiBitSubmitAction.walletIsBusy",
new Object[]{controller.getLocaliser().getString(this.bitcoinController.getModel().getActivePerWalletModelData().getBusyTaskKey())})));
importPrivateKeysSubmitAction.setEnabled(false);
} else {
// Enable unless wallet has been modified by another process.
if (!this.bitcoinController.getModel().getActivePerWalletModelData().isFilesHaveBeenChangedByAnotherProcess()) {
importPrivateKeysSubmitAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipText(controller.getLocaliser().getString("importPrivateKeysSubmitAction.tooltip")));
importPrivateKeysSubmitAction.setEnabled(true);
}
}
}
private void setFileChooserFont(Component[] comp) {
for (int x = 0; x < comp.length; x++) {
if (comp[x] instanceof Container)
setFileChooserFont(((Container) comp[x]).getComponents());
try {
comp[x].setFont(adjustedFont);
} catch (Exception e) {
}// do nothing
}
}
} | src/main/java/org/multibit/viewsystem/swing/view/panels/ImportPrivateKeysPanel.java | /**
* Copyright 2011 multibit.org
*
* Licensed under the MIT license (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/mit-license.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.multibit.viewsystem.swing.view.panels;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.ComponentOrientation;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.CharBuffer;
import java.text.DateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Locale;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.SwingConstants;
import javax.swing.filechooser.FileFilter;
import org.multibit.controller.Controller;
import org.multibit.controller.bitcoin.BitcoinController;
import org.multibit.crypto.KeyCrypterOpenSSL;
import org.multibit.file.PrivateKeyAndDate;
import org.multibit.file.PrivateKeysHandler;
import org.multibit.file.PrivateKeysHandlerException;
import org.multibit.model.bitcoin.BitcoinModel;
import org.multibit.model.bitcoin.WalletBusyListener;
import org.multibit.model.core.CoreModel;
import org.multibit.utils.ImageLoader;
import org.multibit.viewsystem.DisplayHint;
import org.multibit.viewsystem.View;
import org.multibit.viewsystem.Viewable;
import org.multibit.viewsystem.swing.ColorAndFontConstants;
import org.multibit.viewsystem.swing.MultiBitFrame;
import org.multibit.viewsystem.swing.action.HelpContextAction;
import org.multibit.viewsystem.swing.action.ImportPrivateKeysSubmitAction;
import org.multibit.viewsystem.swing.view.PrivateKeyFileFilter;
import org.multibit.viewsystem.swing.view.components.FontSizer;
import org.multibit.viewsystem.swing.view.components.HelpButton;
import org.multibit.viewsystem.swing.view.components.MultiBitButton;
import org.multibit.viewsystem.swing.view.components.MultiBitLabel;
import org.multibit.viewsystem.swing.view.components.MultiBitTitledPanel;
import com.google.dogecoin.crypto.KeyCrypterException;
import org.bitcoinj.wallet.Protos.Wallet.EncryptionType;
import com.piuk.blockchain.MyWallet;
import com.piuk.blockchain.MyWalletEncryptedKeyFileFilter;
import com.piuk.blockchain.MyWalletPlainKeyFileFilter;
/**
* The import private keys view.
*/
public class ImportPrivateKeysPanel extends JPanel implements Viewable, WalletBusyListener {
private static final long serialVersionUID = 444992294329957705L;
private final Controller controller;
private final BitcoinController bitcoinController;
private MultiBitFrame mainFrame;
private MultiBitLabel walletFilenameLabel;
private MultiBitLabel walletDescriptionLabel;
private MultiBitButton chooseFilenameButton;
private String chooseFilenameButtonText;
private JFileChooser fileChooser;
private MultiBitLabel outputFilenameLabel;
private MultiBitLabel messageLabel1;
private MultiBitLabel messageLabel2;
private String outputFilename;
private MultiBitLabel passwordInfoLabel;
private JPasswordField passwordField1;
private MultiBitLabel passwordPromptLabel1;
private MultiBitButton unlockButton;
private JPasswordField passwordField2;
private MultiBitLabel passwordPromptLabel2;
private JPasswordField walletPasswordField;
private MultiBitLabel walletPasswordPromptLabel;
private JLabel numberOfKeysLabel;
private JLabel replayDateLabel;
private ImportPrivateKeysSubmitAction importPrivateKeysSubmitAction;
private KeyCrypterOpenSSL encrypterDecrypter;
public FileFilter multiBitFileChooser;
public FileFilter myWalletPlainFileChooser;
public FileFilter myWalletEncryptedFileChooser;
private Font adjustedFont;
/**
* Creates a new {@link ImportPrivateKeysPanel}.
*/
public ImportPrivateKeysPanel(BitcoinController bitcoinController, MultiBitFrame mainFrame) {
this.bitcoinController = bitcoinController;
this.controller = this.bitcoinController;
this.mainFrame = mainFrame;
setBackground(ColorAndFontConstants.VERY_LIGHT_BACKGROUND_COLOR);
applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
outputFilename = "";
initUI();
walletBusyChange(this.bitcoinController.getModel().getActivePerWalletModelData().isBusy());
this.bitcoinController.registerWalletBusyListener(this);
enableImportFilePasswordPanel(false);
passwordField1.setText("");
passwordField2.setText("");
boolean walletPasswordRequired = false;
if (this.bitcoinController.getModel().getActiveWallet() != null && this.bitcoinController.getModel().getActiveWallet().getEncryptionType() == EncryptionType.ENCRYPTED_SCRYPT_AES) {
walletPasswordRequired = true;
}
enableWalletPassword(walletPasswordRequired);
encrypterDecrypter = new KeyCrypterOpenSSL();
multiBitFileChooser = new PrivateKeyFileFilter(controller);
myWalletPlainFileChooser = new MyWalletPlainKeyFileFilter();
myWalletEncryptedFileChooser = new MyWalletEncryptedKeyFileFilter();
}
private void initUI() {
setLayout(new BorderLayout());
JPanel mainPanel = new JPanel();
mainPanel.setMinimumSize(new Dimension(550, 160));
mainPanel.setLayout(new GridBagLayout());
mainPanel.setOpaque(false);
mainPanel.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
String[] keys = new String[] { "resetTransactionsPanel.walletDescriptionLabel",
"resetTransactionsPanel.walletFilenameLabel", "showExportPrivateKeysPanel.passwordPrompt",
"showExportPrivateKeysPanel.repeatPasswordPrompt", "showImportPrivateKeysPanel.numberOfKeys.text",
"showImportPrivateKeysPanel.replayDate.text" };
int stentWidth = MultiBitTitledPanel.calculateStentWidthForKeys(controller.getLocaliser(), keys, this)
+ ExportPrivateKeysPanel.STENT_DELTA;
GridBagConstraints constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 0;
constraints.gridy = 0;
constraints.gridwidth = 2;
constraints.weightx = 1;
constraints.weighty = 1;
constraints.anchor = GridBagConstraints.LINE_START;
JPanel walletPanel = createWalletPanel(stentWidth);
mainPanel.add(walletPanel, constraints);
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 0;
constraints.gridy = 1;
constraints.gridwidth = 2;
constraints.weightx = 1;
constraints.weighty = 1;
constraints.anchor = GridBagConstraints.LINE_START;
JPanel filenamePanel = createFilenamePanel(stentWidth);
mainPanel.add(filenamePanel, constraints);
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 0;
constraints.gridy = 2;
constraints.gridwidth = 2;
constraints.weightx = 1;
constraints.weighty = 0.2;
constraints.anchor = GridBagConstraints.LINE_START;
JPanel passwordPanel = createPasswordPanel(stentWidth);
mainPanel.add(passwordPanel, constraints);
JLabel filler1 = new JLabel();
filler1.setOpaque(false);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 0;
constraints.gridy = 3;
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.weightx = 1;
constraints.weighty = 0.1;
constraints.anchor = GridBagConstraints.CENTER;
mainPanel.add(filler1, constraints);
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 0;
constraints.gridy = 4;
constraints.gridwidth = 1;
constraints.weightx = 0.4;
constraints.weighty = 0.06;
constraints.anchor = GridBagConstraints.LINE_START;
JPanel buttonPanel = createButtonPanel();
mainPanel.add(buttonPanel, constraints);
messageLabel1 = new MultiBitLabel("");
messageLabel1.setOpaque(false);
messageLabel1.setBorder(BorderFactory.createEmptyBorder(0, 30, 0, 0));
messageLabel1.setHorizontalAlignment(JLabel.LEADING);
messageLabel1.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 0;
constraints.gridy = 5;
constraints.gridwidth = 3;
constraints.weightx = 1;
constraints.weighty = 0.06;
constraints.anchor = GridBagConstraints.LINE_START;
mainPanel.add(messageLabel1, constraints);
messageLabel2 = new MultiBitLabel("");
messageLabel2.setOpaque(false);
messageLabel2.setBorder(BorderFactory.createEmptyBorder(0, 30, 0, 0));
messageLabel2.setHorizontalAlignment(JLabel.LEADING);
messageLabel2.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 0;
constraints.gridy = 6;
constraints.gridwidth = 3;
constraints.weightx = 1;
constraints.weighty = 0.06;
constraints.anchor = GridBagConstraints.LINE_START;
mainPanel.add(messageLabel2, constraints);
Action helpAction;
if (ComponentOrientation.LEFT_TO_RIGHT == ComponentOrientation.getOrientation(controller.getLocaliser().getLocale())) {
helpAction = new HelpContextAction(controller, ImageLoader.HELP_CONTENTS_BIG_ICON_FILE,
"multiBitFrame.helpMenuText", "multiBitFrame.helpMenuTooltip", "multiBitFrame.helpMenuText",
HelpContentsPanel.HELP_IMPORTING_PRIVATE_KEYS_URL);
} else {
helpAction = new HelpContextAction(controller, ImageLoader.HELP_CONTENTS_BIG_RTL_ICON_FILE,
"multiBitFrame.helpMenuText", "multiBitFrame.helpMenuTooltip", "multiBitFrame.helpMenuText",
HelpContentsPanel.HELP_IMPORTING_PRIVATE_KEYS_URL);
}
HelpButton helpButton = new HelpButton(helpAction, controller);
helpButton.setText("");
String tooltipText = HelpContentsPanel.createMultilineTooltipText(new String[] { controller.getLocaliser().getString(
"multiBitFrame.helpMenuTooltip") });
helpButton.setToolTipText(tooltipText);
helpButton.setHorizontalAlignment(SwingConstants.LEADING);
helpButton.setBorder(BorderFactory.createEmptyBorder(0, AbstractTradePanel.HELP_BUTTON_INDENT,
AbstractTradePanel.HELP_BUTTON_INDENT, AbstractTradePanel.HELP_BUTTON_INDENT));
helpButton.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.NONE;
constraints.gridx = 0;
constraints.gridy = 7;
constraints.weightx = 1;
constraints.weighty = 0.1;
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.anchor = GridBagConstraints.BASELINE_LEADING;
mainPanel.add(helpButton, constraints);
JLabel filler2 = new JLabel();
filler2.setOpaque(false);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 0;
constraints.gridy = 8;
constraints.gridwidth = 1;
constraints.weightx = 1;
constraints.weighty = 100;
constraints.anchor = GridBagConstraints.CENTER;
mainPanel.add(filler2, constraints);
JScrollPane mainScrollPane = new JScrollPane(mainPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
mainScrollPane.setBorder(BorderFactory.createEmptyBorder());
mainScrollPane.getViewport().setBackground(ColorAndFontConstants.VERY_LIGHT_BACKGROUND_COLOR);
mainScrollPane.getViewport().setOpaque(true);
mainScrollPane.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
mainScrollPane.getHorizontalScrollBar().setUnitIncrement(CoreModel.SCROLL_INCREMENT);
mainScrollPane.getVerticalScrollBar().setUnitIncrement(CoreModel.SCROLL_INCREMENT);
add(mainScrollPane, BorderLayout.CENTER);
}
private JPanel createWalletPanel(int stentWidth) {
MultiBitTitledPanel inputWalletPanel = new MultiBitTitledPanel(controller.getLocaliser().getString(
"showImportPrivateKeysPanel.wallet.title"), ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
GridBagConstraints constraints = new GridBagConstraints();
MultiBitTitledPanel.addLeftJustifiedTextAtIndent(
controller.getLocaliser().getString("showImportPrivateKeysPanel.wallet.text"), 3, inputWalletPanel);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 1;
constraints.gridy = 4;
constraints.weightx = 0.3;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_START;
inputWalletPanel.add(MultiBitTitledPanel.createStent(stentWidth, ExportPrivateKeysPanel.STENT_HEIGHT), constraints);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 2;
constraints.gridy = 5;
constraints.weightx = 0.05;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.CENTER;
inputWalletPanel.add(MultiBitTitledPanel.createStent(MultiBitTitledPanel.SEPARATION_BETWEEN_NAME_VALUE_PAIRS), constraints);
MultiBitLabel walletDescriptionLabelLabel = new MultiBitLabel(controller.getLocaliser().getString(
"resetTransactionsPanel.walletDescriptionLabel"));
walletDescriptionLabelLabel.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.NONE;
constraints.gridx = 1;
constraints.gridy = 5;
constraints.weightx = 0.5;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_END;
inputWalletPanel.add(walletDescriptionLabelLabel, constraints);
walletDescriptionLabel = new MultiBitLabel(this.bitcoinController.getModel().getActivePerWalletModelData().getWalletDescription());
walletDescriptionLabel.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.NONE;
constraints.gridx = 3;
constraints.gridy = 5;
constraints.weightx = 0.5;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_START;
inputWalletPanel.add(walletDescriptionLabel, constraints);
MultiBitLabel walletFilenameLabelLabel = new MultiBitLabel(controller.getLocaliser().getString(
"resetTransactionsPanel.walletFilenameLabel"));
walletFilenameLabelLabel.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.NONE;
constraints.gridx = 1;
constraints.gridy = 6;
constraints.weightx = 0.5;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_END;
inputWalletPanel.add(walletFilenameLabelLabel, constraints);
walletFilenameLabel = new MultiBitLabel(this.bitcoinController.getModel().getActiveWalletFilename());
walletFilenameLabel.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.NONE;
constraints.gridx = 3;
constraints.gridy = 6;
constraints.weightx = 0.5;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_START;
inputWalletPanel.add(walletFilenameLabel, constraints);
JPanel filler3 = new JPanel();
filler3.setOpaque(false);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 1;
constraints.gridy = 7;
constraints.weightx = 0.3;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_START;
inputWalletPanel.add(filler3, constraints);
walletPasswordPromptLabel = new MultiBitLabel(controller.getLocaliser().getString("showExportPrivateKeysPanel.walletPasswordPrompt"));
walletPasswordPromptLabel.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.NONE;
constraints.gridx = 1;
constraints.gridy = 8;
constraints.weightx = 0.3;
constraints.weighty = 0.1;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_END;
inputWalletPanel.add(walletPasswordPromptLabel, constraints);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 2;
constraints.gridy = 8;
constraints.weightx = 0.05;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.CENTER;
inputWalletPanel.add(MultiBitTitledPanel.createStent(MultiBitTitledPanel.SEPARATION_BETWEEN_NAME_VALUE_PAIRS),
constraints);
walletPasswordField = new JPasswordField(24);
walletPasswordField.setMinimumSize(new Dimension(200, 20));
walletPasswordField.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.NONE;
constraints.gridx = 3;
constraints.gridy = 8;
constraints.weightx = 0.3;
constraints.weighty = 0.6;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_START;
inputWalletPanel.add(walletPasswordField, constraints);
JPanel filler4 = new JPanel();
filler4.setOpaque(false);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 1;
constraints.gridy = 9;
constraints.weightx = 0.3;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_START;
inputWalletPanel.add(filler4, constraints);
return inputWalletPanel;
}
private JPanel createFilenamePanel(int stentWidth) {
MultiBitTitledPanel outputFilenamePanel = new MultiBitTitledPanel(controller.getLocaliser().getString(
"showImportPrivateKeysPanel.filename.title"), ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
MultiBitTitledPanel.addLeftJustifiedTextAtIndent(" ", 1, outputFilenamePanel);
GridBagConstraints constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 0;
constraints.gridy = 2;
constraints.weightx = 0.3;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_START;
outputFilenamePanel.add(MultiBitTitledPanel.getIndentPanel(1), constraints);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 1;
constraints.gridy = 3;
constraints.weightx = 0.3;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_START;
outputFilenamePanel.add(MultiBitTitledPanel.createStent(stentWidth, ExportPrivateKeysPanel.STENT_HEIGHT), constraints);
chooseFilenameButtonText = "";
String chooseFilenameButtonText1 = controller.getLocaliser().getString("showImportPrivateKeysPanel.filename.text");
String chooseFilenameButtonText2 = controller.getLocaliser().getString("showImportPrivateKeysPanel.filename.text.2");
// If the second term is localised, use that, otherwise the first.
if (controller.getLocaliser().getLocale().equals(Locale.ENGLISH)) {
chooseFilenameButtonText = chooseFilenameButtonText2;
} else {
if (!"Import from ...".equals(chooseFilenameButtonText2)) {
chooseFilenameButtonText = chooseFilenameButtonText2;
} else {
chooseFilenameButtonText = chooseFilenameButtonText1;
}
}
chooseFilenameButton = new MultiBitButton(chooseFilenameButtonText);
chooseFilenameButton.setToolTipText(HelpContentsPanel.createTooltipText(controller.getLocaliser().getString("showImportPrivateKeysPanel.filename.tooltip")));
chooseFilenameButton.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
final MultiBitButton finalChooseFilenameButton = chooseFilenameButton;
chooseFilenameButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
chooseFile(finalChooseFilenameButton);
}
});
MultiBitLabel walletFilenameLabelLabel = new MultiBitLabel(controller.getLocaliser().getString(
"resetTransactionsPanel.walletFilenameLabel"));
walletFilenameLabelLabel.setHorizontalAlignment(JLabel.TRAILING);
walletFilenameLabelLabel.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 1;
constraints.gridy = 4;
constraints.weightx = 0.5;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_END;
outputFilenamePanel.add(walletFilenameLabelLabel, constraints);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 2;
constraints.gridy = 5;
constraints.weightx = 0.05;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.CENTER;
outputFilenamePanel.add(MultiBitTitledPanel.createStent(MultiBitTitledPanel.SEPARATION_BETWEEN_NAME_VALUE_PAIRS),
constraints);
outputFilenameLabel = new MultiBitLabel(outputFilename);
outputFilenameLabel.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 3;
constraints.gridy = 4;
constraints.weightx = 0.5;
constraints.weighty = 0.3;
constraints.gridwidth = 2;
constraints.anchor = GridBagConstraints.LINE_START;
outputFilenamePanel.add(outputFilenameLabel, constraints);
JPanel filler0 = new JPanel();
filler0.setOpaque(false);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 5;
constraints.gridy = 4;
constraints.weightx = 100;
constraints.weighty = 1;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_END;
outputFilenamePanel.add(filler0, constraints);
JPanel filler2 = new JPanel();
filler2.setOpaque(false);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 1;
constraints.gridy = 5;
constraints.weightx = 0.3;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_START;
outputFilenamePanel.add(filler2, constraints);
MultiBitLabel numberOfKeysLabelLabel = new MultiBitLabel(controller.getLocaliser().getString(
"showImportPrivateKeysPanel.numberOfKeys.text"));
numberOfKeysLabelLabel.setToolTipText(HelpContentsPanel.createTooltipText(controller.getLocaliser()
.getString("showImportPrivateKeysPanel.numberOfKeys.tooltip")));
numberOfKeysLabelLabel.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.NONE;
constraints.gridx = 1;
constraints.gridy = 6;
constraints.weightx = 0.5;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_END;
outputFilenamePanel.add(numberOfKeysLabelLabel, constraints);
JPanel filler3 = new JPanel();
filler3.setOpaque(false);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 2;
constraints.gridy = 6;
constraints.weightx = 0.1;
constraints.weighty = 0.1;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_START;
outputFilenamePanel.add(filler3, constraints);
numberOfKeysLabel = new MultiBitLabel(" ");
numberOfKeysLabel.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 3;
constraints.gridy = 6;
constraints.weightx = 0.5;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_START;
outputFilenamePanel.add(numberOfKeysLabel, constraints);
MultiBitLabel replayDateLabelLabel = new MultiBitLabel(controller.getLocaliser().getString(
"showImportPrivateKeysPanel.replayDate.text"));
replayDateLabelLabel.setToolTipText(HelpContentsPanel.createTooltipText(controller.getLocaliser().getString("showImportPrivateKeysPanel.replayDate.tooltip")));
replayDateLabelLabel.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.NONE;
constraints.gridx = 1;
constraints.gridy = 7;
constraints.weightx = 0.5;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_END;
outputFilenamePanel.add(replayDateLabelLabel, constraints);
replayDateLabel = new MultiBitLabel(" ");
replayDateLabel.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridx = 3;
constraints.gridy = 7;
constraints.weightx = 0.5;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_START;
outputFilenamePanel.add(replayDateLabel, constraints);
JPanel filler4 = new JPanel();
filler4.setOpaque(false);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 1;
constraints.gridy = 8;
constraints.weightx = 0.3;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_START;
outputFilenamePanel.add(filler4, constraints);
constraints.fill = GridBagConstraints.NONE;
constraints.gridx = 3;
constraints.gridy = 9;
constraints.weightx = 0.5;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_START;
outputFilenamePanel.add(chooseFilenameButton, constraints);
JPanel filler5 = new JPanel();
filler5.setOpaque(false);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 1;
constraints.gridy = 10;
constraints.weightx = 0.3;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_START;
outputFilenamePanel.add(filler5, constraints);
return outputFilenamePanel;
}
private JPanel createPasswordPanel(int stentWidth) {
// Do/do not password protect radios.
MultiBitTitledPanel passwordProtectPanel = new MultiBitTitledPanel(controller.getLocaliser().getString(
"showImportPrivateKeysPanel.password.title"), ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
GridBagConstraints constraints = new GridBagConstraints();
passwordInfoLabel = MultiBitTitledPanel.addLeftJustifiedTextAtIndent(
controller.getLocaliser().getString("showImportPrivateKeysPanel.enterPassword"), 3, passwordProtectPanel);
passwordInfoLabel.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 1;
constraints.gridy = 4;
constraints.weightx = 0.3;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_START;
passwordProtectPanel.add(MultiBitTitledPanel.createStent(stentWidth, ExportPrivateKeysPanel.STENT_HEIGHT), constraints);
passwordPromptLabel1 = new MultiBitLabel(controller.getLocaliser().getString("showExportPrivateKeysPanel.passwordPrompt"));
passwordPromptLabel1.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.NONE;
constraints.gridx = 1;
constraints.gridy = 5;
constraints.weightx = 0.3;
constraints.weighty = 0.1;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_END;
passwordProtectPanel.add(passwordPromptLabel1, constraints);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 2;
constraints.gridy = 5;
constraints.weightx = 0.05;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.CENTER;
passwordProtectPanel.add(MultiBitTitledPanel.createStent(MultiBitTitledPanel.SEPARATION_BETWEEN_NAME_VALUE_PAIRS),
constraints);
passwordField1 = new JPasswordField(24);
passwordField1.setMinimumSize(new Dimension(200, 20));
passwordField1.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.NONE;
constraints.gridx = 3;
constraints.gridy = 5;
constraints.weightx = 0.3;
constraints.weighty = 0.6;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_START;
passwordProtectPanel.add(passwordField1, constraints);
passwordPromptLabel2 = new MultiBitLabel(controller.getLocaliser().getString("showImportPrivateKeysPanel.secondPassword"));
passwordPromptLabel2.setVisible(false);
passwordPromptLabel2.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.NONE;
constraints.gridx = 1;
constraints.gridy = 6;
constraints.weightx = 0.3;
constraints.weighty = 0.1;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_END;
passwordProtectPanel.add(passwordPromptLabel2, constraints);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 2;
constraints.gridy = 6;
constraints.weightx = 0.05;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.CENTER;
passwordProtectPanel.add(MultiBitTitledPanel.createStent(MultiBitTitledPanel.SEPARATION_BETWEEN_NAME_VALUE_PAIRS),
constraints);
passwordField2 = new JPasswordField(24);
passwordField2.setMinimumSize(new Dimension(200, 20));
passwordField2.setVisible(false);
passwordField2.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.NONE;
constraints.gridx = 3;
constraints.gridy = 6;
constraints.weightx = 0.3;
constraints.weighty = 0.6;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_START;
passwordProtectPanel.add(passwordField2, constraints);
JLabel filler3 = new JLabel();
filler3.setMinimumSize(new Dimension(3, 3));
filler3.setMaximumSize(new Dimension(3, 3));
filler3.setPreferredSize(new Dimension(3, 3));
filler3.setOpaque(false);
constraints.fill = GridBagConstraints.NONE;
constraints.gridx = 1;
constraints.gridy = 7;
constraints.weightx = 0.1;
constraints.weighty = 0.1;
constraints.gridwidth = 1;
constraints.gridheight = 1;
constraints.anchor = GridBagConstraints.CENTER;
passwordProtectPanel.add(filler3, constraints);
unlockButton = new MultiBitButton(controller.getLocaliser().getString("showImportPrivateKeysPanel.unlock.text"));
unlockButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
setMessageText1(" ");
try {
readInImportFileAndUpdateDetails();
} catch (KeyCrypterException ede) {
setMessageText1(controller.getLocaliser().getString("importPrivateKeysSubmitAction.privateKeysUnlockFailure",
new Object[] { ede.getMessage() }));
}
}
});
unlockButton.setToolTipText(HelpContentsPanel.createTooltipText(controller.getLocaliser().getString("showImportPrivateKeysPanel.unlock.tooltip")));
unlockButton.setEnabled(false);
unlockButton.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
constraints.fill = GridBagConstraints.NONE;
constraints.gridx = 3;
constraints.gridy = 8;
constraints.weightx = 0.3;
constraints.weighty = 0.6;
constraints.gridwidth = 3;
constraints.anchor = GridBagConstraints.LINE_START;
passwordProtectPanel.add(unlockButton, constraints);
JPanel filler5 = new JPanel();
filler5.setOpaque(false);
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 1;
constraints.gridy = 9;
constraints.weightx = 0.3;
constraints.weighty = 0.3;
constraints.gridwidth = 1;
constraints.anchor = GridBagConstraints.LINE_START;
passwordProtectPanel.add(filler3, constraints);
return passwordProtectPanel;
}
private JPanel createButtonPanel() {
JPanel buttonPanel = new JPanel();
buttonPanel.setOpaque(false);
FlowLayout flowLayout = new FlowLayout();
flowLayout.setAlignment(FlowLayout.LEADING);
buttonPanel.setLayout(flowLayout);
buttonPanel.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
importPrivateKeysSubmitAction = new ImportPrivateKeysSubmitAction(this.bitcoinController, mainFrame, this,
ImageLoader.createImageIcon(ImageLoader.IMPORT_PRIVATE_KEYS_ICON_FILE), walletPasswordField, passwordField1, passwordField2);
MultiBitButton submitButton = new MultiBitButton(importPrivateKeysSubmitAction, controller);
submitButton.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
buttonPanel.add(submitButton);
return buttonPanel;
}
@Override
public void displayView(DisplayHint displayHint) {
// If it is a wallet transaction change no need to update.
if (DisplayHint.WALLET_TRANSACTIONS_HAVE_CHANGED == displayHint) {
return;
}
walletFilenameLabel.setText(this.bitcoinController.getModel().getActiveWalletFilename());
walletDescriptionLabel.setText(this.bitcoinController.getModel().getActivePerWalletModelData().getWalletDescription());
boolean walletPasswordRequired = false;
if (this.bitcoinController.getModel().getActiveWallet() != null && this.bitcoinController.getModel().getActiveWallet().getEncryptionType() == EncryptionType.ENCRYPTED_SCRYPT_AES) {
walletPasswordRequired = true;
}
enableWalletPassword(walletPasswordRequired);
walletBusyChange(this.bitcoinController.getModel().getActivePerWalletModelData().isBusy());
if (outputFilename == null || "".equals(outputFilename)) {
outputFilenameLabel.setText(controller.getLocaliser().getString("showImportPrivateKeysPanel.noFileSelected"));
}
messageLabel1.setText(" ");
messageLabel2.setText(" ");
}
@Override
public void navigateAwayFromView() {
}
private void chooseFile(MultiBitButton callingButton) {
JFileChooser.setDefaultLocale(controller.getLocaliser().getLocale());
fileChooser = new JFileChooser();
fileChooser.setLocale(controller.getLocaliser().getLocale());
fileChooser.setDialogTitle(chooseFilenameButtonText);
adjustedFont = FontSizer.INSTANCE.getAdjustedDefaultFont();
if (adjustedFont != null) {
setFileChooserFont(new Container[] {fileChooser});
}
fileChooser.applyComponentOrientation(ComponentOrientation.getOrientation(controller.getLocaliser().getLocale()));
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.addChoosableFileFilter(multiBitFileChooser);
fileChooser.addChoosableFileFilter(myWalletPlainFileChooser);
fileChooser.addChoosableFileFilter(myWalletEncryptedFileChooser);
fileChooser.setAcceptAllFileFilterUsed(false);
fileChooser.setFileFilter(multiBitFileChooser);
if (outputFilename != null && !"".equals(outputFilename)) {
fileChooser.setCurrentDirectory(new File(outputFilename));
fileChooser.setSelectedFile(new File(outputFilename));
} else {
if (this.bitcoinController.getModel().getActiveWalletFilename() != null) {
fileChooser.setCurrentDirectory(new File(this.bitcoinController.getModel().getActiveWalletFilename()));
}
String defaultFileName = fileChooser.getCurrentDirectory().getAbsoluteFile() + File.separator
+ controller.getLocaliser().getString("saveWalletAsView.untitled") + "."
+ BitcoinModel.PRIVATE_KEY_FILE_EXTENSION;
fileChooser.setSelectedFile(new File(defaultFileName));
}
try {
callingButton.setEnabled(false);
mainFrame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
fileChooser.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
int returnVal = fileChooser.showOpenDialog(mainFrame);
if (returnVal == JFileChooser.APPROVE_OPTION) {
numberOfKeysLabel.setText(" ");
replayDateLabel.setText(" ");
passwordField1.setText("");
File file = fileChooser.getSelectedFile();
if (file != null) {
outputFilename = file.getAbsolutePath();
outputFilenameLabel.setText(outputFilename);
if (multiBitFileChooser.accept(file)) {
try {
String firstLine = readFirstLineInFile(file);
if (firstLine != null && firstLine.startsWith(encrypterDecrypter.getOpenSSLMagicText())) {
// File is encrypted.
enableImportFilePasswordPanel(true);
passwordField1.requestFocusInWindow();
} else {
// File is not encrypted.
enableImportFilePasswordPanel(false);
readInImportFileAndUpdateDetails();
}
} catch (IOException e) {
setMessageText1(controller.getLocaliser().getString(
"importPrivateKeysSubmitAction.privateKeysImportFailure",
new Object[] { e.getClass().getName() + " " + e.getMessage() }));
} catch (KeyCrypterException e) {
// TODO User may not have entered a password yet so
// password incorrect is ok at this stage.
// Other errors indicate a more general problem with
// the
// import.
setMessageText1(controller.getLocaliser().getString(
"importPrivateKeysSubmitAction.privateKeysImportFailure",
new Object[] { e.getClass().getName() + " " + e.getMessage() }));
}
} else if (myWalletEncryptedFileChooser.accept(file)) {
enableImportFilePasswordPanel(true);
passwordField1.requestFocusInWindow();
} else if (myWalletPlainFileChooser.accept(file)) {
// File is not encrypted.
enableImportFilePasswordPanel(false);
try {
readInImportFileAndUpdateDetails();
} catch (KeyCrypterException e) {
setMessageText1(controller.getLocaliser().getString(
"importPrivateKeysSubmitAction.privateKeysImportFailure",
new Object[] { e.getClass().getName() + " " + e.getMessage() }));
}
}
}
}
} finally {
mainFrame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
callingButton.setEnabled(true);
}
}
private void enableSecondPasswordPanel(boolean enablePanel) {
passwordField2.setEnabled(enablePanel);
passwordPromptLabel2.setEnabled(enablePanel);
passwordField2.setVisible(enablePanel);
passwordPromptLabel2.setVisible(enablePanel);
}
private void enableImportFilePasswordPanel(boolean enableImportFilePanel) {
if (enableImportFilePanel) {
// Enable the import file password panel.
passwordPromptLabel1.setEnabled(true);
passwordField1.setEnabled(true);
unlockButton.setEnabled(true);
passwordInfoLabel.setForeground(Color.BLACK);
} else {
// Disable the import file password panel.
passwordPromptLabel1.setEnabled(false);
passwordField1.setEnabled(false);
unlockButton.setEnabled(false);
passwordInfoLabel.setForeground(Color.GRAY);
}
}
private void enableWalletPassword(boolean enableWalletPassword) {
if (enableWalletPassword) {
// Enable the wallet password.
walletPasswordField.setEnabled(true);
walletPasswordPromptLabel.setEnabled(true);
} else {
// Disable the wallet password.
walletPasswordField.setEnabled(false);
walletPasswordPromptLabel.setEnabled(false);
}
}
/**
* Read in the import file and show the file details.
* @throws EncrypterDecrypterException
* @throws PrivateKeysHandlerException
*/
private void readInImportFileAndUpdateDetails() throws PrivateKeysHandlerException, KeyCrypterException {
// Update number of keys and earliest date.
try {
File file = new File(outputFilename);
if (multiBitFileChooser.accept(file)) {
// Read in contents of file.
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
PrivateKeysHandler privateKeysHandler = new PrivateKeysHandler(this.bitcoinController.getModel().getNetworkParameters());
Collection<PrivateKeyAndDate> privateKeyAndDates = privateKeysHandler.readInPrivateKeys(new File(outputFilename),
CharBuffer.wrap(passwordField1.getPassword()));
numberOfKeysLabel.setText("" + privateKeyAndDates.size());
Date replayDate = privateKeysHandler.calculateReplayDate(privateKeyAndDates, this.bitcoinController.getModel()
.getActiveWallet());
if (replayDate == null) {
replayDateLabel.setText(controller.getLocaliser().getString(
"showImportPrivateKeysPanel.thereWereMissingKeyDates"));
} else {
replayDateLabel.setText(DateFormat.getDateInstance(DateFormat.MEDIUM, controller.getLocaliser().getLocale())
.format(replayDate));
}
setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
} else if (myWalletEncryptedFileChooser.accept(file)) {
try {
String importFileContents = PrivateKeysHandler.readFile(file);
String mainPassword = new String(passwordField1.getPassword());
String secondPassword = new String(passwordField2.getPassword());
MyWallet wallet = new MyWallet(importFileContents, mainPassword);
boolean needSecondPassword = false;
if (wallet.isDoubleEncrypted()) {
if ("".equals(secondPassword)) {
needSecondPassword = true;
requestSecondPassword();
}
}
if (!needSecondPassword) {
wallet.setTemporySecondPassword(secondPassword);
int numberOfKeys = 0;
if (wallet.getBitcoinJWallet() != null && wallet.getBitcoinJWallet().getKeychain() != null) {
numberOfKeys = wallet.getBitcoinJWallet().getKeychainSize();
}
numberOfKeysLabel.setText("" + numberOfKeys);
replayDateLabel.setText(controller.getLocaliser().getString(
"showImportPrivateKeysPanel.thereWereMissingKeyDates"));
}
} catch (Exception e) {
throw new KeyCrypterException("Error Decrypting Wallet");
}
} else if (myWalletPlainFileChooser.accept(file)) {
try {
String importFileContents = PrivateKeysHandler.readFile(file);
MyWallet wallet = new MyWallet(importFileContents);
int numberOfKeys = 0;
if (wallet.getBitcoinJWallet() != null && wallet.getBitcoinJWallet().getKeychain() != null) {
numberOfKeys = wallet.getBitcoinJWallet().getKeychainSize();
}
numberOfKeysLabel.setText("" + numberOfKeys);
replayDateLabel.setText(controller.getLocaliser().getString(
"showImportPrivateKeysPanel.thereWereMissingKeyDates"));
} catch (Exception e) {
throw new KeyCrypterException("Error Opening Wallet");
}
}
} finally {
setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
}
public void requestSecondPassword() {
enableSecondPasswordPanel(true);
setMessageText1(controller.getLocaliser().getString("importPrivateKeysSubmitAction.enterTheSecondPassword"));
}
public String getOutputFilename() {
return outputFilename;
}
public void clearPasswords() {
walletPasswordField.setText("");
passwordField1.setText("");
if (passwordField2 != null) {
passwordField2.setText("");
}
}
public void setMessageText1(String message1) {
if (messageLabel1 != null) {
messageLabel1.setText(message1);
}
}
public String getMessageText1() {
if (messageLabel1 != null) {
return messageLabel1.getText();
} else {
return "";
}
}
public void setMessageText2(String message2) {
if (messageLabel2 != null) {
messageLabel2.setText(message2);
}
}
public String getMessageText2() {
if (messageLabel2 != null) {
return messageLabel2.getText();
} else {
return "";
}
}
private String readFirstLineInFile(File file) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(file));
return reader.readLine();
}
@Override
public Icon getViewIcon() {
return ImageLoader.createImageIcon(ImageLoader.IMPORT_PRIVATE_KEYS_ICON_FILE);
}
@Override
public String getViewTitle() {
return controller.getLocaliser().getString("showImportPrivateKeysAction.text");
}
@Override
public String getViewTooltip() {
return controller.getLocaliser().getString("showImportPrivateKeysAction.tooltip");
}
@Override
public View getViewId() {
return View.SHOW_IMPORT_PRIVATE_KEYS_VIEW;
}
// Used in testing.
public MultiBitButton getUnlockButton() {
return unlockButton;
}
public ImportPrivateKeysSubmitAction getImportPrivateKeysSubmitAction() {
return importPrivateKeysSubmitAction;
}
public void setOutputFilename(String outputFilename) {
this.outputFilename = outputFilename;
}
public void setImportFilePassword(CharSequence password) {
passwordField1.setText(password.toString());
}
public void setWalletPassword(CharSequence password) {
walletPasswordField.setText(password.toString());
}
public boolean isWalletPasswordFieldEnabled() {
return walletPasswordField.isEnabled();
}
@Override
public void walletBusyChange(boolean newWalletIsBusy) {
// Update the enable status of the action to match the wallet busy status.
if (this.bitcoinController.getModel().getActivePerWalletModelData().isBusy()) {
// Wallet is busy with another operation that may change the private keys - Action is disabled.
importPrivateKeysSubmitAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipText(controller.getLocaliser().getString("multiBitSubmitAction.walletIsBusy",
new Object[]{controller.getLocaliser().getString(this.bitcoinController.getModel().getActivePerWalletModelData().getBusyTaskKey())})));
importPrivateKeysSubmitAction.setEnabled(false);
} else {
// Enable unless wallet has been modified by another process.
if (!this.bitcoinController.getModel().getActivePerWalletModelData().isFilesHaveBeenChangedByAnotherProcess()) {
importPrivateKeysSubmitAction.putValue(Action.SHORT_DESCRIPTION, HelpContentsPanel.createTooltipText(controller.getLocaliser().getString("importPrivateKeysSubmitAction.tooltip")));
importPrivateKeysSubmitAction.setEnabled(true);
}
}
}
private void setFileChooserFont(Component[] comp) {
for (int x = 0; x < comp.length; x++) {
if (comp[x] instanceof Container)
setFileChooserFont(((Container) comp[x]).getComponents());
try {
comp[x].setFont(adjustedFont);
} catch (Exception e) {
}// do nothing
}
}
} | Remove blockchain.info wallet import.
| src/main/java/org/multibit/viewsystem/swing/view/panels/ImportPrivateKeysPanel.java | Remove blockchain.info wallet import. |
|
Java | mit | beb40eeea7603c8e9522a90402aee553c4af69d3 | 0 | NorthernNorth/bLR_droid | /*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.bluetoothlegatt;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import java.util.List;
import java.util.UUID;
/**
* Service for managing connection and data communication with a GATT server hosted on a
* given Bluetooth LE device.
*/
public class BluetoothLeService extends Service {
private final static String TAG = BluetoothLeService.class.getSimpleName();
private BluetoothManager mBluetoothManager;
private BluetoothAdapter mBluetoothAdapter;
private String mBluetoothDeviceAddress;
private BluetoothGatt mBluetoothGatt;
private int mConnectionState = STATE_DISCONNECTED;
private static final int STATE_DISCONNECTED = 0;
private static final int STATE_CONNECTING = 1;
private static final int STATE_CONNECTED = 2;
public final static String ACTION_GATT_CONNECTED =
"com.example.bluetooth.le.ACTION_GATT_CONNECTED";
public final static String ACTION_GATT_DISCONNECTED =
"com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";
public final static String ACTION_GATT_SERVICES_DISCOVERED =
"com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";
public final static String ACTION_DATA_AVAILABLE =
"com.example.bluetooth.le.ACTION_DATA_AVAILABLE";
public final static String ACTION_UARTTx_DATA_AVAILABLE =
"com.example.bluetooth.le.ACTION_UARTTx_DATA_AVAILABLE";
public final static String EXTRA_DATA =
"com.example.bluetooth.le.EXTRA_DATA";
//public final static UUID UUID_HEART_RATE_MEASUREMENT =
//UUID.fromString(SampleGattAttributes.HEART_RATE_MEASUREMENT);
// Implements callback methods for GATT events that the app cares about. For example,
// connection change and services discovered.
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
String intentAction;
if (newState == BluetoothProfile.STATE_CONNECTED) {
intentAction = ACTION_GATT_CONNECTED;
mConnectionState = STATE_CONNECTED;
broadcastUpdate(intentAction);
Log.i(TAG, "Connected to GATT server.");
// Attempts to discover services after successful connection.
Log.i(TAG, "Attempting to start service discovery:" +
mBluetoothGatt.discoverServices());
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
intentAction = ACTION_GATT_DISCONNECTED;
mConnectionState = STATE_DISCONNECTED;
Log.i(TAG, "Disconnected from GATT server.");
broadcastUpdate(intentAction);
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
} else {
Log.w(TAG, "onServicesDiscovered received: " + status);
}
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic,
int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
Log.d(TAG, "Characteristic read!!!!!");
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic) {
Log.d(TAG, "Characteristic changed!!!!!");
Log.d(TAG, characteristic.getUuid().toString());
//UARTTx
if (characteristic.getUuid().toString().equals("6e400002-b5a3-f393-e0a9-e50e24dcca9e")){
Log.d(TAG, "UARTTx changed!!!");
broadcastUpdate(ACTION_UARTTx_DATA_AVAILABLE, characteristic);
}
}
};
private void broadcastUpdate(final String action) {
final Intent intent = new Intent(action);
sendBroadcast(intent);
}
private void broadcastUpdate(final String action,
final BluetoothGattCharacteristic characteristic) {
Log.d(TAG, "LW1");
final Intent intent = new Intent(action);
Log.d(TAG, "LW2");
// This is special handling for the Heart Rate Measurement profile. Data parsing is
// carried out as per profile specifications:
// http://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.heart_rate_measurement.xml
// if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
// int flag = characteristic.getProperties();
// int format = -1;
// if ((flag & 0x01) != 0) {
// format = BluetoothGattCharacteristic.FORMAT_UINT16;
// Log.d(TAG, "Heart rate format UINT16.");
// } else {
// format = BluetoothGattCharacteristic.FORMAT_UINT8;
// Log.d(TAG, "Heart rate format UINT8.");
// }
// final int heartRate = characteristic.getIntValue(format, 1);
// Log.d(TAG, String.format("Received heart rate: %d", heartRate));
// intent.putExtra(EXTRA_DATA, String.valueOf(heartRate));
// } else {
// For all other profiles, writes the data formatted in HEX.
// final byte[] data = characteristic.getValue();
// if (data != null && data.length > 0) {
// final StringBuilder stringBuilder = new StringBuilder(data.length);
// for(byte byteChar : data)
// stringBuilder.append(String.format("%02X ", byteChar));
// intent.putExtra(EXTRA_DATA, new String(data) + "\n" + stringBuilder.toString());
// }
// }
final String data = characteristic.getStringValue(0);
intent.putExtra(EXTRA_DATA,data);
Log.d(TAG, "LW3");
sendBroadcast(intent);
Log.d(TAG, "LW4");
}
public class LocalBinder extends Binder {
BluetoothLeService getService() {
return BluetoothLeService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public boolean onUnbind(Intent intent) {
// After using a given device, you should make sure that BluetoothGatt.close() is called
// such that resources are cleaned up properly. In this particular example, close() is
// invoked when the UI is disconnected from the Service.
close();
return super.onUnbind(intent);
}
private final IBinder mBinder = new LocalBinder();
/**
* Initializes a reference to the local Bluetooth adapter.
*
* @return Return true if the initialization is successful.
*/
public boolean initialize() {
// For API level 18 and above, get a reference to BluetoothAdapter through
// BluetoothManager.
if (mBluetoothManager == null) {
mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
if (mBluetoothManager == null) {
Log.e(TAG, "Unable to initialize BluetoothManager.");
return false;
}
}
mBluetoothAdapter = mBluetoothManager.getAdapter();
if (mBluetoothAdapter == null) {
Log.e(TAG, "Unable to obtain a BluetoothAdapter.");
return false;
}
return true;
}
/**
* Connects to the GATT server hosted on the Bluetooth LE device.
*
* @param address The device address of the destination device.
*
* @return Return true if the connection is initiated successfully. The connection result
* is reported asynchronously through the
* {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
* callback.
*/
public boolean connect(final String address) {
if (mBluetoothAdapter == null || address == null) {
Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
return false;
}
// Previously connected device. Try to reconnect.
if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress)
&& mBluetoothGatt != null) {
Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.");
if (mBluetoothGatt.connect()) {
mConnectionState = STATE_CONNECTING;
return true;
} else {
return false;
}
}
final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
if (device == null) {
Log.w(TAG, "Device not found. Unable to connect.");
return false;
}
// We want to directly connect to the device, so we are setting the autoConnect
// parameter to false.
mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
Log.d(TAG, "Trying to create a new connection.");
mBluetoothDeviceAddress = address;
mConnectionState = STATE_CONNECTING;
return true;
}
/**
* Disconnects an existing connection or cancel a pending connection. The disconnection result
* is reported asynchronously through the
* {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
* callback.
*/
public void disconnect() {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.disconnect();
}
/**
* After using a given BLE device, the app must call this method to ensure resources are
* released properly.
*/
public void close() {
if (mBluetoothGatt == null) {
return;
}
mBluetoothGatt.close();
mBluetoothGatt = null;
}
/**
* Request a read on a given {@code BluetoothGattCharacteristic}. The read result is reported
* asynchronously through the {@code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)}
* callback.
*
* @param characteristic The characteristic to read from.
*/
public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.readCharacteristic(characteristic);
}
public void setLocalCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enabled){
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.d(TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
}
/**
* Enables or disables notification on a give characteristic.
*
* @param characteristic Characteristic to act on.
* @param enabled If true, enable notification. False otherwise.
*/
public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
boolean enabled, boolean indication) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.d(TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
// This is specific to Heart Rate Measurement.
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
if (descriptor != null){
Log.d(TAG, "Descriptor not null");
if (enabled){
if (indication){
descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
Log.d(TAG, "Descriptor Indication");
}
else {
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
Log.d(TAG, "Descriptor Notification");
}
}
else {
descriptor.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
}
// Log.d(TAG,descriptor.getUuid().toString());
// Log.d(TAG,""+descriptor.getPermissions());
//BluetoothGattDescriptor descriptor = new BluetoothGattDescriptor(UUID.nameUUIDFromBytes(BLEUUID.PIN_CHARACTERISTIC_CONFIG_DESCRIPTOR.getBytes()), BluetoothGattDescriptor.PERMISSION_WRITE_SIGNED);
// final byte[] data = descriptor.getValue();
// final StringBuilder stringBuilder = new StringBuilder(data.length);
// for(byte byteChar : data)
// stringBuilder.append(String.format("%02X ", byteChar));
// Log.d(TAG,stringBuilder.toString());
// if (descriptor.getCharacteristic()!=null){
// Log.d(TAG,"descriptor chara not null");
// }
// else Log.d(TAG,"des chara null");
boolean success = mBluetoothGatt.writeDescriptor(descriptor);
if (success){
Log.d(TAG,"success");
}
else Log.d(TAG,"unsuccess");
}
}
/**
* Retrieves a list of supported GATT services on the connected device. This should be
* invoked only after {@code BluetoothGatt#discoverServices()} completes successfully.
*
* @return A {@code List} of supported services.
*/
public List<BluetoothGattService> getSupportedGattServices() {
if (mBluetoothGatt == null) return null;
return mBluetoothGatt.getServices();
}
public BluetoothGattService obtainService (String uuid){
return mBluetoothGatt.getService(UUID.fromString(uuid));
}
}
| java/com/example/android/bluetoothlegatt/BluetoothLeService.java | /*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.bluetoothlegatt;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import java.util.List;
import java.util.UUID;
/**
* Service for managing connection and data communication with a GATT server hosted on a
* given Bluetooth LE device.
*/
public class BluetoothLeService extends Service {
private final static String TAG = BluetoothLeService.class.getSimpleName();
private BluetoothManager mBluetoothManager;
private BluetoothAdapter mBluetoothAdapter;
private String mBluetoothDeviceAddress;
private BluetoothGatt mBluetoothGatt;
private int mConnectionState = STATE_DISCONNECTED;
private static final int STATE_DISCONNECTED = 0;
private static final int STATE_CONNECTING = 1;
private static final int STATE_CONNECTED = 2;
public final static String ACTION_GATT_CONNECTED =
"com.example.bluetooth.le.ACTION_GATT_CONNECTED";
public final static String ACTION_GATT_DISCONNECTED =
"com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";
public final static String ACTION_GATT_SERVICES_DISCOVERED =
"com.example.bluetooth.le.ACTION_GATT_SERVICES_DISCOVERED";
public final static String ACTION_DATA_AVAILABLE =
"com.example.bluetooth.le.ACTION_DATA_AVAILABLE";
public final static String ACTION_UARTTx_DATA_AVAILABLE =
"com.example.bluetooth.le.ACTION_UARTTx_DATA_AVAILABLE";
public final static String EXTRA_DATA =
"com.example.bluetooth.le.EXTRA_DATA";
//public final static UUID UUID_HEART_RATE_MEASUREMENT =
//UUID.fromString(SampleGattAttributes.HEART_RATE_MEASUREMENT);
// Implements callback methods for GATT events that the app cares about. For example,
// connection change and services discovered.
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
String intentAction;
if (newState == BluetoothProfile.STATE_CONNECTED) {
intentAction = ACTION_GATT_CONNECTED;
mConnectionState = STATE_CONNECTED;
broadcastUpdate(intentAction);
Log.i(TAG, "Connected to GATT server.");
// Attempts to discover services after successful connection.
Log.i(TAG, "Attempting to start service discovery:" +
mBluetoothGatt.discoverServices());
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
intentAction = ACTION_GATT_DISCONNECTED;
mConnectionState = STATE_DISCONNECTED;
Log.i(TAG, "Disconnected from GATT server.");
broadcastUpdate(intentAction);
}
}
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
broadcastUpdate(ACTION_GATT_SERVICES_DISCOVERED);
} else {
Log.w(TAG, "onServicesDiscovered received: " + status);
}
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic,
int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
Log.d(TAG, "Characteristic read!!!!!");
broadcastUpdate(ACTION_DATA_AVAILABLE, characteristic);
}
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic) {
Log.d(TAG, "Characteristic changed!!!!!");
Log.d(TAG, characteristic.getUuid().toString());
//UARTTx
if (characteristic.getUuid().toString().equals("6e400002-b5a3-f393-e0a9-e50e24dcca9e")){
Log.d(TAG, "UARTTx changed!!!");
broadcastUpdate(ACTION_UARTTx_DATA_AVAILABLE, characteristic);
}
}
};
private void broadcastUpdate(final String action) {
final Intent intent = new Intent(action);
sendBroadcast(intent);
}
private void broadcastUpdate(final String action,
final BluetoothGattCharacteristic characteristic) {
Log.d(TAG, "LW1");
final Intent intent = new Intent(action);
Log.d(TAG, "LW2");
// This is special handling for the Heart Rate Measurement profile. Data parsing is
// carried out as per profile specifications:
// http://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.heart_rate_measurement.xml
// if (UUID_HEART_RATE_MEASUREMENT.equals(characteristic.getUuid())) {
// int flag = characteristic.getProperties();
// int format = -1;
// if ((flag & 0x01) != 0) {
// format = BluetoothGattCharacteristic.FORMAT_UINT16;
// Log.d(TAG, "Heart rate format UINT16.");
// } else {
// format = BluetoothGattCharacteristic.FORMAT_UINT8;
// Log.d(TAG, "Heart rate format UINT8.");
// }
// final int heartRate = characteristic.getIntValue(format, 1);
// Log.d(TAG, String.format("Received heart rate: %d", heartRate));
// intent.putExtra(EXTRA_DATA, String.valueOf(heartRate));
// } else {
// For all other profiles, writes the data formatted in HEX.
final byte[] data = characteristic.getValue();
if (data != null && data.length > 0) {
final StringBuilder stringBuilder = new StringBuilder(data.length);
for(byte byteChar : data)
stringBuilder.append(String.format("%02X ", byteChar));
intent.putExtra(EXTRA_DATA, new String(data) + "\n" + stringBuilder.toString());
}
// }
Log.d(TAG, "LW3");
sendBroadcast(intent);
Log.d(TAG, "LW4");
}
public class LocalBinder extends Binder {
BluetoothLeService getService() {
return BluetoothLeService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public boolean onUnbind(Intent intent) {
// After using a given device, you should make sure that BluetoothGatt.close() is called
// such that resources are cleaned up properly. In this particular example, close() is
// invoked when the UI is disconnected from the Service.
close();
return super.onUnbind(intent);
}
private final IBinder mBinder = new LocalBinder();
/**
* Initializes a reference to the local Bluetooth adapter.
*
* @return Return true if the initialization is successful.
*/
public boolean initialize() {
// For API level 18 and above, get a reference to BluetoothAdapter through
// BluetoothManager.
if (mBluetoothManager == null) {
mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
if (mBluetoothManager == null) {
Log.e(TAG, "Unable to initialize BluetoothManager.");
return false;
}
}
mBluetoothAdapter = mBluetoothManager.getAdapter();
if (mBluetoothAdapter == null) {
Log.e(TAG, "Unable to obtain a BluetoothAdapter.");
return false;
}
return true;
}
/**
* Connects to the GATT server hosted on the Bluetooth LE device.
*
* @param address The device address of the destination device.
*
* @return Return true if the connection is initiated successfully. The connection result
* is reported asynchronously through the
* {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
* callback.
*/
public boolean connect(final String address) {
if (mBluetoothAdapter == null || address == null) {
Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
return false;
}
// Previously connected device. Try to reconnect.
if (mBluetoothDeviceAddress != null && address.equals(mBluetoothDeviceAddress)
&& mBluetoothGatt != null) {
Log.d(TAG, "Trying to use an existing mBluetoothGatt for connection.");
if (mBluetoothGatt.connect()) {
mConnectionState = STATE_CONNECTING;
return true;
} else {
return false;
}
}
final BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
if (device == null) {
Log.w(TAG, "Device not found. Unable to connect.");
return false;
}
// We want to directly connect to the device, so we are setting the autoConnect
// parameter to false.
mBluetoothGatt = device.connectGatt(this, false, mGattCallback);
Log.d(TAG, "Trying to create a new connection.");
mBluetoothDeviceAddress = address;
mConnectionState = STATE_CONNECTING;
return true;
}
/**
* Disconnects an existing connection or cancel a pending connection. The disconnection result
* is reported asynchronously through the
* {@code BluetoothGattCallback#onConnectionStateChange(android.bluetooth.BluetoothGatt, int, int)}
* callback.
*/
public void disconnect() {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.disconnect();
}
/**
* After using a given BLE device, the app must call this method to ensure resources are
* released properly.
*/
public void close() {
if (mBluetoothGatt == null) {
return;
}
mBluetoothGatt.close();
mBluetoothGatt = null;
}
/**
* Request a read on a given {@code BluetoothGattCharacteristic}. The read result is reported
* asynchronously through the {@code BluetoothGattCallback#onCharacteristicRead(android.bluetooth.BluetoothGatt, android.bluetooth.BluetoothGattCharacteristic, int)}
* callback.
*
* @param characteristic The characteristic to read from.
*/
public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.readCharacteristic(characteristic);
}
public void setLocalCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enabled){
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.d(TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
}
/**
* Enables or disables notification on a give characteristic.
*
* @param characteristic Characteristic to act on.
* @param enabled If true, enable notification. False otherwise.
*/
public void setCharacteristicNotification(BluetoothGattCharacteristic characteristic,
boolean enabled, boolean indication) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.d(TAG, "BluetoothAdapter not initialized");
return;
}
mBluetoothGatt.setCharacteristicNotification(characteristic, enabled);
// This is specific to Heart Rate Measurement.
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(
UUID.fromString(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG));
if (descriptor != null){
Log.d(TAG, "Descriptor not null");
if (enabled){
if (indication){
descriptor.setValue(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE);
Log.d(TAG, "Descriptor Indication");
}
else {
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
Log.d(TAG, "Descriptor Notification");
}
}
else {
descriptor.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
}
// Log.d(TAG,descriptor.getUuid().toString());
// Log.d(TAG,""+descriptor.getPermissions());
//BluetoothGattDescriptor descriptor = new BluetoothGattDescriptor(UUID.nameUUIDFromBytes(BLEUUID.PIN_CHARACTERISTIC_CONFIG_DESCRIPTOR.getBytes()), BluetoothGattDescriptor.PERMISSION_WRITE_SIGNED);
// final byte[] data = descriptor.getValue();
// final StringBuilder stringBuilder = new StringBuilder(data.length);
// for(byte byteChar : data)
// stringBuilder.append(String.format("%02X ", byteChar));
// Log.d(TAG,stringBuilder.toString());
// if (descriptor.getCharacteristic()!=null){
// Log.d(TAG,"descriptor chara not null");
// }
// else Log.d(TAG,"des chara null");
boolean success = mBluetoothGatt.writeDescriptor(descriptor);
if (success){
Log.d(TAG,"success");
}
else Log.d(TAG,"unsuccess");
}
}
/**
* Retrieves a list of supported GATT services on the connected device. This should be
* invoked only after {@code BluetoothGatt#discoverServices()} completes successfully.
*
* @return A {@code List} of supported services.
*/
public List<BluetoothGattService> getSupportedGattServices() {
if (mBluetoothGatt == null) return null;
return mBluetoothGatt.getServices();
}
public BluetoothGattService obtainService (String uuid){
return mBluetoothGatt.getService(UUID.fromString(uuid));
}
}
| UART data field working
| java/com/example/android/bluetoothlegatt/BluetoothLeService.java | UART data field working |
|
Java | mit | c78931829e54c7d3fb00ba9b7427ca92b1655f5f | 0 | MikeLydeamore/ItsRainingFood | package com.insane.itsrainingfood;
import java.io.File;
import net.minecraftforge.common.config.Configuration;
public class Config {
public static final String categoryGeneral="categoryGeneral";
public static int configTicks;
public static boolean soundEnabled;
public static void doConfig(File file)
{
Configuration config = new Configuration(file);
config.load();
configTicks = config.getInt("ticksForFood", categoryGeneral, 160, 1, Integer.MAX_VALUE, "Number of ticks to restore food");
soundEnabled = config.get(categoryGeneral, "soundEnabled", true).getBoolean();
if (config.hasChanged())
config.save();
}
}
| src/main/java/com/insane/itsrainingfood/Config.java | package com.insane.itsrainingfood;
import java.io.File;
import net.minecraftforge.common.config.Configuration;
public class Config {
public static final String categoryGeneral="categoryGeneral";
public static int configTicks;
public static boolean soundEnabled;
public static void doConfig(File file)
{
Configuration config = new Configuration(file);
config.load();
configTicks = config.get(categoryGeneral, "ticksForFood", 160, "Number of ticks to restore food").getInt();
soundEnabled = config.get(categoryGeneral, "soundEnabled", true).getBoolean();
if (config.hasChanged())
config.save();
}
}
| Fixed config allowing invalid values
Fixed ticksForFood allowing values less than one which could result in crashes | src/main/java/com/insane/itsrainingfood/Config.java | Fixed config allowing invalid values |
|
Java | mpl-2.0 | 6087f99188b26201f7698c187d95bfab1e205f1f | 0 | AlexTrotsenko/rhino,tejassaoji/RhinoCoarseTainting,tntim96/rhino-apigee,rasmuserik/rhino,tntim96/rhino-apigee,Pilarbrist/rhino,ashwinrayaprolu1984/rhino,tejassaoji/RhinoCoarseTainting,sam/htmlunit-rhino-fork,swannodette/rhino,tntim96/rhino-apigee,sam/htmlunit-rhino-fork,sam/htmlunit-rhino-fork,sainaen/rhino,qhanam/rhino,swannodette/rhino,Angelfirenze/rhino,lv7777/egit_test,Angelfirenze/rhino,Angelfirenze/rhino,Pilarbrist/rhino,InstantWebP2P/rhino-android,tuchida/rhino,Angelfirenze/rhino,ashwinrayaprolu1984/rhino,Distrotech/rhino,tntim96/rhino-jscover-repackaged,rasmuserik/rhino,AlexTrotsenko/rhino,jsdoc3/rhino,Pilarbrist/rhino,lv7777/egit_test,lv7777/egit_test,lv7777/egit_test,qhanam/rhino,qhanam/rhino,Angelfirenze/rhino,qhanam/rhino,swannodette/rhino,Distrotech/rhino,sainaen/rhino,tntim96/rhino-jscover,tuchida/rhino,tntim96/htmlunit-rhino-fork,ashwinrayaprolu1984/rhino,AlexTrotsenko/rhino,Angelfirenze/rhino,lv7777/egit_test,Pilarbrist/rhino,sam/htmlunit-rhino-fork,sam/htmlunit-rhino-fork,sainaen/rhino,tuchida/rhino,AlexTrotsenko/rhino,sam/htmlunit-rhino-fork,Pilarbrist/rhino,tuchida/rhino,sainaen/rhino,AlexTrotsenko/rhino,Angelfirenze/rhino,jsdoc3/rhino,ashwinrayaprolu1984/rhino,swannodette/rhino,Pilarbrist/rhino,AlexTrotsenko/rhino,InstantWebP2P/rhino-android,Pilarbrist/rhino,ashwinrayaprolu1984/rhino,lv7777/egit_test,lv7777/egit_test,tejassaoji/RhinoCoarseTainting,swannodette/rhino,swannodette/rhino,tntim96/rhino-jscover,sainaen/rhino,sainaen/rhino,sainaen/rhino,tuchida/rhino,tuchida/rhino,tejassaoji/RhinoCoarseTainting,tejassaoji/RhinoCoarseTainting,tejassaoji/RhinoCoarseTainting,ashwinrayaprolu1984/rhino,tuchida/rhino,tejassaoji/RhinoCoarseTainting,ashwinrayaprolu1984/rhino,tntim96/htmlunit-rhino-fork,sam/htmlunit-rhino-fork,swannodette/rhino,tntim96/rhino-jscover-repackaged,jsdoc3/rhino,AlexTrotsenko/rhino | /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1997-1999
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Norris Boyd
* Mike McCabe
* Igor Bukanov
*
* Alternatively, the contents of this file may be used under the terms of
* the GNU General Public License Version 2 or later (the "GPL"), in which
* case the provisions of the GPL are applicable instead of those above. If
* you wish to allow use of your version of this file only under the terms of
* the GPL and not to allow others to use your version of this file under the
* MPL, indicate your decision by deleting the provisions above and replacing
* them with the notice and other provisions required by the GPL. If you do
* not delete the provisions above, a recipient may use your version of this
* file under either the MPL or the GPL.
*
* ***** END LICENSE BLOCK ***** */
package org.mozilla.javascript;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* This class implements the Array native object.
* @author Norris Boyd
* @author Mike McCabe
*/
public class NativeArray extends IdScriptableObject
{
static final long serialVersionUID = 7331366857676127338L;
/*
* Optimization possibilities and open issues:
* - Long vs. double schizophrenia. I suspect it might be better
* to use double throughout.
*
* - Functions that need a new Array call "new Array" in the
* current scope rather than using a hardwired constructor;
* "Array" could be redefined. It turns out that js calls the
* equivalent of "new Array" in the current scope, except that it
* always gets at least an object back, even when Array == null.
*/
private static final Object ARRAY_TAG = "Array";
private static final Integer NEGATIVE_ONE = Integer.valueOf(-1);
static void init(Scriptable scope, boolean sealed)
{
NativeArray obj = new NativeArray(0);
obj.exportAsJSClass(MAX_PROTOTYPE_ID, scope, sealed);
}
static int getMaximumInitialCapacity() {
return maximumInitialCapacity;
}
static void setMaximumInitialCapacity(int maximumInitialCapacity) {
NativeArray.maximumInitialCapacity = maximumInitialCapacity;
}
public NativeArray(long lengthArg)
{
denseOnly = lengthArg <= maximumInitialCapacity;
if (denseOnly) {
int intLength = (int) lengthArg;
if (intLength < DEFAULT_INITIAL_CAPACITY)
intLength = DEFAULT_INITIAL_CAPACITY;
dense = new Object[intLength];
Arrays.fill(dense, Scriptable.NOT_FOUND);
}
length = lengthArg;
}
public NativeArray(Object[] array)
{
denseOnly = true;
dense = array;
length = array.length;
}
@Override
public String getClassName()
{
return "Array";
}
private static final int
Id_length = 1,
MAX_INSTANCE_ID = 1;
@Override
protected int getMaxInstanceId()
{
return MAX_INSTANCE_ID;
}
@Override
protected int findInstanceIdInfo(String s)
{
if (s.equals("length")) {
return instanceIdInfo(DONTENUM | PERMANENT, Id_length);
}
return super.findInstanceIdInfo(s);
}
@Override
protected String getInstanceIdName(int id)
{
if (id == Id_length) { return "length"; }
return super.getInstanceIdName(id);
}
@Override
protected Object getInstanceIdValue(int id)
{
if (id == Id_length) {
return ScriptRuntime.wrapNumber(length);
}
return super.getInstanceIdValue(id);
}
@Override
protected void setInstanceIdValue(int id, Object value)
{
if (id == Id_length) {
setLength(value); return;
}
super.setInstanceIdValue(id, value);
}
@Override
protected void fillConstructorProperties(IdFunctionObject ctor)
{
addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_join,
"join", 2);
addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_reverse,
"reverse", 1);
addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_sort,
"sort", 2);
addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_push,
"push", 2);
addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_pop,
"pop", 2);
addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_shift,
"shift", 2);
addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_unshift,
"unshift", 2);
addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_splice,
"splice", 2);
addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_concat,
"concat", 2);
addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_slice,
"slice", 2);
addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_indexOf,
"indexOf", 2);
addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_lastIndexOf,
"lastIndexOf", 2);
addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_every,
"every", 2);
addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_filter,
"filter", 2);
addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_forEach,
"forEach", 2);
addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_map,
"map", 2);
addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_some,
"some", 2);
addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_reduce,
"reduce", 2);
addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_reduceRight,
"reduceRight", 2);
super.fillConstructorProperties(ctor);
}
@Override
protected void initPrototypeId(int id)
{
String s;
int arity;
switch (id) {
case Id_constructor: arity=1; s="constructor"; break;
case Id_toString: arity=0; s="toString"; break;
case Id_toLocaleString: arity=1; s="toLocaleString"; break;
case Id_toSource: arity=0; s="toSource"; break;
case Id_join: arity=1; s="join"; break;
case Id_reverse: arity=0; s="reverse"; break;
case Id_sort: arity=1; s="sort"; break;
case Id_push: arity=1; s="push"; break;
case Id_pop: arity=1; s="pop"; break;
case Id_shift: arity=1; s="shift"; break;
case Id_unshift: arity=1; s="unshift"; break;
case Id_splice: arity=1; s="splice"; break;
case Id_concat: arity=1; s="concat"; break;
case Id_slice: arity=1; s="slice"; break;
case Id_indexOf: arity=1; s="indexOf"; break;
case Id_lastIndexOf: arity=1; s="lastIndexOf"; break;
case Id_every: arity=1; s="every"; break;
case Id_filter: arity=1; s="filter"; break;
case Id_forEach: arity=1; s="forEach"; break;
case Id_map: arity=1; s="map"; break;
case Id_some: arity=1; s="some"; break;
case Id_reduce: arity=1; s="reduce"; break;
case Id_reduceRight: arity=1; s="reduceRight"; break;
default: throw new IllegalArgumentException(String.valueOf(id));
}
initPrototypeMethod(ARRAY_TAG, id, s, arity);
}
@Override
public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
{
if (!f.hasTag(ARRAY_TAG)) {
return super.execIdCall(f, cx, scope, thisObj, args);
}
int id = f.methodId();
again:
for (;;) {
switch (id) {
case ConstructorId_join:
case ConstructorId_reverse:
case ConstructorId_sort:
case ConstructorId_push:
case ConstructorId_pop:
case ConstructorId_shift:
case ConstructorId_unshift:
case ConstructorId_splice:
case ConstructorId_concat:
case ConstructorId_slice:
case ConstructorId_indexOf:
case ConstructorId_lastIndexOf:
case ConstructorId_every:
case ConstructorId_filter:
case ConstructorId_forEach:
case ConstructorId_map:
case ConstructorId_some:
case ConstructorId_reduce:
case ConstructorId_reduceRight: {
if (args.length > 0) {
thisObj = ScriptRuntime.toObject(scope, args[0]);
Object[] newArgs = new Object[args.length-1];
for (int i=0; i < newArgs.length; i++)
newArgs[i] = args[i+1];
args = newArgs;
}
id = -id;
continue again;
}
case Id_constructor: {
boolean inNewExpr = (thisObj == null);
if (!inNewExpr) {
// IdFunctionObject.construct will set up parent, proto
return f.construct(cx, scope, args);
}
return jsConstructor(cx, scope, args);
}
case Id_toString:
return toStringHelper(cx, scope, thisObj,
cx.hasFeature(Context.FEATURE_TO_STRING_AS_SOURCE), false);
case Id_toLocaleString:
return toStringHelper(cx, scope, thisObj, false, true);
case Id_toSource:
return toStringHelper(cx, scope, thisObj, true, false);
case Id_join:
return js_join(cx, thisObj, args);
case Id_reverse:
return js_reverse(cx, thisObj, args);
case Id_sort:
return js_sort(cx, scope, thisObj, args);
case Id_push:
return js_push(cx, thisObj, args);
case Id_pop:
return js_pop(cx, thisObj, args);
case Id_shift:
return js_shift(cx, thisObj, args);
case Id_unshift:
return js_unshift(cx, thisObj, args);
case Id_splice:
return js_splice(cx, scope, thisObj, args);
case Id_concat:
return js_concat(cx, scope, thisObj, args);
case Id_slice:
return js_slice(cx, thisObj, args);
case Id_indexOf:
return indexOfHelper(cx, thisObj, args, false);
case Id_lastIndexOf:
return indexOfHelper(cx, thisObj, args, true);
case Id_every:
case Id_filter:
case Id_forEach:
case Id_map:
case Id_some:
return iterativeMethod(cx, id, scope, thisObj, args);
case Id_reduce:
case Id_reduceRight:
return reduceMethod(cx, id, scope, thisObj, args);
}
throw new IllegalArgumentException(String.valueOf(id));
}
}
@Override
public Object get(int index, Scriptable start)
{
if (!denseOnly && isGetterOrSetter(null, index, false))
return super.get(index, start);
if (dense != null && 0 <= index && index < dense.length)
return dense[index];
return super.get(index, start);
}
@Override
public boolean has(int index, Scriptable start)
{
if (!denseOnly && isGetterOrSetter(null, index, false))
return super.has(index, start);
if (dense != null && 0 <= index && index < dense.length)
return dense[index] != NOT_FOUND;
return super.has(index, start);
}
// if id is an array index (ECMA 15.4.0), return the number,
// otherwise return -1L
private static long toArrayIndex(String id)
{
double d = ScriptRuntime.toNumber(id);
if (d == d) {
long index = ScriptRuntime.toUint32(d);
if (index == d && index != 4294967295L) {
// Assume that ScriptRuntime.toString(index) is the same
// as java.lang.Long.toString(index) for long
if (Long.toString(index).equals(id)) {
return index;
}
}
}
return -1;
}
@Override
public void put(String id, Scriptable start, Object value)
{
super.put(id, start, value);
if (start == this) {
// If the object is sealed, super will throw exception
long index = toArrayIndex(id);
if (index >= length) {
length = index + 1;
denseOnly = false;
}
}
}
private boolean ensureCapacity(int capacity)
{
if (capacity > dense.length) {
if (capacity > MAX_PRE_GROW_SIZE) {
denseOnly = false;
return false;
}
capacity = Math.max(capacity, (int)(dense.length * GROW_FACTOR));
Object[] newDense = new Object[capacity];
System.arraycopy(dense, 0, newDense, 0, dense.length);
Arrays.fill(newDense, dense.length, newDense.length,
Scriptable.NOT_FOUND);
dense = newDense;
}
return true;
}
@Override
public void put(int index, Scriptable start, Object value)
{
if (start == this && !isSealed() && dense != null && 0 <= index &&
(denseOnly || !isGetterOrSetter(null, index, true)))
{
if (index < dense.length) {
dense[index] = value;
if (this.length <= index)
this.length = (long)index + 1;
return;
} else if (denseOnly && index < dense.length * GROW_FACTOR &&
ensureCapacity(index+1))
{
dense[index] = value;
this.length = (long)index + 1;
return;
} else {
denseOnly = false;
}
}
super.put(index, start, value);
if (start == this) {
// only set the array length if given an array index (ECMA 15.4.0)
if (this.length <= index) {
// avoid overflowing index!
this.length = (long)index + 1;
}
}
}
@Override
public void delete(int index)
{
if (dense != null && 0 <= index && index < dense.length &&
!isSealed() && (denseOnly || !isGetterOrSetter(null, index, true)))
{
dense[index] = NOT_FOUND;
} else {
super.delete(index);
}
}
@Override
public Object[] getIds()
{
Object[] superIds = super.getIds();
if (dense == null) { return superIds; }
int N = dense.length;
long currentLength = length;
if (N > currentLength) {
N = (int)currentLength;
}
if (N == 0) { return superIds; }
int superLength = superIds.length;
Object[] ids = new Object[N + superLength];
int presentCount = 0;
for (int i = 0; i != N; ++i) {
// Replace existing elements by their indexes
if (dense[i] != NOT_FOUND) {
ids[presentCount] = Integer.valueOf(i);
++presentCount;
}
}
if (presentCount != N) {
// dense contains deleted elems, need to shrink the result
Object[] tmp = new Object[presentCount + superLength];
System.arraycopy(ids, 0, tmp, 0, presentCount);
ids = tmp;
}
System.arraycopy(superIds, 0, ids, presentCount, superLength);
return ids;
}
@Override
public Object[] getAllIds()
{
Set<Object> allIds = new LinkedHashSet<Object>(
Arrays.asList(this.getIds()));
allIds.addAll(Arrays.asList(super.getAllIds()));
return allIds.toArray();
}
@Override
public Object getDefaultValue(Class<?> hint)
{
if (hint == ScriptRuntime.NumberClass) {
Context cx = Context.getContext();
if (cx.getLanguageVersion() == Context.VERSION_1_2)
return Long.valueOf(length);
}
return super.getDefaultValue(hint);
}
/**
* See ECMA 15.4.1,2
*/
private static Object jsConstructor(Context cx, Scriptable scope,
Object[] args)
{
if (args.length == 0)
return new NativeArray(0);
// Only use 1 arg as first element for version 1.2; for
// any other version (including 1.3) follow ECMA and use it as
// a length.
if (cx.getLanguageVersion() == Context.VERSION_1_2) {
return new NativeArray(args);
} else {
Object arg0 = args[0];
if (args.length > 1 || !(arg0 instanceof Number)) {
return new NativeArray(args);
} else {
long len = ScriptRuntime.toUint32(arg0);
if (len != ((Number)arg0).doubleValue())
throw Context.reportRuntimeError0("msg.arraylength.bad");
return new NativeArray(len);
}
}
}
public long getLength() {
return length;
}
/** @deprecated Use {@link #getLength()} instead. */
public long jsGet_length() {
return getLength();
}
/**
* Change the value of the internal flag that determines whether all
* storage is handed by a dense backing array rather than an associative
* store.
* @param denseOnly new value for denseOnly flag
* @throws IllegalArgumentException if an attempt is made to enable
* denseOnly after it was disabled; NativeArray code is not written
* to handle switching back to a dense representation
*/
void setDenseOnly(boolean denseOnly) {
if (denseOnly && !this.denseOnly)
throw new IllegalArgumentException();
this.denseOnly = denseOnly;
}
private void setLength(Object val) {
/* XXX do we satisfy this?
* 15.4.5.1 [[Put]](P, V):
* 1. Call the [[CanPut]] method of A with name P.
* 2. If Result(1) is false, return.
* ?
*/
double d = ScriptRuntime.toNumber(val);
long longVal = ScriptRuntime.toUint32(d);
if (longVal != d)
throw Context.reportRuntimeError0("msg.arraylength.bad");
if (denseOnly) {
if (longVal < length) {
// downcast okay because denseOnly
Arrays.fill(dense, (int) longVal, dense.length, NOT_FOUND);
length = longVal;
return;
} else if (longVal < MAX_PRE_GROW_SIZE &&
longVal < (length * GROW_FACTOR) &&
ensureCapacity((int)longVal))
{
length = longVal;
return;
} else {
denseOnly = false;
}
}
if (longVal < length) {
// remove all properties between longVal and length
if (length - longVal > 0x1000) {
// assume that the representation is sparse
Object[] e = getIds(); // will only find in object itself
for (int i=0; i < e.length; i++) {
Object id = e[i];
if (id instanceof String) {
// > MAXINT will appear as string
String strId = (String)id;
long index = toArrayIndex(strId);
if (index >= longVal)
delete(strId);
} else {
int index = ((Integer)id).intValue();
if (index >= longVal)
delete(index);
}
}
} else {
// assume a dense representation
for (long i = longVal; i < length; i++) {
deleteElem(this, i);
}
}
}
length = longVal;
}
/* Support for generic Array-ish objects. Most of the Array
* functions try to be generic; anything that has a length
* property is assumed to be an array.
* getLengthProperty returns 0 if obj does not have the length property
* or its value is not convertible to a number.
*/
static long getLengthProperty(Context cx, Scriptable obj) {
// These will both give numeric lengths within Uint32 range.
if (obj instanceof NativeString) {
return ((NativeString)obj).getLength();
} else if (obj instanceof NativeArray) {
return ((NativeArray)obj).getLength();
}
return ScriptRuntime.toUint32(
ScriptRuntime.getObjectProp(obj, "length", cx));
}
private static Object setLengthProperty(Context cx, Scriptable target,
long length)
{
return ScriptRuntime.setObjectProp(
target, "length", ScriptRuntime.wrapNumber(length), cx);
}
/* Utility functions to encapsulate index > Integer.MAX_VALUE
* handling. Also avoids unnecessary object creation that would
* be necessary to use the general ScriptRuntime.get/setElem
* functions... though this is probably premature optimization.
*/
private static void deleteElem(Scriptable target, long index) {
int i = (int)index;
if (i == index) { target.delete(i); }
else { target.delete(Long.toString(index)); }
}
private static Object getElem(Context cx, Scriptable target, long index)
{
if (index > Integer.MAX_VALUE) {
String id = Long.toString(index);
return ScriptRuntime.getObjectProp(target, id, cx);
} else {
return ScriptRuntime.getObjectIndex(target, (int)index, cx);
}
}
// same as getElem, but without converting NOT_FOUND to undefined
private static Object getRawElem(Scriptable target, long index) {
if (index > Integer.MAX_VALUE) {
return ScriptableObject.getProperty(target, Long.toString(index));
} else {
return ScriptableObject.getProperty(target, (int) index);
}
}
private static void setElem(Context cx, Scriptable target, long index,
Object value)
{
if (index > Integer.MAX_VALUE) {
String id = Long.toString(index);
ScriptRuntime.setObjectProp(target, id, value, cx);
} else {
ScriptRuntime.setObjectIndex(target, (int)index, value, cx);
}
}
private static String toStringHelper(Context cx, Scriptable scope,
Scriptable thisObj,
boolean toSource, boolean toLocale)
{
/* It's probably redundant to handle long lengths in this
* function; StringBuilders are limited to 2^31 in java.
*/
long length = getLengthProperty(cx, thisObj);
StringBuilder result = new StringBuilder(256);
// whether to return '4,unquoted,5' or '[4, "quoted", 5]'
String separator;
if (toSource) {
result.append('[');
separator = ", ";
} else {
separator = ",";
}
boolean haslast = false;
long i = 0;
boolean toplevel, iterating;
if (cx.iterating == null) {
toplevel = true;
iterating = false;
cx.iterating = new ObjToIntMap(31);
} else {
toplevel = false;
iterating = cx.iterating.has(thisObj);
}
// Make sure cx.iterating is set to null when done
// so we don't leak memory
try {
if (!iterating) {
cx.iterating.put(thisObj, 0); // stop recursion.
for (i = 0; i < length; i++) {
if (i > 0) result.append(separator);
Object elem = getElem(cx, thisObj, i);
if (elem == null || elem == Undefined.instance) {
haslast = false;
continue;
}
haslast = true;
if (toSource) {
result.append(ScriptRuntime.uneval(cx, scope, elem));
} else if (elem instanceof String) {
String s = (String)elem;
if (toSource) {
result.append('\"');
result.append(ScriptRuntime.escapeString(s));
result.append('\"');
} else {
result.append(s);
}
} else {
if (toLocale)
{
Callable fun;
Scriptable funThis;
fun = ScriptRuntime.getPropFunctionAndThis(
elem, "toLocaleString", cx);
funThis = ScriptRuntime.lastStoredScriptable(cx);
elem = fun.call(cx, scope, funThis,
ScriptRuntime.emptyArgs);
}
result.append(ScriptRuntime.toString(elem));
}
}
}
} finally {
if (toplevel) {
cx.iterating = null;
}
}
if (toSource) {
//for [,,].length behavior; we want toString to be symmetric.
if (!haslast && i > 0)
result.append(", ]");
else
result.append(']');
}
return result.toString();
}
/**
* See ECMA 15.4.4.3
*/
private static String js_join(Context cx, Scriptable thisObj,
Object[] args)
{
long llength = getLengthProperty(cx, thisObj);
int length = (int)llength;
if (llength != length) {
throw Context.reportRuntimeError1(
"msg.arraylength.too.big", String.valueOf(llength));
}
// if no args, use "," as separator
String separator = (args.length < 1 || args[0] == Undefined.instance)
? ","
: ScriptRuntime.toString(args[0]);
if (thisObj instanceof NativeArray) {
NativeArray na = (NativeArray) thisObj;
if (na.denseOnly) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i != 0) {
sb.append(separator);
}
if (i < na.dense.length) {
Object temp = na.dense[i];
if (temp != null && temp != Undefined.instance &&
temp != Scriptable.NOT_FOUND)
{
sb.append(ScriptRuntime.toString(temp));
}
}
}
return sb.toString();
}
}
if (length == 0) {
return "";
}
String[] buf = new String[length];
int total_size = 0;
for (int i = 0; i != length; i++) {
Object temp = getElem(cx, thisObj, i);
if (temp != null && temp != Undefined.instance) {
String str = ScriptRuntime.toString(temp);
total_size += str.length();
buf[i] = str;
}
}
total_size += (length - 1) * separator.length();
StringBuilder sb = new StringBuilder(total_size);
for (int i = 0; i != length; i++) {
if (i != 0) {
sb.append(separator);
}
String str = buf[i];
if (str != null) {
// str == null for undefined or null
sb.append(str);
}
}
return sb.toString();
}
/**
* See ECMA 15.4.4.4
*/
private static Scriptable js_reverse(Context cx, Scriptable thisObj,
Object[] args)
{
if (thisObj instanceof NativeArray) {
NativeArray na = (NativeArray) thisObj;
if (na.denseOnly) {
for (int i=0, j=((int)na.length)-1; i < j; i++,j--) {
Object temp = na.dense[i];
na.dense[i] = na.dense[j];
na.dense[j] = temp;
}
return thisObj;
}
}
long len = getLengthProperty(cx, thisObj);
long half = len / 2;
for(long i=0; i < half; i++) {
long j = len - i - 1;
Object temp1 = getElem(cx, thisObj, i);
Object temp2 = getElem(cx, thisObj, j);
setElem(cx, thisObj, i, temp2);
setElem(cx, thisObj, j, temp1);
}
return thisObj;
}
/**
* See ECMA 15.4.4.5
*/
private static Scriptable js_sort(Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
{
long length = getLengthProperty(cx, thisObj);
if (length <= 1) { return thisObj; }
Object compare;
Object[] cmpBuf;
if (args.length > 0 && Undefined.instance != args[0]) {
// sort with given compare function
compare = args[0];
cmpBuf = new Object[2]; // Buffer for cmp arguments
} else {
// sort with default compare
compare = null;
cmpBuf = null;
}
if (thisObj instanceof NativeArray) {
NativeArray na = (NativeArray) thisObj;
if (na.denseOnly) {
int ilength = (int) length;
heapsort(cx, scope, na.dense, ilength, compare, cmpBuf);
return thisObj;
}
}
// Should we use the extended sort function, or the faster one?
if (length >= Integer.MAX_VALUE) {
heapsort_extended(cx, scope, thisObj, length, compare, cmpBuf);
} else {
int ilength = (int)length;
// copy the JS array into a working array, so it can be
// sorted cheaply.
Object[] working = new Object[ilength];
for (int i = 0; i != ilength; ++i) {
working[i] = getElem(cx, thisObj, i);
}
heapsort(cx, scope, working, ilength, compare, cmpBuf);
// copy the working array back into thisObj
for (int i = 0; i != ilength; ++i) {
setElem(cx, thisObj, i, working[i]);
}
}
return thisObj;
}
// Return true only if x > y
private static boolean isBigger(Context cx, Scriptable scope,
Object x, Object y,
Object cmp, Object[] cmpBuf)
{
if (cmp == null) {
if (cmpBuf != null) Kit.codeBug();
} else {
if (cmpBuf == null || cmpBuf.length != 2) Kit.codeBug();
}
Object undef = Undefined.instance;
Object notfound = Scriptable.NOT_FOUND;
// sort undefined to end
if (y == undef || y == notfound) {
return false; // x can not be bigger then undef
} else if (x == undef || x == notfound) {
return true; // y != undef here, so x > y
}
if (cmp == null) {
// if no cmp function supplied, sort lexicographically
String a = ScriptRuntime.toString(x);
String b = ScriptRuntime.toString(y);
return a.compareTo(b) > 0;
}
else {
// assemble args and call supplied JS cmp function
cmpBuf[0] = x;
cmpBuf[1] = y;
Callable fun = ScriptRuntime.getValueFunctionAndThis(cmp, cx);
Scriptable funThis = ScriptRuntime.lastStoredScriptable(cx);
Object ret = fun.call(cx, scope, funThis, cmpBuf);
double d = ScriptRuntime.toNumber(ret);
// XXX what to do when cmp function returns NaN? ECMA states
// that it's then not a 'consistent comparison function'... but
// then what do we do? Back out and start over with the generic
// cmp function when we see a NaN? Throw an error?
// for now, just ignore it:
return d > 0;
}
}
/** Heapsort implementation.
* See "Introduction to Algorithms" by Cormen, Leiserson, Rivest for details.
* Adjusted for zero based indexes.
*/
private static void heapsort(Context cx, Scriptable scope,
Object[] array, int length,
Object cmp, Object[] cmpBuf)
{
if (length <= 1) Kit.codeBug();
// Build heap
for (int i = length / 2; i != 0;) {
--i;
Object pivot = array[i];
heapify(cx, scope, pivot, array, i, length, cmp, cmpBuf);
}
// Sort heap
for (int i = length; i != 1;) {
--i;
Object pivot = array[i];
array[i] = array[0];
heapify(cx, scope, pivot, array, 0, i, cmp, cmpBuf);
}
}
/** pivot and child heaps of i should be made into heap starting at i,
* original array[i] is never used to have less array access during sorting.
*/
private static void heapify(Context cx, Scriptable scope,
Object pivot, Object[] array, int i, int end,
Object cmp, Object[] cmpBuf)
{
for (;;) {
int child = i * 2 + 1;
if (child >= end) {
break;
}
Object childVal = array[child];
if (child + 1 < end) {
Object nextVal = array[child + 1];
if (isBigger(cx, scope, nextVal, childVal, cmp, cmpBuf)) {
++child; childVal = nextVal;
}
}
if (!isBigger(cx, scope, childVal, pivot, cmp, cmpBuf)) {
break;
}
array[i] = childVal;
i = child;
}
array[i] = pivot;
}
/** Version of heapsort that call getElem/setElem on target to query/assign
* array elements instead of Java array access
*/
private static void heapsort_extended(Context cx, Scriptable scope,
Scriptable target, long length,
Object cmp, Object[] cmpBuf)
{
if (length <= 1) Kit.codeBug();
// Build heap
for (long i = length / 2; i != 0;) {
--i;
Object pivot = getElem(cx, target, i);
heapify_extended(cx, scope, pivot, target, i, length, cmp, cmpBuf);
}
// Sort heap
for (long i = length; i != 1;) {
--i;
Object pivot = getElem(cx, target, i);
setElem(cx, target, i, getElem(cx, target, 0));
heapify_extended(cx, scope, pivot, target, 0, i, cmp, cmpBuf);
}
}
private static void heapify_extended(Context cx, Scriptable scope,
Object pivot, Scriptable target,
long i, long end,
Object cmp, Object[] cmpBuf)
{
for (;;) {
long child = i * 2 + 1;
if (child >= end) {
break;
}
Object childVal = getElem(cx, target, child);
if (child + 1 < end) {
Object nextVal = getElem(cx, target, child + 1);
if (isBigger(cx, scope, nextVal, childVal, cmp, cmpBuf)) {
++child; childVal = nextVal;
}
}
if (!isBigger(cx, scope, childVal, pivot, cmp, cmpBuf)) {
break;
}
setElem(cx, target, i, childVal);
i = child;
}
setElem(cx, target, i, pivot);
}
/**
* Non-ECMA methods.
*/
private static Object js_push(Context cx, Scriptable thisObj,
Object[] args)
{
if (thisObj instanceof NativeArray) {
NativeArray na = (NativeArray) thisObj;
if (na.denseOnly &&
na.ensureCapacity((int) na.length + args.length))
{
for (int i = 0; i < args.length; i++) {
na.dense[(int)na.length++] = args[i];
}
return ScriptRuntime.wrapNumber(na.length);
}
}
long length = getLengthProperty(cx, thisObj);
for (int i = 0; i < args.length; i++) {
setElem(cx, thisObj, length + i, args[i]);
}
length += args.length;
Object lengthObj = setLengthProperty(cx, thisObj, length);
/*
* If JS1.2, follow Perl4 by returning the last thing pushed.
* Otherwise, return the new array length.
*/
if (cx.getLanguageVersion() == Context.VERSION_1_2)
// if JS1.2 && no arguments, return undefined.
return args.length == 0
? Undefined.instance
: args[args.length - 1];
else
return lengthObj;
}
private static Object js_pop(Context cx, Scriptable thisObj,
Object[] args)
{
Object result;
if (thisObj instanceof NativeArray) {
NativeArray na = (NativeArray) thisObj;
if (na.denseOnly && na.length > 0) {
na.length--;
result = na.dense[(int)na.length];
na.dense[(int)na.length] = NOT_FOUND;
return result;
}
}
long length = getLengthProperty(cx, thisObj);
if (length > 0) {
length--;
// Get the to-be-deleted property's value.
result = getElem(cx, thisObj, length);
// We don't need to delete the last property, because
// setLength does that for us.
} else {
result = Undefined.instance;
}
// necessary to match js even when length < 0; js pop will give a
// length property to any target it is called on.
setLengthProperty(cx, thisObj, length);
return result;
}
private static Object js_shift(Context cx, Scriptable thisObj,
Object[] args)
{
if (thisObj instanceof NativeArray) {
NativeArray na = (NativeArray) thisObj;
if (na.denseOnly && na.length > 0) {
na.length--;
Object result = na.dense[0];
System.arraycopy(na.dense, 1, na.dense, 0, (int)na.length);
na.dense[(int)na.length] = NOT_FOUND;
return result;
}
}
Object result;
long length = getLengthProperty(cx, thisObj);
if (length > 0) {
long i = 0;
length--;
// Get the to-be-deleted property's value.
result = getElem(cx, thisObj, i);
/*
* Slide down the array above the first element. Leave i
* set to point to the last element.
*/
if (length > 0) {
for (i = 1; i <= length; i++) {
Object temp = getElem(cx, thisObj, i);
setElem(cx, thisObj, i - 1, temp);
}
}
// We don't need to delete the last property, because
// setLength does that for us.
} else {
result = Undefined.instance;
}
setLengthProperty(cx, thisObj, length);
return result;
}
private static Object js_unshift(Context cx, Scriptable thisObj,
Object[] args)
{
if (thisObj instanceof NativeArray) {
NativeArray na = (NativeArray) thisObj;
if (na.denseOnly &&
na.ensureCapacity((int)na.length + args.length))
{
System.arraycopy(na.dense, 0, na.dense, args.length,
(int) na.length);
for (int i = 0; i < args.length; i++) {
na.dense[i] = args[i];
}
na.length += args.length;
return ScriptRuntime.wrapNumber(na.length);
}
}
long length = getLengthProperty(cx, thisObj);
int argc = args.length;
if (args.length > 0) {
/* Slide up the array to make room for args at the bottom */
if (length > 0) {
for (long last = length - 1; last >= 0; last--) {
Object temp = getElem(cx, thisObj, last);
setElem(cx, thisObj, last + argc, temp);
}
}
/* Copy from argv to the bottom of the array. */
for (int i = 0; i < args.length; i++) {
setElem(cx, thisObj, i, args[i]);
}
/* Follow Perl by returning the new array length. */
length += args.length;
return setLengthProperty(cx, thisObj, length);
}
return ScriptRuntime.wrapNumber(length);
}
private static Object js_splice(Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
{
NativeArray na = null;
boolean denseMode = false;
if (thisObj instanceof NativeArray) {
na = (NativeArray) thisObj;
denseMode = na.denseOnly;
}
/* create an empty Array to return. */
scope = getTopLevelScope(scope);
int argc = args.length;
if (argc == 0)
return ScriptRuntime.newObject(cx, scope, "Array", null);
long length = getLengthProperty(cx, thisObj);
/* Convert the first argument into a starting index. */
long begin = toSliceIndex(ScriptRuntime.toInteger(args[0]), length);
argc--;
/* Convert the second argument into count */
long count;
if (args.length == 1) {
count = length - begin;
} else {
double dcount = ScriptRuntime.toInteger(args[1]);
if (dcount < 0) {
count = 0;
} else if (dcount > (length - begin)) {
count = length - begin;
} else {
count = (long)dcount;
}
argc--;
}
long end = begin + count;
/* If there are elements to remove, put them into the return value. */
Object result;
if (count != 0) {
if (count == 1
&& (cx.getLanguageVersion() == Context.VERSION_1_2))
{
/*
* JS lacks "list context", whereby in Perl one turns the
* single scalar that's spliced out into an array just by
* assigning it to @single instead of $single, or by using it
* as Perl push's first argument, for instance.
*
* JS1.2 emulated Perl too closely and returned a non-Array for
* the single-splice-out case, requiring callers to test and
* wrap in [] if necessary. So JS1.3, default, and other
* versions all return an array of length 1 for uniformity.
*/
result = getElem(cx, thisObj, begin);
} else {
if (denseMode) {
int intLen = (int) (end - begin);
Object[] copy = new Object[intLen];
System.arraycopy(na.dense, (int) begin, copy, 0, intLen);
result = cx.newArray(scope, copy);
} else {
Scriptable resultArray = ScriptRuntime.newObject(cx, scope,
"Array", null);
for (long last = begin; last != end; last++) {
Object temp = getElem(cx, thisObj, last);
setElem(cx, resultArray, last - begin, temp);
}
result = resultArray;
}
}
} else { // (count == 0)
if (cx.getLanguageVersion() == Context.VERSION_1_2) {
/* Emulate C JS1.2; if no elements are removed, return undefined. */
result = Undefined.instance;
} else {
result = ScriptRuntime.newObject(cx, scope, "Array", null);
}
}
/* Find the direction (up or down) to copy and make way for argv. */
long delta = argc - count;
if (denseMode && length + delta < Integer.MAX_VALUE &&
na.ensureCapacity((int) (length + delta)))
{
System.arraycopy(na.dense, (int) end, na.dense,
(int) (begin + argc), (int) (length - end));
if (argc > 0) {
System.arraycopy(args, 2, na.dense, (int) begin, argc);
}
if (delta < 0) {
Arrays.fill(na.dense, (int) (length + delta), (int) length,
NOT_FOUND);
}
na.length = length + delta;
return result;
}
if (delta > 0) {
for (long last = length - 1; last >= end; last--) {
Object temp = getElem(cx, thisObj, last);
setElem(cx, thisObj, last + delta, temp);
}
} else if (delta < 0) {
for (long last = end; last < length; last++) {
Object temp = getElem(cx, thisObj, last);
setElem(cx, thisObj, last + delta, temp);
}
}
/* Copy from argv into the hole to complete the splice. */
int argoffset = args.length - argc;
for (int i = 0; i < argc; i++) {
setElem(cx, thisObj, begin + i, args[i + argoffset]);
}
/* Update length in case we deleted elements from the end. */
setLengthProperty(cx, thisObj, length + delta);
return result;
}
/*
* See Ecma 262v3 15.4.4.4
*/
private static Scriptable js_concat(Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
{
// create an empty Array to return.
scope = getTopLevelScope(scope);
Function ctor = ScriptRuntime.getExistingCtor(cx, scope, "Array");
Scriptable result = ctor.construct(cx, scope, ScriptRuntime.emptyArgs);
if (thisObj instanceof NativeArray && result instanceof NativeArray) {
NativeArray denseThis = (NativeArray) thisObj;
NativeArray denseResult = (NativeArray) result;
if (denseThis.denseOnly && denseResult.denseOnly) {
// First calculate length of resulting array
boolean canUseDense = true;
int length = (int) denseThis.length;
for (int i = 0; i < args.length && canUseDense; i++) {
if (args[i] instanceof NativeArray) {
// only try to use dense approach for Array-like
// objects that are actually NativeArrays
final NativeArray arg = (NativeArray) args[i];
canUseDense = arg.denseOnly;
length += arg.length;
} else {
length++;
}
}
if (canUseDense && denseResult.ensureCapacity(length)) {
System.arraycopy(denseThis.dense, 0, denseResult.dense,
0, (int) denseThis.length);
int cursor = (int) denseThis.length;
for (int i = 0; i < args.length && canUseDense; i++) {
if (args[i] instanceof NativeArray) {
NativeArray arg = (NativeArray) args[i];
System.arraycopy(arg.dense, 0,
denseResult.dense, cursor,
(int)arg.length);
cursor += (int)arg.length;
} else {
denseResult.dense[cursor++] = args[i];
}
}
denseResult.length = length;
return result;
}
}
}
long length;
long slot = 0;
/* Put the target in the result array; only add it as an array
* if it looks like one.
*/
if (ScriptRuntime.instanceOf(thisObj, ctor, cx)) {
length = getLengthProperty(cx, thisObj);
// Copy from the target object into the result
for (slot = 0; slot < length; slot++) {
Object temp = getElem(cx, thisObj, slot);
setElem(cx, result, slot, temp);
}
} else {
setElem(cx, result, slot++, thisObj);
}
/* Copy from the arguments into the result. If any argument
* has a numeric length property, treat it as an array and add
* elements separately; otherwise, just copy the argument.
*/
for (int i = 0; i < args.length; i++) {
if (ScriptRuntime.instanceOf(args[i], ctor, cx)) {
// ScriptRuntime.instanceOf => instanceof Scriptable
Scriptable arg = (Scriptable)args[i];
length = getLengthProperty(cx, arg);
for (long j = 0; j < length; j++, slot++) {
Object temp = getElem(cx, arg, j);
setElem(cx, result, slot, temp);
}
} else {
setElem(cx, result, slot++, args[i]);
}
}
return result;
}
private Scriptable js_slice(Context cx, Scriptable thisObj,
Object[] args)
{
Scriptable scope = getTopLevelScope(this);
Scriptable result = ScriptRuntime.newObject(cx, scope, "Array", null);
long length = getLengthProperty(cx, thisObj);
long begin, end;
if (args.length == 0) {
begin = 0;
end = length;
} else {
begin = toSliceIndex(ScriptRuntime.toInteger(args[0]), length);
if (args.length == 1) {
end = length;
} else {
end = toSliceIndex(ScriptRuntime.toInteger(args[1]), length);
}
}
for (long slot = begin; slot < end; slot++) {
Object temp = getElem(cx, thisObj, slot);
setElem(cx, result, slot - begin, temp);
}
return result;
}
private static long toSliceIndex(double value, long length) {
long result;
if (value < 0.0) {
if (value + length < 0.0) {
result = 0;
} else {
result = (long)(value + length);
}
} else if (value > length) {
result = length;
} else {
result = (long)value;
}
return result;
}
/**
* Implements the methods "indexOf" and "lastIndexOf".
*/
private Object indexOfHelper(Context cx, Scriptable thisObj,
Object[] args, boolean isLast)
{
Object compareTo = args.length > 0 ? args[0] : Undefined.instance;
long length = getLengthProperty(cx, thisObj);
long start;
if (isLast) {
// lastIndexOf
/*
* From http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Objects:Array:lastIndexOf
* The index at which to start searching backwards. Defaults to the
* array's length, i.e. the whole array will be searched. If the
* index is greater than or equal to the length of the array, the
* whole array will be searched. If negative, it is taken as the
* offset from the end of the array. Note that even when the index
* is negative, the array is still searched from back to front. If
* the calculated index is less than 0, -1 is returned, i.e. the
* array will not be searched.
*/
if (args.length < 2) {
// default
start = length-1;
} else {
start = ScriptRuntime.toInt32(ScriptRuntime.toNumber(args[1]));
if (start >= length)
start = length-1;
else if (start < 0)
start += length;
// Note that start may be negative, but that's okay
// as the result of -1 will fall out from the code below
}
} else {
// indexOf
/*
* From http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Objects:Array:indexOf
* The index at which to begin the search. Defaults to 0, i.e. the
* whole array will be searched. If the index is greater than or
* equal to the length of the array, -1 is returned, i.e. the array
* will not be searched. If negative, it is taken as the offset from
* the end of the array. Note that even when the index is negative,
* the array is still searched from front to back. If the calculated
* index is less than 0, the whole array will be searched.
*/
if (args.length < 2) {
// default
start = 0;
} else {
start = ScriptRuntime.toInt32(ScriptRuntime.toNumber(args[1]));
if (start < 0) {
start += length;
if (start < 0)
start = 0;
}
// Note that start may be > length-1, but that's okay
// as the result of -1 will fall out from the code below
}
}
if (thisObj instanceof NativeArray) {
NativeArray na = (NativeArray) thisObj;
if (na.denseOnly) {
if (isLast) {
for (int i=(int)start; i >= 0; i--) {
if (na.dense[i] != Scriptable.NOT_FOUND &&
ScriptRuntime.shallowEq(na.dense[i], compareTo))
{
return Long.valueOf(i);
}
}
} else {
for (int i=(int)start; i < length; i++) {
if (na.dense[i] != Scriptable.NOT_FOUND &&
ScriptRuntime.shallowEq(na.dense[i], compareTo))
{
return Long.valueOf(i);
}
}
}
return NEGATIVE_ONE;
}
}
if (isLast) {
for (long i=start; i >= 0; i--) {
if (ScriptRuntime.shallowEq(getElem(cx, thisObj, i), compareTo)) {
return new Long(i);
}
}
} else {
for (long i=start; i < length; i++) {
if (ScriptRuntime.shallowEq(getElem(cx, thisObj, i), compareTo)) {
return new Long(i);
}
}
}
return NEGATIVE_ONE;
}
/**
* Implements the methods "every", "filter", "forEach", "map", and "some".
*/
private Object iterativeMethod(Context cx, int id, Scriptable scope,
Scriptable thisObj, Object[] args)
{
Object callbackArg = args.length > 0 ? args[0] : Undefined.instance;
if (callbackArg == null || !(callbackArg instanceof Function)) {
throw ScriptRuntime.notFunctionError(callbackArg);
}
Function f = (Function) callbackArg;
Scriptable parent = ScriptableObject.getTopLevelScope(f);
Scriptable thisArg;
if (args.length < 2 || args[1] == null || args[1] == Undefined.instance)
{
thisArg = parent;
} else {
thisArg = ScriptRuntime.toObject(cx, scope, args[1]);
}
long length = getLengthProperty(cx, thisObj);
Scriptable array = ScriptRuntime.newObject(cx, scope, "Array", null);
long j=0;
for (long i=0; i < length; i++) {
Object[] innerArgs = new Object[3];
Object elem = getRawElem(thisObj, i);
if (elem == Scriptable.NOT_FOUND) {
continue;
}
innerArgs[0] = elem;
innerArgs[1] = Long.valueOf(i);
innerArgs[2] = thisObj;
Object result = f.call(cx, parent, thisArg, innerArgs);
switch (id) {
case Id_every:
if (!ScriptRuntime.toBoolean(result))
return Boolean.FALSE;
break;
case Id_filter:
if (ScriptRuntime.toBoolean(result))
setElem(cx, array, j++, innerArgs[0]);
break;
case Id_forEach:
break;
case Id_map:
setElem(cx, array, i, result);
break;
case Id_some:
if (ScriptRuntime.toBoolean(result))
return Boolean.TRUE;
break;
}
}
switch (id) {
case Id_every:
return Boolean.TRUE;
case Id_filter:
case Id_map:
return array;
case Id_some:
return Boolean.FALSE;
case Id_forEach:
default:
return Undefined.instance;
}
}
/**
* Implements the methods "reduce" and "reduceRight".
*/
private Object reduceMethod(Context cx, int id, Scriptable scope,
Scriptable thisObj, Object[] args)
{
Object callbackArg = args.length > 0 ? args[0] : Undefined.instance;
if (callbackArg == null || !(callbackArg instanceof Function)) {
throw ScriptRuntime.notFunctionError(callbackArg);
}
Function f = (Function) callbackArg;
Scriptable parent = ScriptableObject.getTopLevelScope(f);
long length = getLengthProperty(cx, thisObj);
// offset hack to serve both reduce and reduceRight with the same loop
long offset = id == Id_reduceRight ? length - 1 : 0;
Object value = args.length > 1 ? args[1] : Scriptable.NOT_FOUND;
for (long i = 0; i < length; i++) {
Object elem = getRawElem(thisObj, Math.abs(i - offset));
if (elem == Scriptable.NOT_FOUND) {
continue;
}
if (value == Scriptable.NOT_FOUND) {
// no initial value passed, use first element found as inital value
value = elem;
} else {
Object[] innerArgs = new Object[4];
innerArgs[0] = value;
innerArgs[1] = elem;
innerArgs[2] = new Long(i);
innerArgs[3] = thisObj;
value = f.call(cx, parent, parent, innerArgs);
}
}
if (value == Scriptable.NOT_FOUND) {
// reproduce spidermonkey error message
throw Context.reportRuntimeError0("msg.empty.array.reduce");
}
return value;
}
// #string_id_map#
@Override
protected int findPrototypeId(String s)
{
int id;
// #generated# Last update: 2005-09-26 15:47:42 EDT
L0: { id = 0; String X = null; int c;
L: switch (s.length()) {
case 3: c=s.charAt(0);
if (c=='m') { if (s.charAt(2)=='p' && s.charAt(1)=='a') {id=Id_map; break L0;} }
else if (c=='p') { if (s.charAt(2)=='p' && s.charAt(1)=='o') {id=Id_pop; break L0;} }
break L;
case 4: switch (s.charAt(2)) {
case 'i': X="join";id=Id_join; break L;
case 'm': X="some";id=Id_some; break L;
case 'r': X="sort";id=Id_sort; break L;
case 's': X="push";id=Id_push; break L;
} break L;
case 5: c=s.charAt(1);
if (c=='h') { X="shift";id=Id_shift; }
else if (c=='l') { X="slice";id=Id_slice; }
else if (c=='v') { X="every";id=Id_every; }
break L;
case 6: c=s.charAt(0);
if (c=='c') { X="concat";id=Id_concat; }
else if (c=='f') { X="filter";id=Id_filter; }
else if (c=='s') { X="splice";id=Id_splice; }
else if (c=='r') { X="reduce";id=Id_reduce; }
break L;
case 7: switch (s.charAt(0)) {
case 'f': X="forEach";id=Id_forEach; break L;
case 'i': X="indexOf";id=Id_indexOf; break L;
case 'r': X="reverse";id=Id_reverse; break L;
case 'u': X="unshift";id=Id_unshift; break L;
} break L;
case 8: c=s.charAt(3);
if (c=='o') { X="toSource";id=Id_toSource; }
else if (c=='t') { X="toString";id=Id_toString; }
break L;
case 11: c=s.charAt(0);
if (c=='c') { X="constructor";id=Id_constructor; }
else if (c=='l') { X="lastIndexOf";id=Id_lastIndexOf; }
else if (c=='r') { X="reduceRight";id=Id_reduceRight; }
break L;
case 14: X="toLocaleString";id=Id_toLocaleString; break L;
}
if (X!=null && X!=s && !X.equals(s)) id = 0;
}
// #/generated#
return id;
}
private static final int
Id_constructor = 1,
Id_toString = 2,
Id_toLocaleString = 3,
Id_toSource = 4,
Id_join = 5,
Id_reverse = 6,
Id_sort = 7,
Id_push = 8,
Id_pop = 9,
Id_shift = 10,
Id_unshift = 11,
Id_splice = 12,
Id_concat = 13,
Id_slice = 14,
Id_indexOf = 15,
Id_lastIndexOf = 16,
Id_every = 17,
Id_filter = 18,
Id_forEach = 19,
Id_map = 20,
Id_some = 21,
Id_reduce = 22,
Id_reduceRight = 23,
MAX_PROTOTYPE_ID = 23;
// #/string_id_map#
private static final int
ConstructorId_join = -Id_join,
ConstructorId_reverse = -Id_reverse,
ConstructorId_sort = -Id_sort,
ConstructorId_push = -Id_push,
ConstructorId_pop = -Id_pop,
ConstructorId_shift = -Id_shift,
ConstructorId_unshift = -Id_unshift,
ConstructorId_splice = -Id_splice,
ConstructorId_concat = -Id_concat,
ConstructorId_slice = -Id_slice,
ConstructorId_indexOf = -Id_indexOf,
ConstructorId_lastIndexOf = -Id_lastIndexOf,
ConstructorId_every = -Id_every,
ConstructorId_filter = -Id_filter,
ConstructorId_forEach = -Id_forEach,
ConstructorId_map = -Id_map,
ConstructorId_some = -Id_some,
ConstructorId_reduce = -Id_reduce,
ConstructorId_reduceRight = -Id_reduceRight;
/**
* Internal representation of the JavaScript array's length property.
*/
private long length;
/**
* Fast storage for dense arrays. Sparse arrays will use the superclass's
* hashtable storage scheme.
*/
private Object[] dense;
/**
* True if all numeric properties are stored in <code>dense</code>.
*/
private boolean denseOnly;
/**
* The maximum size of <code>dense</code> that will be allocated initially.
*/
private static int maximumInitialCapacity = 10000;
/**
* The default capacity for <code>dense</code>.
*/
private static final int DEFAULT_INITIAL_CAPACITY = 10;
/**
* The factor to grow <code>dense</code> by.
*/
private static final double GROW_FACTOR = 1.5;
private static final int MAX_PRE_GROW_SIZE = (int)(Integer.MAX_VALUE / GROW_FACTOR);
}
| src/org/mozilla/javascript/NativeArray.java | /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1997-1999
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Norris Boyd
* Mike McCabe
* Igor Bukanov
*
* Alternatively, the contents of this file may be used under the terms of
* the GNU General Public License Version 2 or later (the "GPL"), in which
* case the provisions of the GPL are applicable instead of those above. If
* you wish to allow use of your version of this file only under the terms of
* the GPL and not to allow others to use your version of this file under the
* MPL, indicate your decision by deleting the provisions above and replacing
* them with the notice and other provisions required by the GPL. If you do
* not delete the provisions above, a recipient may use your version of this
* file under either the MPL or the GPL.
*
* ***** END LICENSE BLOCK ***** */
package org.mozilla.javascript;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* This class implements the Array native object.
* @author Norris Boyd
* @author Mike McCabe
*/
public class NativeArray extends IdScriptableObject
{
static final long serialVersionUID = 7331366857676127338L;
/*
* Optimization possibilities and open issues:
* - Long vs. double schizophrenia. I suspect it might be better
* to use double throughout.
*
* - Functions that need a new Array call "new Array" in the
* current scope rather than using a hardwired constructor;
* "Array" could be redefined. It turns out that js calls the
* equivalent of "new Array" in the current scope, except that it
* always gets at least an object back, even when Array == null.
*/
private static final Object ARRAY_TAG = "Array";
private static final Integer NEGATIVE_ONE = Integer.valueOf(-1);
static void init(Scriptable scope, boolean sealed)
{
NativeArray obj = new NativeArray(0);
obj.exportAsJSClass(MAX_PROTOTYPE_ID, scope, sealed);
}
static int getMaximumInitialCapacity() {
return maximumInitialCapacity;
}
static void setMaximumInitialCapacity(int maximumInitialCapacity) {
NativeArray.maximumInitialCapacity = maximumInitialCapacity;
}
public NativeArray(long lengthArg)
{
denseOnly = lengthArg <= maximumInitialCapacity;
if (denseOnly) {
int intLength = (int) lengthArg;
if (intLength < DEFAULT_INITIAL_CAPACITY)
intLength = DEFAULT_INITIAL_CAPACITY;
dense = new Object[intLength];
Arrays.fill(dense, Scriptable.NOT_FOUND);
}
length = lengthArg;
}
public NativeArray(Object[] array)
{
denseOnly = true;
dense = array;
length = array.length;
}
@Override
public String getClassName()
{
return "Array";
}
private static final int
Id_length = 1,
MAX_INSTANCE_ID = 1;
@Override
protected int getMaxInstanceId()
{
return MAX_INSTANCE_ID;
}
@Override
protected int findInstanceIdInfo(String s)
{
if (s.equals("length")) {
return instanceIdInfo(DONTENUM | PERMANENT, Id_length);
}
return super.findInstanceIdInfo(s);
}
@Override
protected String getInstanceIdName(int id)
{
if (id == Id_length) { return "length"; }
return super.getInstanceIdName(id);
}
@Override
protected Object getInstanceIdValue(int id)
{
if (id == Id_length) {
return ScriptRuntime.wrapNumber(length);
}
return super.getInstanceIdValue(id);
}
@Override
protected void setInstanceIdValue(int id, Object value)
{
if (id == Id_length) {
setLength(value); return;
}
super.setInstanceIdValue(id, value);
}
@Override
protected void fillConstructorProperties(IdFunctionObject ctor)
{
addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_join,
"join", 2);
addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_reverse,
"reverse", 1);
addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_sort,
"sort", 2);
addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_push,
"push", 2);
addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_pop,
"pop", 2);
addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_shift,
"shift", 2);
addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_unshift,
"unshift", 2);
addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_splice,
"splice", 2);
addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_concat,
"concat", 2);
addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_slice,
"slice", 2);
addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_indexOf,
"indexOf", 2);
addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_lastIndexOf,
"lastIndexOf", 2);
addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_every,
"every", 2);
addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_filter,
"filter", 2);
addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_forEach,
"forEach", 2);
addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_map,
"map", 2);
addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_some,
"some", 2);
addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_reduce,
"reduce", 2);
addIdFunctionProperty(ctor, ARRAY_TAG, ConstructorId_reduceRight,
"reduceRight", 2);
super.fillConstructorProperties(ctor);
}
@Override
protected void initPrototypeId(int id)
{
String s;
int arity;
switch (id) {
case Id_constructor: arity=1; s="constructor"; break;
case Id_toString: arity=0; s="toString"; break;
case Id_toLocaleString: arity=1; s="toLocaleString"; break;
case Id_toSource: arity=0; s="toSource"; break;
case Id_join: arity=1; s="join"; break;
case Id_reverse: arity=0; s="reverse"; break;
case Id_sort: arity=1; s="sort"; break;
case Id_push: arity=1; s="push"; break;
case Id_pop: arity=1; s="pop"; break;
case Id_shift: arity=1; s="shift"; break;
case Id_unshift: arity=1; s="unshift"; break;
case Id_splice: arity=1; s="splice"; break;
case Id_concat: arity=1; s="concat"; break;
case Id_slice: arity=1; s="slice"; break;
case Id_indexOf: arity=1; s="indexOf"; break;
case Id_lastIndexOf: arity=1; s="lastIndexOf"; break;
case Id_every: arity=1; s="every"; break;
case Id_filter: arity=1; s="filter"; break;
case Id_forEach: arity=1; s="forEach"; break;
case Id_map: arity=1; s="map"; break;
case Id_some: arity=1; s="some"; break;
case Id_reduce: arity=1; s="reduce"; break;
case Id_reduceRight: arity=1; s="reduceRight"; break;
default: throw new IllegalArgumentException(String.valueOf(id));
}
initPrototypeMethod(ARRAY_TAG, id, s, arity);
}
@Override
public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
{
if (!f.hasTag(ARRAY_TAG)) {
return super.execIdCall(f, cx, scope, thisObj, args);
}
int id = f.methodId();
again:
for (;;) {
switch (id) {
case ConstructorId_join:
case ConstructorId_reverse:
case ConstructorId_sort:
case ConstructorId_push:
case ConstructorId_pop:
case ConstructorId_shift:
case ConstructorId_unshift:
case ConstructorId_splice:
case ConstructorId_concat:
case ConstructorId_slice:
case ConstructorId_indexOf:
case ConstructorId_lastIndexOf:
case ConstructorId_every:
case ConstructorId_filter:
case ConstructorId_forEach:
case ConstructorId_map:
case ConstructorId_some:
case ConstructorId_reduce:
case ConstructorId_reduceRight: {
if (args.length > 0) {
thisObj = ScriptRuntime.toObject(scope, args[0]);
Object[] newArgs = new Object[args.length-1];
for (int i=0; i < newArgs.length; i++)
newArgs[i] = args[i+1];
args = newArgs;
}
id = -id;
continue again;
}
case Id_constructor: {
boolean inNewExpr = (thisObj == null);
if (!inNewExpr) {
// IdFunctionObject.construct will set up parent, proto
return f.construct(cx, scope, args);
}
return jsConstructor(cx, scope, args);
}
case Id_toString:
return toStringHelper(cx, scope, thisObj,
cx.hasFeature(Context.FEATURE_TO_STRING_AS_SOURCE), false);
case Id_toLocaleString:
return toStringHelper(cx, scope, thisObj, false, true);
case Id_toSource:
return toStringHelper(cx, scope, thisObj, true, false);
case Id_join:
return js_join(cx, thisObj, args);
case Id_reverse:
return js_reverse(cx, thisObj, args);
case Id_sort:
return js_sort(cx, scope, thisObj, args);
case Id_push:
return js_push(cx, thisObj, args);
case Id_pop:
return js_pop(cx, thisObj, args);
case Id_shift:
return js_shift(cx, thisObj, args);
case Id_unshift:
return js_unshift(cx, thisObj, args);
case Id_splice:
return js_splice(cx, scope, thisObj, args);
case Id_concat:
return js_concat(cx, scope, thisObj, args);
case Id_slice:
return js_slice(cx, thisObj, args);
case Id_indexOf:
return indexOfHelper(cx, thisObj, args, false);
case Id_lastIndexOf:
return indexOfHelper(cx, thisObj, args, true);
case Id_every:
case Id_filter:
case Id_forEach:
case Id_map:
case Id_some:
return iterativeMethod(cx, id, scope, thisObj, args);
case Id_reduce:
case Id_reduceRight:
return reduceMethod(cx, id, scope, thisObj, args);
}
throw new IllegalArgumentException(String.valueOf(id));
}
}
@Override
public Object get(int index, Scriptable start)
{
if (!denseOnly && isGetterOrSetter(null, index, false))
return super.get(index, start);
if (dense != null && 0 <= index && index < dense.length)
return dense[index];
return super.get(index, start);
}
@Override
public boolean has(int index, Scriptable start)
{
if (!denseOnly && isGetterOrSetter(null, index, false))
return super.has(index, start);
if (dense != null && 0 <= index && index < dense.length)
return dense[index] != NOT_FOUND;
return super.has(index, start);
}
// if id is an array index (ECMA 15.4.0), return the number,
// otherwise return -1L
private static long toArrayIndex(String id)
{
double d = ScriptRuntime.toNumber(id);
if (d == d) {
long index = ScriptRuntime.toUint32(d);
if (index == d && index != 4294967295L) {
// Assume that ScriptRuntime.toString(index) is the same
// as java.lang.Long.toString(index) for long
if (Long.toString(index).equals(id)) {
return index;
}
}
}
return -1;
}
@Override
public void put(String id, Scriptable start, Object value)
{
super.put(id, start, value);
if (start == this) {
// If the object is sealed, super will throw exception
long index = toArrayIndex(id);
if (index >= length) {
length = index + 1;
denseOnly = false;
}
}
}
private boolean ensureCapacity(int capacity)
{
if (capacity > dense.length) {
if (capacity > MAX_PRE_GROW_SIZE) {
denseOnly = false;
return false;
}
capacity = Math.max(capacity, (int)(dense.length * GROW_FACTOR));
Object[] newDense = new Object[capacity];
System.arraycopy(dense, 0, newDense, 0, dense.length);
Arrays.fill(newDense, dense.length, newDense.length,
Scriptable.NOT_FOUND);
dense = newDense;
}
return true;
}
@Override
public void put(int index, Scriptable start, Object value)
{
if (start == this && !isSealed() && dense != null && 0 <= index &&
(denseOnly || !isGetterOrSetter(null, index, true)))
{
if (index < dense.length) {
dense[index] = value;
if (this.length <= index)
this.length = (long)index + 1;
return;
} else if (denseOnly && index < dense.length * GROW_FACTOR &&
ensureCapacity(index+1))
{
dense[index] = value;
this.length = (long)index + 1;
return;
} else {
denseOnly = false;
}
}
super.put(index, start, value);
if (start == this) {
// only set the array length if given an array index (ECMA 15.4.0)
if (this.length <= index) {
// avoid overflowing index!
this.length = (long)index + 1;
}
}
}
@Override
public void delete(int index)
{
if (dense != null && 0 <= index && index < dense.length &&
!isSealed() && (denseOnly || !isGetterOrSetter(null, index, true)))
{
dense[index] = NOT_FOUND;
} else {
super.delete(index);
}
}
@Override
public Object[] getIds()
{
Object[] superIds = super.getIds();
if (dense == null) { return superIds; }
int N = dense.length;
long currentLength = length;
if (N > currentLength) {
N = (int)currentLength;
}
if (N == 0) { return superIds; }
int superLength = superIds.length;
Object[] ids = new Object[N + superLength];
int presentCount = 0;
for (int i = 0; i != N; ++i) {
// Replace existing elements by their indexes
if (dense[i] != NOT_FOUND) {
ids[presentCount] = Integer.valueOf(i);
++presentCount;
}
}
if (presentCount != N) {
// dense contains deleted elems, need to shrink the result
Object[] tmp = new Object[presentCount + superLength];
System.arraycopy(ids, 0, tmp, 0, presentCount);
ids = tmp;
}
System.arraycopy(superIds, 0, ids, presentCount, superLength);
return ids;
}
@Override
public Object[] getAllIds()
{
Set allIds = new LinkedHashSet(Arrays.asList(this.getIds()));
allIds.addAll(Arrays.asList(super.getAllIds()));
return allIds.toArray();
}
@Override
public Object getDefaultValue(Class<?> hint)
{
if (hint == ScriptRuntime.NumberClass) {
Context cx = Context.getContext();
if (cx.getLanguageVersion() == Context.VERSION_1_2)
return Long.valueOf(length);
}
return super.getDefaultValue(hint);
}
/**
* See ECMA 15.4.1,2
*/
private static Object jsConstructor(Context cx, Scriptable scope,
Object[] args)
{
if (args.length == 0)
return new NativeArray(0);
// Only use 1 arg as first element for version 1.2; for
// any other version (including 1.3) follow ECMA and use it as
// a length.
if (cx.getLanguageVersion() == Context.VERSION_1_2) {
return new NativeArray(args);
} else {
Object arg0 = args[0];
if (args.length > 1 || !(arg0 instanceof Number)) {
return new NativeArray(args);
} else {
long len = ScriptRuntime.toUint32(arg0);
if (len != ((Number)arg0).doubleValue())
throw Context.reportRuntimeError0("msg.arraylength.bad");
return new NativeArray(len);
}
}
}
public long getLength() {
return length;
}
/** @deprecated Use {@link #getLength()} instead. */
public long jsGet_length() {
return getLength();
}
/**
* Change the value of the internal flag that determines whether all
* storage is handed by a dense backing array rather than an associative
* store.
* @param denseOnly new value for denseOnly flag
* @throws IllegalArgumentException if an attempt is made to enable
* denseOnly after it was disabled; NativeArray code is not written
* to handle switching back to a dense representation
*/
void setDenseOnly(boolean denseOnly) {
if (denseOnly && !this.denseOnly)
throw new IllegalArgumentException();
this.denseOnly = denseOnly;
}
private void setLength(Object val) {
/* XXX do we satisfy this?
* 15.4.5.1 [[Put]](P, V):
* 1. Call the [[CanPut]] method of A with name P.
* 2. If Result(1) is false, return.
* ?
*/
double d = ScriptRuntime.toNumber(val);
long longVal = ScriptRuntime.toUint32(d);
if (longVal != d)
throw Context.reportRuntimeError0("msg.arraylength.bad");
if (denseOnly) {
if (longVal < length) {
// downcast okay because denseOnly
Arrays.fill(dense, (int) longVal, dense.length, NOT_FOUND);
length = longVal;
return;
} else if (longVal < MAX_PRE_GROW_SIZE &&
longVal < (length * GROW_FACTOR) &&
ensureCapacity((int)longVal))
{
length = longVal;
return;
} else {
denseOnly = false;
}
}
if (longVal < length) {
// remove all properties between longVal and length
if (length - longVal > 0x1000) {
// assume that the representation is sparse
Object[] e = getIds(); // will only find in object itself
for (int i=0; i < e.length; i++) {
Object id = e[i];
if (id instanceof String) {
// > MAXINT will appear as string
String strId = (String)id;
long index = toArrayIndex(strId);
if (index >= longVal)
delete(strId);
} else {
int index = ((Integer)id).intValue();
if (index >= longVal)
delete(index);
}
}
} else {
// assume a dense representation
for (long i = longVal; i < length; i++) {
deleteElem(this, i);
}
}
}
length = longVal;
}
/* Support for generic Array-ish objects. Most of the Array
* functions try to be generic; anything that has a length
* property is assumed to be an array.
* getLengthProperty returns 0 if obj does not have the length property
* or its value is not convertible to a number.
*/
static long getLengthProperty(Context cx, Scriptable obj) {
// These will both give numeric lengths within Uint32 range.
if (obj instanceof NativeString) {
return ((NativeString)obj).getLength();
} else if (obj instanceof NativeArray) {
return ((NativeArray)obj).getLength();
}
return ScriptRuntime.toUint32(
ScriptRuntime.getObjectProp(obj, "length", cx));
}
private static Object setLengthProperty(Context cx, Scriptable target,
long length)
{
return ScriptRuntime.setObjectProp(
target, "length", ScriptRuntime.wrapNumber(length), cx);
}
/* Utility functions to encapsulate index > Integer.MAX_VALUE
* handling. Also avoids unnecessary object creation that would
* be necessary to use the general ScriptRuntime.get/setElem
* functions... though this is probably premature optimization.
*/
private static void deleteElem(Scriptable target, long index) {
int i = (int)index;
if (i == index) { target.delete(i); }
else { target.delete(Long.toString(index)); }
}
private static Object getElem(Context cx, Scriptable target, long index)
{
if (index > Integer.MAX_VALUE) {
String id = Long.toString(index);
return ScriptRuntime.getObjectProp(target, id, cx);
} else {
return ScriptRuntime.getObjectIndex(target, (int)index, cx);
}
}
// same as getElem, but without converting NOT_FOUND to undefined
private static Object getRawElem(Scriptable target, long index) {
if (index > Integer.MAX_VALUE) {
return ScriptableObject.getProperty(target, Long.toString(index));
} else {
return ScriptableObject.getProperty(target, (int) index);
}
}
private static void setElem(Context cx, Scriptable target, long index,
Object value)
{
if (index > Integer.MAX_VALUE) {
String id = Long.toString(index);
ScriptRuntime.setObjectProp(target, id, value, cx);
} else {
ScriptRuntime.setObjectIndex(target, (int)index, value, cx);
}
}
private static String toStringHelper(Context cx, Scriptable scope,
Scriptable thisObj,
boolean toSource, boolean toLocale)
{
/* It's probably redundant to handle long lengths in this
* function; StringBuilders are limited to 2^31 in java.
*/
long length = getLengthProperty(cx, thisObj);
StringBuilder result = new StringBuilder(256);
// whether to return '4,unquoted,5' or '[4, "quoted", 5]'
String separator;
if (toSource) {
result.append('[');
separator = ", ";
} else {
separator = ",";
}
boolean haslast = false;
long i = 0;
boolean toplevel, iterating;
if (cx.iterating == null) {
toplevel = true;
iterating = false;
cx.iterating = new ObjToIntMap(31);
} else {
toplevel = false;
iterating = cx.iterating.has(thisObj);
}
// Make sure cx.iterating is set to null when done
// so we don't leak memory
try {
if (!iterating) {
cx.iterating.put(thisObj, 0); // stop recursion.
for (i = 0; i < length; i++) {
if (i > 0) result.append(separator);
Object elem = getElem(cx, thisObj, i);
if (elem == null || elem == Undefined.instance) {
haslast = false;
continue;
}
haslast = true;
if (toSource) {
result.append(ScriptRuntime.uneval(cx, scope, elem));
} else if (elem instanceof String) {
String s = (String)elem;
if (toSource) {
result.append('\"');
result.append(ScriptRuntime.escapeString(s));
result.append('\"');
} else {
result.append(s);
}
} else {
if (toLocale)
{
Callable fun;
Scriptable funThis;
fun = ScriptRuntime.getPropFunctionAndThis(
elem, "toLocaleString", cx);
funThis = ScriptRuntime.lastStoredScriptable(cx);
elem = fun.call(cx, scope, funThis,
ScriptRuntime.emptyArgs);
}
result.append(ScriptRuntime.toString(elem));
}
}
}
} finally {
if (toplevel) {
cx.iterating = null;
}
}
if (toSource) {
//for [,,].length behavior; we want toString to be symmetric.
if (!haslast && i > 0)
result.append(", ]");
else
result.append(']');
}
return result.toString();
}
/**
* See ECMA 15.4.4.3
*/
private static String js_join(Context cx, Scriptable thisObj,
Object[] args)
{
long llength = getLengthProperty(cx, thisObj);
int length = (int)llength;
if (llength != length) {
throw Context.reportRuntimeError1(
"msg.arraylength.too.big", String.valueOf(llength));
}
// if no args, use "," as separator
String separator = (args.length < 1 || args[0] == Undefined.instance)
? ","
: ScriptRuntime.toString(args[0]);
if (thisObj instanceof NativeArray) {
NativeArray na = (NativeArray) thisObj;
if (na.denseOnly) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
if (i != 0) {
sb.append(separator);
}
if (i < na.dense.length) {
Object temp = na.dense[i];
if (temp != null && temp != Undefined.instance &&
temp != Scriptable.NOT_FOUND)
{
sb.append(ScriptRuntime.toString(temp));
}
}
}
return sb.toString();
}
}
if (length == 0) {
return "";
}
String[] buf = new String[length];
int total_size = 0;
for (int i = 0; i != length; i++) {
Object temp = getElem(cx, thisObj, i);
if (temp != null && temp != Undefined.instance) {
String str = ScriptRuntime.toString(temp);
total_size += str.length();
buf[i] = str;
}
}
total_size += (length - 1) * separator.length();
StringBuilder sb = new StringBuilder(total_size);
for (int i = 0; i != length; i++) {
if (i != 0) {
sb.append(separator);
}
String str = buf[i];
if (str != null) {
// str == null for undefined or null
sb.append(str);
}
}
return sb.toString();
}
/**
* See ECMA 15.4.4.4
*/
private static Scriptable js_reverse(Context cx, Scriptable thisObj,
Object[] args)
{
if (thisObj instanceof NativeArray) {
NativeArray na = (NativeArray) thisObj;
if (na.denseOnly) {
for (int i=0, j=((int)na.length)-1; i < j; i++,j--) {
Object temp = na.dense[i];
na.dense[i] = na.dense[j];
na.dense[j] = temp;
}
return thisObj;
}
}
long len = getLengthProperty(cx, thisObj);
long half = len / 2;
for(long i=0; i < half; i++) {
long j = len - i - 1;
Object temp1 = getElem(cx, thisObj, i);
Object temp2 = getElem(cx, thisObj, j);
setElem(cx, thisObj, i, temp2);
setElem(cx, thisObj, j, temp1);
}
return thisObj;
}
/**
* See ECMA 15.4.4.5
*/
private static Scriptable js_sort(Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
{
long length = getLengthProperty(cx, thisObj);
if (length <= 1) { return thisObj; }
Object compare;
Object[] cmpBuf;
if (args.length > 0 && Undefined.instance != args[0]) {
// sort with given compare function
compare = args[0];
cmpBuf = new Object[2]; // Buffer for cmp arguments
} else {
// sort with default compare
compare = null;
cmpBuf = null;
}
if (thisObj instanceof NativeArray) {
NativeArray na = (NativeArray) thisObj;
if (na.denseOnly) {
int ilength = (int) length;
heapsort(cx, scope, na.dense, ilength, compare, cmpBuf);
return thisObj;
}
}
// Should we use the extended sort function, or the faster one?
if (length >= Integer.MAX_VALUE) {
heapsort_extended(cx, scope, thisObj, length, compare, cmpBuf);
} else {
int ilength = (int)length;
// copy the JS array into a working array, so it can be
// sorted cheaply.
Object[] working = new Object[ilength];
for (int i = 0; i != ilength; ++i) {
working[i] = getElem(cx, thisObj, i);
}
heapsort(cx, scope, working, ilength, compare, cmpBuf);
// copy the working array back into thisObj
for (int i = 0; i != ilength; ++i) {
setElem(cx, thisObj, i, working[i]);
}
}
return thisObj;
}
// Return true only if x > y
private static boolean isBigger(Context cx, Scriptable scope,
Object x, Object y,
Object cmp, Object[] cmpBuf)
{
if (cmp == null) {
if (cmpBuf != null) Kit.codeBug();
} else {
if (cmpBuf == null || cmpBuf.length != 2) Kit.codeBug();
}
Object undef = Undefined.instance;
Object notfound = Scriptable.NOT_FOUND;
// sort undefined to end
if (y == undef || y == notfound) {
return false; // x can not be bigger then undef
} else if (x == undef || x == notfound) {
return true; // y != undef here, so x > y
}
if (cmp == null) {
// if no cmp function supplied, sort lexicographically
String a = ScriptRuntime.toString(x);
String b = ScriptRuntime.toString(y);
return a.compareTo(b) > 0;
}
else {
// assemble args and call supplied JS cmp function
cmpBuf[0] = x;
cmpBuf[1] = y;
Callable fun = ScriptRuntime.getValueFunctionAndThis(cmp, cx);
Scriptable funThis = ScriptRuntime.lastStoredScriptable(cx);
Object ret = fun.call(cx, scope, funThis, cmpBuf);
double d = ScriptRuntime.toNumber(ret);
// XXX what to do when cmp function returns NaN? ECMA states
// that it's then not a 'consistent comparison function'... but
// then what do we do? Back out and start over with the generic
// cmp function when we see a NaN? Throw an error?
// for now, just ignore it:
return d > 0;
}
}
/** Heapsort implementation.
* See "Introduction to Algorithms" by Cormen, Leiserson, Rivest for details.
* Adjusted for zero based indexes.
*/
private static void heapsort(Context cx, Scriptable scope,
Object[] array, int length,
Object cmp, Object[] cmpBuf)
{
if (length <= 1) Kit.codeBug();
// Build heap
for (int i = length / 2; i != 0;) {
--i;
Object pivot = array[i];
heapify(cx, scope, pivot, array, i, length, cmp, cmpBuf);
}
// Sort heap
for (int i = length; i != 1;) {
--i;
Object pivot = array[i];
array[i] = array[0];
heapify(cx, scope, pivot, array, 0, i, cmp, cmpBuf);
}
}
/** pivot and child heaps of i should be made into heap starting at i,
* original array[i] is never used to have less array access during sorting.
*/
private static void heapify(Context cx, Scriptable scope,
Object pivot, Object[] array, int i, int end,
Object cmp, Object[] cmpBuf)
{
for (;;) {
int child = i * 2 + 1;
if (child >= end) {
break;
}
Object childVal = array[child];
if (child + 1 < end) {
Object nextVal = array[child + 1];
if (isBigger(cx, scope, nextVal, childVal, cmp, cmpBuf)) {
++child; childVal = nextVal;
}
}
if (!isBigger(cx, scope, childVal, pivot, cmp, cmpBuf)) {
break;
}
array[i] = childVal;
i = child;
}
array[i] = pivot;
}
/** Version of heapsort that call getElem/setElem on target to query/assign
* array elements instead of Java array access
*/
private static void heapsort_extended(Context cx, Scriptable scope,
Scriptable target, long length,
Object cmp, Object[] cmpBuf)
{
if (length <= 1) Kit.codeBug();
// Build heap
for (long i = length / 2; i != 0;) {
--i;
Object pivot = getElem(cx, target, i);
heapify_extended(cx, scope, pivot, target, i, length, cmp, cmpBuf);
}
// Sort heap
for (long i = length; i != 1;) {
--i;
Object pivot = getElem(cx, target, i);
setElem(cx, target, i, getElem(cx, target, 0));
heapify_extended(cx, scope, pivot, target, 0, i, cmp, cmpBuf);
}
}
private static void heapify_extended(Context cx, Scriptable scope,
Object pivot, Scriptable target,
long i, long end,
Object cmp, Object[] cmpBuf)
{
for (;;) {
long child = i * 2 + 1;
if (child >= end) {
break;
}
Object childVal = getElem(cx, target, child);
if (child + 1 < end) {
Object nextVal = getElem(cx, target, child + 1);
if (isBigger(cx, scope, nextVal, childVal, cmp, cmpBuf)) {
++child; childVal = nextVal;
}
}
if (!isBigger(cx, scope, childVal, pivot, cmp, cmpBuf)) {
break;
}
setElem(cx, target, i, childVal);
i = child;
}
setElem(cx, target, i, pivot);
}
/**
* Non-ECMA methods.
*/
private static Object js_push(Context cx, Scriptable thisObj,
Object[] args)
{
if (thisObj instanceof NativeArray) {
NativeArray na = (NativeArray) thisObj;
if (na.denseOnly &&
na.ensureCapacity((int) na.length + args.length))
{
for (int i = 0; i < args.length; i++) {
na.dense[(int)na.length++] = args[i];
}
return ScriptRuntime.wrapNumber(na.length);
}
}
long length = getLengthProperty(cx, thisObj);
for (int i = 0; i < args.length; i++) {
setElem(cx, thisObj, length + i, args[i]);
}
length += args.length;
Object lengthObj = setLengthProperty(cx, thisObj, length);
/*
* If JS1.2, follow Perl4 by returning the last thing pushed.
* Otherwise, return the new array length.
*/
if (cx.getLanguageVersion() == Context.VERSION_1_2)
// if JS1.2 && no arguments, return undefined.
return args.length == 0
? Undefined.instance
: args[args.length - 1];
else
return lengthObj;
}
private static Object js_pop(Context cx, Scriptable thisObj,
Object[] args)
{
Object result;
if (thisObj instanceof NativeArray) {
NativeArray na = (NativeArray) thisObj;
if (na.denseOnly && na.length > 0) {
na.length--;
result = na.dense[(int)na.length];
na.dense[(int)na.length] = NOT_FOUND;
return result;
}
}
long length = getLengthProperty(cx, thisObj);
if (length > 0) {
length--;
// Get the to-be-deleted property's value.
result = getElem(cx, thisObj, length);
// We don't need to delete the last property, because
// setLength does that for us.
} else {
result = Undefined.instance;
}
// necessary to match js even when length < 0; js pop will give a
// length property to any target it is called on.
setLengthProperty(cx, thisObj, length);
return result;
}
private static Object js_shift(Context cx, Scriptable thisObj,
Object[] args)
{
if (thisObj instanceof NativeArray) {
NativeArray na = (NativeArray) thisObj;
if (na.denseOnly && na.length > 0) {
na.length--;
Object result = na.dense[0];
System.arraycopy(na.dense, 1, na.dense, 0, (int)na.length);
na.dense[(int)na.length] = NOT_FOUND;
return result;
}
}
Object result;
long length = getLengthProperty(cx, thisObj);
if (length > 0) {
long i = 0;
length--;
// Get the to-be-deleted property's value.
result = getElem(cx, thisObj, i);
/*
* Slide down the array above the first element. Leave i
* set to point to the last element.
*/
if (length > 0) {
for (i = 1; i <= length; i++) {
Object temp = getElem(cx, thisObj, i);
setElem(cx, thisObj, i - 1, temp);
}
}
// We don't need to delete the last property, because
// setLength does that for us.
} else {
result = Undefined.instance;
}
setLengthProperty(cx, thisObj, length);
return result;
}
private static Object js_unshift(Context cx, Scriptable thisObj,
Object[] args)
{
if (thisObj instanceof NativeArray) {
NativeArray na = (NativeArray) thisObj;
if (na.denseOnly &&
na.ensureCapacity((int)na.length + args.length))
{
System.arraycopy(na.dense, 0, na.dense, args.length,
(int) na.length);
for (int i = 0; i < args.length; i++) {
na.dense[i] = args[i];
}
na.length += args.length;
return ScriptRuntime.wrapNumber(na.length);
}
}
long length = getLengthProperty(cx, thisObj);
int argc = args.length;
if (args.length > 0) {
/* Slide up the array to make room for args at the bottom */
if (length > 0) {
for (long last = length - 1; last >= 0; last--) {
Object temp = getElem(cx, thisObj, last);
setElem(cx, thisObj, last + argc, temp);
}
}
/* Copy from argv to the bottom of the array. */
for (int i = 0; i < args.length; i++) {
setElem(cx, thisObj, i, args[i]);
}
/* Follow Perl by returning the new array length. */
length += args.length;
return setLengthProperty(cx, thisObj, length);
}
return ScriptRuntime.wrapNumber(length);
}
private static Object js_splice(Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
{
NativeArray na = null;
boolean denseMode = false;
if (thisObj instanceof NativeArray) {
na = (NativeArray) thisObj;
denseMode = na.denseOnly;
}
/* create an empty Array to return. */
scope = getTopLevelScope(scope);
int argc = args.length;
if (argc == 0)
return ScriptRuntime.newObject(cx, scope, "Array", null);
long length = getLengthProperty(cx, thisObj);
/* Convert the first argument into a starting index. */
long begin = toSliceIndex(ScriptRuntime.toInteger(args[0]), length);
argc--;
/* Convert the second argument into count */
long count;
if (args.length == 1) {
count = length - begin;
} else {
double dcount = ScriptRuntime.toInteger(args[1]);
if (dcount < 0) {
count = 0;
} else if (dcount > (length - begin)) {
count = length - begin;
} else {
count = (long)dcount;
}
argc--;
}
long end = begin + count;
/* If there are elements to remove, put them into the return value. */
Object result;
if (count != 0) {
if (count == 1
&& (cx.getLanguageVersion() == Context.VERSION_1_2))
{
/*
* JS lacks "list context", whereby in Perl one turns the
* single scalar that's spliced out into an array just by
* assigning it to @single instead of $single, or by using it
* as Perl push's first argument, for instance.
*
* JS1.2 emulated Perl too closely and returned a non-Array for
* the single-splice-out case, requiring callers to test and
* wrap in [] if necessary. So JS1.3, default, and other
* versions all return an array of length 1 for uniformity.
*/
result = getElem(cx, thisObj, begin);
} else {
if (denseMode) {
int intLen = (int) (end - begin);
Object[] copy = new Object[intLen];
System.arraycopy(na.dense, (int) begin, copy, 0, intLen);
result = cx.newArray(scope, copy);
} else {
Scriptable resultArray = ScriptRuntime.newObject(cx, scope,
"Array", null);
for (long last = begin; last != end; last++) {
Object temp = getElem(cx, thisObj, last);
setElem(cx, resultArray, last - begin, temp);
}
result = resultArray;
}
}
} else { // (count == 0)
if (cx.getLanguageVersion() == Context.VERSION_1_2) {
/* Emulate C JS1.2; if no elements are removed, return undefined. */
result = Undefined.instance;
} else {
result = ScriptRuntime.newObject(cx, scope, "Array", null);
}
}
/* Find the direction (up or down) to copy and make way for argv. */
long delta = argc - count;
if (denseMode && length + delta < Integer.MAX_VALUE &&
na.ensureCapacity((int) (length + delta)))
{
System.arraycopy(na.dense, (int) end, na.dense,
(int) (begin + argc), (int) (length - end));
if (argc > 0) {
System.arraycopy(args, 2, na.dense, (int) begin, argc);
}
if (delta < 0) {
Arrays.fill(na.dense, (int) (length + delta), (int) length,
NOT_FOUND);
}
na.length = length + delta;
return result;
}
if (delta > 0) {
for (long last = length - 1; last >= end; last--) {
Object temp = getElem(cx, thisObj, last);
setElem(cx, thisObj, last + delta, temp);
}
} else if (delta < 0) {
for (long last = end; last < length; last++) {
Object temp = getElem(cx, thisObj, last);
setElem(cx, thisObj, last + delta, temp);
}
}
/* Copy from argv into the hole to complete the splice. */
int argoffset = args.length - argc;
for (int i = 0; i < argc; i++) {
setElem(cx, thisObj, begin + i, args[i + argoffset]);
}
/* Update length in case we deleted elements from the end. */
setLengthProperty(cx, thisObj, length + delta);
return result;
}
/*
* See Ecma 262v3 15.4.4.4
*/
private static Scriptable js_concat(Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
{
// create an empty Array to return.
scope = getTopLevelScope(scope);
Function ctor = ScriptRuntime.getExistingCtor(cx, scope, "Array");
Scriptable result = ctor.construct(cx, scope, ScriptRuntime.emptyArgs);
if (thisObj instanceof NativeArray && result instanceof NativeArray) {
NativeArray denseThis = (NativeArray) thisObj;
NativeArray denseResult = (NativeArray) result;
if (denseThis.denseOnly && denseResult.denseOnly) {
// First calculate length of resulting array
boolean canUseDense = true;
int length = (int) denseThis.length;
for (int i = 0; i < args.length && canUseDense; i++) {
if (args[i] instanceof NativeArray) {
// only try to use dense approach for Array-like
// objects that are actually NativeArrays
final NativeArray arg = (NativeArray) args[i];
canUseDense = arg.denseOnly;
length += arg.length;
} else {
length++;
}
}
if (canUseDense && denseResult.ensureCapacity(length)) {
System.arraycopy(denseThis.dense, 0, denseResult.dense,
0, (int) denseThis.length);
int cursor = (int) denseThis.length;
for (int i = 0; i < args.length && canUseDense; i++) {
if (args[i] instanceof NativeArray) {
NativeArray arg = (NativeArray) args[i];
System.arraycopy(arg.dense, 0,
denseResult.dense, cursor,
(int)arg.length);
cursor += (int)arg.length;
} else {
denseResult.dense[cursor++] = args[i];
}
}
denseResult.length = length;
return result;
}
}
}
long length;
long slot = 0;
/* Put the target in the result array; only add it as an array
* if it looks like one.
*/
if (ScriptRuntime.instanceOf(thisObj, ctor, cx)) {
length = getLengthProperty(cx, thisObj);
// Copy from the target object into the result
for (slot = 0; slot < length; slot++) {
Object temp = getElem(cx, thisObj, slot);
setElem(cx, result, slot, temp);
}
} else {
setElem(cx, result, slot++, thisObj);
}
/* Copy from the arguments into the result. If any argument
* has a numeric length property, treat it as an array and add
* elements separately; otherwise, just copy the argument.
*/
for (int i = 0; i < args.length; i++) {
if (ScriptRuntime.instanceOf(args[i], ctor, cx)) {
// ScriptRuntime.instanceOf => instanceof Scriptable
Scriptable arg = (Scriptable)args[i];
length = getLengthProperty(cx, arg);
for (long j = 0; j < length; j++, slot++) {
Object temp = getElem(cx, arg, j);
setElem(cx, result, slot, temp);
}
} else {
setElem(cx, result, slot++, args[i]);
}
}
return result;
}
private Scriptable js_slice(Context cx, Scriptable thisObj,
Object[] args)
{
Scriptable scope = getTopLevelScope(this);
Scriptable result = ScriptRuntime.newObject(cx, scope, "Array", null);
long length = getLengthProperty(cx, thisObj);
long begin, end;
if (args.length == 0) {
begin = 0;
end = length;
} else {
begin = toSliceIndex(ScriptRuntime.toInteger(args[0]), length);
if (args.length == 1) {
end = length;
} else {
end = toSliceIndex(ScriptRuntime.toInteger(args[1]), length);
}
}
for (long slot = begin; slot < end; slot++) {
Object temp = getElem(cx, thisObj, slot);
setElem(cx, result, slot - begin, temp);
}
return result;
}
private static long toSliceIndex(double value, long length) {
long result;
if (value < 0.0) {
if (value + length < 0.0) {
result = 0;
} else {
result = (long)(value + length);
}
} else if (value > length) {
result = length;
} else {
result = (long)value;
}
return result;
}
/**
* Implements the methods "indexOf" and "lastIndexOf".
*/
private Object indexOfHelper(Context cx, Scriptable thisObj,
Object[] args, boolean isLast)
{
Object compareTo = args.length > 0 ? args[0] : Undefined.instance;
long length = getLengthProperty(cx, thisObj);
long start;
if (isLast) {
// lastIndexOf
/*
* From http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Objects:Array:lastIndexOf
* The index at which to start searching backwards. Defaults to the
* array's length, i.e. the whole array will be searched. If the
* index is greater than or equal to the length of the array, the
* whole array will be searched. If negative, it is taken as the
* offset from the end of the array. Note that even when the index
* is negative, the array is still searched from back to front. If
* the calculated index is less than 0, -1 is returned, i.e. the
* array will not be searched.
*/
if (args.length < 2) {
// default
start = length-1;
} else {
start = ScriptRuntime.toInt32(ScriptRuntime.toNumber(args[1]));
if (start >= length)
start = length-1;
else if (start < 0)
start += length;
// Note that start may be negative, but that's okay
// as the result of -1 will fall out from the code below
}
} else {
// indexOf
/*
* From http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Objects:Array:indexOf
* The index at which to begin the search. Defaults to 0, i.e. the
* whole array will be searched. If the index is greater than or
* equal to the length of the array, -1 is returned, i.e. the array
* will not be searched. If negative, it is taken as the offset from
* the end of the array. Note that even when the index is negative,
* the array is still searched from front to back. If the calculated
* index is less than 0, the whole array will be searched.
*/
if (args.length < 2) {
// default
start = 0;
} else {
start = ScriptRuntime.toInt32(ScriptRuntime.toNumber(args[1]));
if (start < 0) {
start += length;
if (start < 0)
start = 0;
}
// Note that start may be > length-1, but that's okay
// as the result of -1 will fall out from the code below
}
}
if (thisObj instanceof NativeArray) {
NativeArray na = (NativeArray) thisObj;
if (na.denseOnly) {
if (isLast) {
for (int i=(int)start; i >= 0; i--) {
if (na.dense[i] != Scriptable.NOT_FOUND &&
ScriptRuntime.shallowEq(na.dense[i], compareTo))
{
return Long.valueOf(i);
}
}
} else {
for (int i=(int)start; i < length; i++) {
if (na.dense[i] != Scriptable.NOT_FOUND &&
ScriptRuntime.shallowEq(na.dense[i], compareTo))
{
return Long.valueOf(i);
}
}
}
return NEGATIVE_ONE;
}
}
if (isLast) {
for (long i=start; i >= 0; i--) {
if (ScriptRuntime.shallowEq(getElem(cx, thisObj, i), compareTo)) {
return new Long(i);
}
}
} else {
for (long i=start; i < length; i++) {
if (ScriptRuntime.shallowEq(getElem(cx, thisObj, i), compareTo)) {
return new Long(i);
}
}
}
return NEGATIVE_ONE;
}
/**
* Implements the methods "every", "filter", "forEach", "map", and "some".
*/
private Object iterativeMethod(Context cx, int id, Scriptable scope,
Scriptable thisObj, Object[] args)
{
Object callbackArg = args.length > 0 ? args[0] : Undefined.instance;
if (callbackArg == null || !(callbackArg instanceof Function)) {
throw ScriptRuntime.notFunctionError(callbackArg);
}
Function f = (Function) callbackArg;
Scriptable parent = ScriptableObject.getTopLevelScope(f);
Scriptable thisArg;
if (args.length < 2 || args[1] == null || args[1] == Undefined.instance)
{
thisArg = parent;
} else {
thisArg = ScriptRuntime.toObject(cx, scope, args[1]);
}
long length = getLengthProperty(cx, thisObj);
Scriptable array = ScriptRuntime.newObject(cx, scope, "Array", null);
long j=0;
for (long i=0; i < length; i++) {
Object[] innerArgs = new Object[3];
Object elem = getRawElem(thisObj, i);
if (elem == Scriptable.NOT_FOUND) {
continue;
}
innerArgs[0] = elem;
innerArgs[1] = Long.valueOf(i);
innerArgs[2] = thisObj;
Object result = f.call(cx, parent, thisArg, innerArgs);
switch (id) {
case Id_every:
if (!ScriptRuntime.toBoolean(result))
return Boolean.FALSE;
break;
case Id_filter:
if (ScriptRuntime.toBoolean(result))
setElem(cx, array, j++, innerArgs[0]);
break;
case Id_forEach:
break;
case Id_map:
setElem(cx, array, i, result);
break;
case Id_some:
if (ScriptRuntime.toBoolean(result))
return Boolean.TRUE;
break;
}
}
switch (id) {
case Id_every:
return Boolean.TRUE;
case Id_filter:
case Id_map:
return array;
case Id_some:
return Boolean.FALSE;
case Id_forEach:
default:
return Undefined.instance;
}
}
/**
* Implements the methods "reduce" and "reduceRight".
*/
private Object reduceMethod(Context cx, int id, Scriptable scope,
Scriptable thisObj, Object[] args)
{
Object callbackArg = args.length > 0 ? args[0] : Undefined.instance;
if (callbackArg == null || !(callbackArg instanceof Function)) {
throw ScriptRuntime.notFunctionError(callbackArg);
}
Function f = (Function) callbackArg;
Scriptable parent = ScriptableObject.getTopLevelScope(f);
long length = getLengthProperty(cx, thisObj);
// offset hack to serve both reduce and reduceRight with the same loop
long offset = id == Id_reduceRight ? length - 1 : 0;
Object value = args.length > 1 ? args[1] : Scriptable.NOT_FOUND;
for (long i = 0; i < length; i++) {
Object elem = getRawElem(thisObj, Math.abs(i - offset));
if (elem == Scriptable.NOT_FOUND) {
continue;
}
if (value == Scriptable.NOT_FOUND) {
// no initial value passed, use first element found as inital value
value = elem;
} else {
Object[] innerArgs = new Object[4];
innerArgs[0] = value;
innerArgs[1] = elem;
innerArgs[2] = new Long(i);
innerArgs[3] = thisObj;
value = f.call(cx, parent, parent, innerArgs);
}
}
if (value == Scriptable.NOT_FOUND) {
// reproduce spidermonkey error message
throw Context.reportRuntimeError0("msg.empty.array.reduce");
}
return value;
}
// #string_id_map#
@Override
protected int findPrototypeId(String s)
{
int id;
// #generated# Last update: 2005-09-26 15:47:42 EDT
L0: { id = 0; String X = null; int c;
L: switch (s.length()) {
case 3: c=s.charAt(0);
if (c=='m') { if (s.charAt(2)=='p' && s.charAt(1)=='a') {id=Id_map; break L0;} }
else if (c=='p') { if (s.charAt(2)=='p' && s.charAt(1)=='o') {id=Id_pop; break L0;} }
break L;
case 4: switch (s.charAt(2)) {
case 'i': X="join";id=Id_join; break L;
case 'm': X="some";id=Id_some; break L;
case 'r': X="sort";id=Id_sort; break L;
case 's': X="push";id=Id_push; break L;
} break L;
case 5: c=s.charAt(1);
if (c=='h') { X="shift";id=Id_shift; }
else if (c=='l') { X="slice";id=Id_slice; }
else if (c=='v') { X="every";id=Id_every; }
break L;
case 6: c=s.charAt(0);
if (c=='c') { X="concat";id=Id_concat; }
else if (c=='f') { X="filter";id=Id_filter; }
else if (c=='s') { X="splice";id=Id_splice; }
else if (c=='r') { X="reduce";id=Id_reduce; }
break L;
case 7: switch (s.charAt(0)) {
case 'f': X="forEach";id=Id_forEach; break L;
case 'i': X="indexOf";id=Id_indexOf; break L;
case 'r': X="reverse";id=Id_reverse; break L;
case 'u': X="unshift";id=Id_unshift; break L;
} break L;
case 8: c=s.charAt(3);
if (c=='o') { X="toSource";id=Id_toSource; }
else if (c=='t') { X="toString";id=Id_toString; }
break L;
case 11: c=s.charAt(0);
if (c=='c') { X="constructor";id=Id_constructor; }
else if (c=='l') { X="lastIndexOf";id=Id_lastIndexOf; }
else if (c=='r') { X="reduceRight";id=Id_reduceRight; }
break L;
case 14: X="toLocaleString";id=Id_toLocaleString; break L;
}
if (X!=null && X!=s && !X.equals(s)) id = 0;
}
// #/generated#
return id;
}
private static final int
Id_constructor = 1,
Id_toString = 2,
Id_toLocaleString = 3,
Id_toSource = 4,
Id_join = 5,
Id_reverse = 6,
Id_sort = 7,
Id_push = 8,
Id_pop = 9,
Id_shift = 10,
Id_unshift = 11,
Id_splice = 12,
Id_concat = 13,
Id_slice = 14,
Id_indexOf = 15,
Id_lastIndexOf = 16,
Id_every = 17,
Id_filter = 18,
Id_forEach = 19,
Id_map = 20,
Id_some = 21,
Id_reduce = 22,
Id_reduceRight = 23,
MAX_PROTOTYPE_ID = 23;
// #/string_id_map#
private static final int
ConstructorId_join = -Id_join,
ConstructorId_reverse = -Id_reverse,
ConstructorId_sort = -Id_sort,
ConstructorId_push = -Id_push,
ConstructorId_pop = -Id_pop,
ConstructorId_shift = -Id_shift,
ConstructorId_unshift = -Id_unshift,
ConstructorId_splice = -Id_splice,
ConstructorId_concat = -Id_concat,
ConstructorId_slice = -Id_slice,
ConstructorId_indexOf = -Id_indexOf,
ConstructorId_lastIndexOf = -Id_lastIndexOf,
ConstructorId_every = -Id_every,
ConstructorId_filter = -Id_filter,
ConstructorId_forEach = -Id_forEach,
ConstructorId_map = -Id_map,
ConstructorId_some = -Id_some,
ConstructorId_reduce = -Id_reduce,
ConstructorId_reduceRight = -Id_reduceRight;
/**
* Internal representation of the JavaScript array's length property.
*/
private long length;
/**
* Fast storage for dense arrays. Sparse arrays will use the superclass's
* hashtable storage scheme.
*/
private Object[] dense;
/**
* True if all numeric properties are stored in <code>dense</code>.
*/
private boolean denseOnly;
/**
* The maximum size of <code>dense</code> that will be allocated initially.
*/
private static int maximumInitialCapacity = 10000;
/**
* The default capacity for <code>dense</code>.
*/
private static final int DEFAULT_INITIAL_CAPACITY = 10;
/**
* The factor to grow <code>dense</code> by.
*/
private static final double GROW_FACTOR = 1.5;
private static final int MAX_PRE_GROW_SIZE = (int)(Integer.MAX_VALUE / GROW_FACTOR);
}
| Fix warning.
| src/org/mozilla/javascript/NativeArray.java | Fix warning. |
|
Java | agpl-3.0 | 91ce7bba6c2cb5eda5e6810b54dde10966506834 | 0 | Spirals-Team/librepair,fermadeiral/librepair,fermadeiral/librepair,fermadeiral/librepair,fermadeiral/librepair,Spirals-Team/librepair,Spirals-Team/librepair,Spirals-Team/librepair,Spirals-Team/librepair,fermadeiral/librepair | package fr.inria.spirals.jtravis.helpers;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import fr.inria.spirals.jtravis.entities.Build;
import fr.inria.spirals.jtravis.entities.Config;
import fr.inria.spirals.jtravis.entities.Commit;
import fr.inria.spirals.jtravis.entities.Job;
import fr.inria.spirals.jtravis.entities.Repository;
import okhttp3.ResponseBody;
import org.kohsuke.github.GHCommit;
import org.kohsuke.github.GHCommitPointer;
import org.kohsuke.github.GHPullRequest;
import org.kohsuke.github.GHRateLimit;
import org.kohsuke.github.GHRepository;
import org.kohsuke.github.GitHub;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* The helper to deal with Build objects
*
* @author Simon Urli
*/
public class BuildHelper extends AbstractHelper {
public static final String BUILD_NAME = "builds";
public static final String BUILD_ENDPOINT = BUILD_NAME+"/";
private static BuildHelper instance;
private BuildHelper() {
super();
}
private static BuildHelper getInstance() {
if (instance == null) {
instance = new BuildHelper();
}
return instance;
}
public static Build getBuildFromId(int id, Repository parentRepo) {
String resourceUrl = TRAVIS_API_ENDPOINT+BUILD_ENDPOINT+id;
try {
String response = getInstance().get(resourceUrl);
JsonParser parser = new JsonParser();
JsonObject allAnswer = parser.parse(response).getAsJsonObject();
JsonObject buildJSON = allAnswer.getAsJsonObject("build");
Build build = createGson().fromJson(buildJSON, Build.class);
JsonObject commitJSON = allAnswer.getAsJsonObject("commit");
Commit commit = CommitHelper.getCommitFromJsonElement(commitJSON);
build.setCommit(commit);
if (parentRepo != null) {
build.setRepository(parentRepo);
}
JsonObject configJSON = buildJSON.getAsJsonObject("config");
Config config = ConfigHelper.getConfigFromJsonElement(configJSON);
build.setConfig(config);
JsonArray arrayJobs = allAnswer.getAsJsonArray("jobs");
for (JsonElement jobJSONElement : arrayJobs) {
Job job = JobHelper.createJobFromJsonElement((JsonObject)jobJSONElement);
build.addJob(job);
}
return build;
} catch (IOException e) {
AbstractHelper.LOGGER.warn("Error when getting build id "+id+" : "+e.getMessage());
return null;
}
}
/**
* This is a recursive method allowing to get build from a slug.
*
* @param slug The slug where to get the builds
* @param result The list result to aggregate
* @param limitDate If given, the date limit to get builds: all builds *before* this date are considered
* @param after_number Used for pagination: multiple requests may have to be made to reach the final date
* @param pullBuild Travis does not mix builds from PR and builds from push. When set to true this mean we get builds from PR.
*/
private static void getBuildsFromSlugRecursively(String slug, List<Build> result, Date limitDate, int after_number, boolean pullBuild) {
Map<Integer, Commit> commits = new HashMap<Integer,Commit>();
String resourceUrl = TRAVIS_API_ENDPOINT+RepositoryHelper.REPO_ENDPOINT+slug+"/"+BUILD_NAME;
if (pullBuild) {
resourceUrl += "?event_type=pull_request";
} else {
resourceUrl += "?event_type=push";
}
if (after_number > 0) {
resourceUrl += "&after_number="+after_number;
}
boolean dateReached = false;
try {
String response = getInstance().get(resourceUrl);
JsonParser parser = new JsonParser();
JsonObject allAnswer = parser.parse(response).getAsJsonObject();
JsonArray commitsArray = allAnswer.getAsJsonArray("commits");
for (JsonElement commitJson : commitsArray) {
Commit commit = createGson().fromJson(commitJson, Commit.class);
commits.put(commit.getId(), commit);
}
JsonArray buildArray = allAnswer.getAsJsonArray("builds");
int lastBuildId = 0;
for (JsonElement buildJson : buildArray) {
Build build = createGson().fromJson(buildJson, Build.class);
if ((limitDate == null) || (build.getFinishedAt() == null) || (build.getFinishedAt().after(limitDate))) {
int commitId = build.getCommitId();
if (commits.containsKey(commitId)) {
build.setCommit(commits.get(commitId));
}
if (lastBuildId < build.getId()) {
lastBuildId = build.getId();
}
result.add(build);
} else {
dateReached = true;
break;
}
}
if (buildArray.size() == 0) {
dateReached = true;
}
if (dateReached && pullBuild) {
return;
}
if (dateReached && !pullBuild) {
getBuildsFromSlugRecursively(slug, result, limitDate, 0, true);
}
if (limitDate == null) {
getBuildsFromSlugRecursively(slug, result, limitDate, 0, true);
}
if (limitDate != null && !dateReached) {
getBuildsFromSlugRecursively(slug, result, limitDate, lastBuildId, pullBuild);
}
} catch (IOException e) {
AbstractHelper.LOGGER.warn("Error when getting list of builds from slug "+slug+" : "+e.getMessage());
}
}
public static List<Build> getBuildsFromSlugWithLimitDate(String slug, Date limitDate) {
List<Build> result = new ArrayList<Build>();
getBuildsFromSlugRecursively(slug, result, limitDate, 0, false);
return result;
}
public static List<Build> getBuildsFromSlug(String slug) {
return getBuildsFromSlugWithLimitDate(slug, null);
}
public static List<Build> getBuildsFromRepositoryWithLimitDate(Repository repository, Date limitDate) {
List<Build> result = new ArrayList<Build>();
getBuildsFromSlugRecursively(repository.getSlug(), result, limitDate, 0, false);
for (Build b : result) {
b.setRepository(repository);
}
return result;
}
public static List<Build> getBuildsFromRepositoryWithLimitDate(Repository repository) {
return getBuildsFromRepositoryWithLimitDate(repository, null);
}
}
| jtravis/src/main/java/fr/inria/spirals/jtravis/helpers/BuildHelper.java | package fr.inria.spirals.jtravis.helpers;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import fr.inria.spirals.jtravis.entities.Build;
import fr.inria.spirals.jtravis.entities.Config;
import fr.inria.spirals.jtravis.entities.Commit;
import fr.inria.spirals.jtravis.entities.Job;
import fr.inria.spirals.jtravis.entities.Repository;
import okhttp3.ResponseBody;
import org.kohsuke.github.GHCommit;
import org.kohsuke.github.GHCommitPointer;
import org.kohsuke.github.GHPullRequest;
import org.kohsuke.github.GHRateLimit;
import org.kohsuke.github.GHRepository;
import org.kohsuke.github.GitHub;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* The helper to deal with Build objects
*
* @author Simon Urli
*/
public class BuildHelper extends AbstractHelper {
public static final String BUILD_NAME = "builds";
public static final String BUILD_ENDPOINT = BUILD_NAME+"/";
private static BuildHelper instance;
private BuildHelper() {
super();
}
private static BuildHelper getInstance() {
if (instance == null) {
instance = new BuildHelper();
}
return instance;
}
public static Build getBuildFromId(int id, Repository parentRepo) {
String resourceUrl = TRAVIS_API_ENDPOINT+BUILD_ENDPOINT+id;
try {
String response = getInstance().get(resourceUrl);
JsonParser parser = new JsonParser();
JsonObject allAnswer = parser.parse(response).getAsJsonObject();
JsonObject buildJSON = allAnswer.getAsJsonObject("build");
Build build = createGson().fromJson(buildJSON, Build.class);
JsonObject commitJSON = allAnswer.getAsJsonObject("commit");
Commit commit = CommitHelper.getCommitFromJsonElement(commitJSON);
build.setCommit(commit);
if (parentRepo != null) {
build.setRepository(parentRepo);
}
JsonObject configJSON = buildJSON.getAsJsonObject("config");
Config config = ConfigHelper.getConfigFromJsonElement(configJSON);
build.setConfig(config);
JsonArray arrayJobs = allAnswer.getAsJsonArray("jobs");
for (JsonElement jobJSONElement : arrayJobs) {
Job job = JobHelper.createJobFromJsonElement((JsonObject)jobJSONElement);
build.addJob(job);
}
return build;
} catch (IOException e) {
AbstractHelper.LOGGER.warn("Error when getting build id "+id+" : "+e.getMessage());
return null;
}
}
/**
* This is a recursive method allowing to get build from a slug.
*
* @param slug The slug where to get the builds
* @param result The list result to aggregate
* @param limitDate If given, the date limit to get builds: all builds *before* this date are considered
* @param after_number Used for pagination: multiple requests may have to be made to reach the final date
* @param pullBuild Travis does not mix builds from PR and builds from push. When set to true this mean we get builds from PR.
*/
private static void getBuildsFromSlugRecursively(String slug, List<Build> result, Date limitDate, int after_number, boolean pullBuild) {
Map<Integer, Commit> commits = new HashMap<Integer,Commit>();
String resourceUrl = TRAVIS_API_ENDPOINT+RepositoryHelper.REPO_ENDPOINT+slug+"/"+BUILD_NAME;
if (pullBuild) {
resourceUrl += "?event_type=pull_request";
} else {
resourceUrl += "?event_type=push";
}
if (after_number > 0) {
resourceUrl += "&after_number="+after_number;
}
boolean dateReached = false;
try {
String response = getInstance().get(resourceUrl);
JsonParser parser = new JsonParser();
JsonObject allAnswer = parser.parse(response).getAsJsonObject();
JsonArray commitsArray = allAnswer.getAsJsonArray("commits");
for (JsonElement commitJson : commitsArray) {
Commit commit = createGson().fromJson(commitJson, Commit.class);
commits.put(commit.getId(), commit);
}
JsonArray buildArray = allAnswer.getAsJsonArray("builds");
int lastBuildId = 0;
for (JsonElement buildJson : buildArray) {
Build build = createGson().fromJson(buildJson, Build.class);
if ((limitDate == null) || (build.getFinishedAt() == null) || (build.getFinishedAt().after(limitDate))) {
int commitId = build.getCommitId();
if (commits.containsKey(commitId)) {
build.setCommit(commits.get(commitId));
}
if (lastBuildId < build.getId()) {
lastBuildId = build.getId();
}
result.add(build);
} else {
dateReached = true;
break;
}
}
if (dateReached && pullBuild) {
return;
}
if (dateReached && !pullBuild) {
getBuildsFromSlugRecursively(slug, result, limitDate, 0, true);
}
if (limitDate == null) {
getBuildsFromSlugRecursively(slug, result, limitDate, 0, true);
}
if (limitDate != null && !dateReached) {
getBuildsFromSlugRecursively(slug, result, limitDate, lastBuildId, pullBuild);
}
} catch (IOException e) {
AbstractHelper.LOGGER.warn("Error when getting list of builds from slug "+slug+" : "+e.getMessage());
}
}
public static List<Build> getBuildsFromSlugWithLimitDate(String slug, Date limitDate) {
List<Build> result = new ArrayList<Build>();
getBuildsFromSlugRecursively(slug, result, limitDate, 0, false);
return result;
}
public static List<Build> getBuildsFromSlug(String slug) {
return getBuildsFromSlugWithLimitDate(slug, null);
}
public static List<Build> getBuildsFromRepositoryWithLimitDate(Repository repository, Date limitDate) {
List<Build> result = new ArrayList<Build>();
getBuildsFromSlugRecursively(repository.getSlug(), result, limitDate, 0, false);
for (Build b : result) {
b.setRepository(repository);
}
return result;
}
public static List<Build> getBuildsFromRepositoryWithLimitDate(Repository repository) {
return getBuildsFromRepositoryWithLimitDate(repository, null);
}
}
| jTravis: fix another bug if the result is empty
| jtravis/src/main/java/fr/inria/spirals/jtravis/helpers/BuildHelper.java | jTravis: fix another bug if the result is empty |
|
Java | agpl-3.0 | a7561f0e8dcbe9f595db2f135119b83af99c24c8 | 0 | BloatIt/bloatit,BloatIt/bloatit,BloatIt/bloatit,BloatIt/bloatit,BloatIt/bloatit | package com.bloatit.framework.webprocessor.components.meta;
/**
* <p>
* HtmlMixedText are used to display a text with embed html element.
* </p>
* <p>
* The main use is to insert link in a translated text flow. The text must
* contains tag like that:
* </p>
* <code>Hello, you can <0:follow this link:comment>.</code>
* <p>
* In this exemple <0:follow this link> will be replaced by the parameters at
* the index 0. The second field is is a comment, the text . If a third text
* will be add to the node.
* </p>
*/
public class HtmlMixedText extends HtmlBranch {
public HtmlMixedText(String content, final HtmlBranch... parameters) {
content = " " + content; // Handle the cast where it starts by a tag
final String[] split = content.split("<[0-9]+(:[^>]+)*>");
int index = 0;
for (final String string : split) {
if (index == 0) {
add(new XmlText(string.substring(1, string.length())));
} else {
add(new XmlText(string));
}
index += string.length();
// If it not the end, replace a tag
final int startIndex = content.indexOf("<", index);
if (startIndex != -1) {
final int endIndex = content.indexOf(">", index);
parseTag(content.substring(startIndex + 1, endIndex), parameters);
index = endIndex + 1;
}
}
}
public void parseTag(final String tag, final HtmlBranch parameters[]) {
final String[] split = tag.split(":");
if (split.length < 1) {
add(new XmlText(" ### Invalid tag '" + tag + "'. Not enough content ### "));
return;
}
final int paramIndex = Integer.valueOf(split[0]);
// Check out of bound
if (paramIndex >= parameters.length) {
add(new XmlText(" ### Invalid index '" + paramIndex + "' in tag '" + tag + "'. Param length: " + parameters.length + " ### "));
return;
}
final HtmlBranch node = (HtmlBranch) parameters[paramIndex].clone();
if (split.length >= 3) {
node.addText(split[2]);
}
add(node);
}
}
| main/src/main/java/com/bloatit/framework/webprocessor/components/meta/HtmlMixedText.java | package com.bloatit.framework.webprocessor.components.meta;
/**
* <p>
* HtmlMixedText are used to display a text with embed html element.
* </p>
* <p>
* The main use is to insert link in a translated text flow. The text must
* contains tag like that:
* </p>
* <code>Hello, you can <0:follow this link:comment>.</code>
* <p>
* In this exemple <0:follow this link> will be replaced by the parameters at
* the index 0. The second field is is a comment, the text . If a third text
* will be add to the node.
* </p>
*/
public class HtmlMixedText extends HtmlBranch {
public HtmlMixedText(final String content, final HtmlBranch... parameters) {
final String[] split = content.split("<[0-9]+(:[^>]+)*>");
int index = 0;
for (final String string : split) {
add(new XmlText(string));
index += string.length();
// If it not the end, replace a tag
final int startIndex = content.indexOf("<", index);
if (startIndex != -1) {
final int endIndex = content.indexOf(">", index);
parseTag(content.substring(startIndex + 1, endIndex), parameters);
index = endIndex + 1;
}
}
}
public void parseTag(final String tag, final HtmlBranch parameters[]) {
final String[] split = tag.split(":");
if (split.length < 1) {
add(new XmlText(" ### Invalid tag '" + tag + "'. Not enough content ### "));
return;
}
final int paramIndex = Integer.valueOf(split[0]);
// Check out of bound
if (paramIndex >= parameters.length) {
add(new XmlText(" ### Invalid index '" + paramIndex + "' in tag '" + tag + "'. Param length: " + parameters.length + " ### "));
return;
}
final HtmlBranch node = (HtmlBranch) parameters[paramIndex].clone();
if (split.length >= 3) {
node.addText(split[2]);
}
add(node);
}
}
| Fixing HtmlMixedText to properly handle strings STARTING with a markup
| main/src/main/java/com/bloatit/framework/webprocessor/components/meta/HtmlMixedText.java | Fixing HtmlMixedText to properly handle strings STARTING with a markup |
|
Java | lgpl-2.1 | 8d47731cf705d778a323cbb5637453e426fa7353 | 0 | geotools/geotools,geotools/geotools,geotools/geotools,geotools/geotools | /*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2002-2008, Open Source Geospatial Foundation (OSGeo)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Created on 03 July 2002, 10:21
*/
package org.geotools.filter;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.logging.Logger;
import org.geotools.factory.CommonFactoryFinder;
import org.geotools.referencing.CRS;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.LineString;
import org.locationtech.jts.geom.LinearRing;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.geom.Polygon;
import org.locationtech.jts.geom.TopologyException;
import org.opengis.filter.FilterFactory2;
import org.opengis.filter.expression.Expression;
import org.opengis.filter.expression.PropertyName;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.helpers.NamespaceSupport;
/**
* parsez short sections of gml for use in expressions and filters Hopefully we can get away without
* a full parser here.
*
* @author iant
* @author Niels Charlier
*/
public final class ExpressionDOMParser {
/** The logger for the filter module. */
private static final Logger LOGGER =
org.geotools.util.logging.Logging.getLogger(ExpressionDOMParser.class);
/** Factory for creating filters. */
private FilterFactory2 ff;
/** Factory for creating geometry objects */
private static GeometryFactory gfac = new GeometryFactory();
/** number of coordinates in a box */
private static final int NUM_BOX_COORDS = 5;
/** Creates a new instance of ExpressionXmlParser */
private ExpressionDOMParser() {
this(CommonFactoryFinder.getFilterFactory2(null));
LOGGER.finer("made new logic factory");
}
/** Constructor injection */
public ExpressionDOMParser(FilterFactory2 factory) {
ff = factory != null ? factory : CommonFactoryFinder.getFilterFactory2(null);
}
/** Setter injection */
public void setFilterFactory(FilterFactory2 factory) {
ff = factory;
}
private static NamespaceSupport getNameSpaces(Node node) {
NamespaceSupport namespaces = new NamespaceSupport();
while (node != null) {
NamedNodeMap atts = node.getAttributes();
if (atts != null) {
for (int i = 0; i < atts.getLength(); i++) {
Node att = atts.item(i);
if (att.getNamespaceURI() != null
&& att.getNamespaceURI().equals("http://www.w3.org/2000/xmlns/")
&& namespaces.getURI(att.getLocalName()) == null) {
namespaces.declarePrefix(att.getLocalName(), att.getNodeValue());
}
}
}
node = node.getParentNode();
}
return namespaces;
}
/**
* @deprecated Please use ExpressionDOMParser.expression
* @param root
*/
public static Expression parseExpression(Node root) {
ExpressionDOMParser parser = new ExpressionDOMParser();
return parser.expression(root);
}
/**
* parses an expression for a filter.
*
* @param root the root node to parse, should be an filter expression.
* @return the geotools representation of the expression held in the node.
*/
public Expression expression(Node root) {
// NodeList children = root.getChildNodes();
// LOGGER.finest("children "+children);
if ((root == null) || (root.getNodeType() != Node.ELEMENT_NODE)) {
LOGGER.finer("bad node input ");
return null;
}
LOGGER.finer("processing root " + root.getLocalName());
Node child = root;
String childName =
(child.getLocalName() != null) ? child.getLocalName() : child.getNodeName();
if (childName.indexOf(':') != -1) {
// the DOM parser wasnt properly set to handle namespaces...
childName = childName.substring(childName.indexOf(':') + 1);
}
if (childName.equalsIgnoreCase("Literal")) {
LOGGER.finer("processing literal " + child);
NodeList kidList = child.getChildNodes();
LOGGER.finest("literal elements (" + kidList.getLength() + ") " + kidList.toString());
for (int i = 0; i < kidList.getLength(); i++) {
Node kid = kidList.item(i);
LOGGER.finest("kid " + i + " " + kid);
if (kid == null) {
LOGGER.finest("Skipping ");
continue;
}
if (kid.getNodeValue() == null) {
/* it might be a gml string so we need to convert it into
* a geometry this is a bit tricky since our standard
* gml parser is SAX based and we're a DOM here.
*/
LOGGER.finer(
"node " + kid.getNodeValue() + " namespace " + kid.getNamespaceURI());
LOGGER.fine("a literal gml string?");
try {
Geometry geom = parseGML(kid);
if (geom != null) {
LOGGER.finer("built a " + geom.getGeometryType() + " from gml");
LOGGER.finer("\tpoints: " + geom.getNumPoints());
} else {
LOGGER.finer("got a null geometry back from gml parser");
}
return ff.literal(geom);
} catch (IllegalFilterException ife) {
LOGGER.warning("Problem building GML/JTS object: " + ife);
}
return null;
}
// CDATA shouldn't be interpretted
if (kid.getNodeType() != Node.CDATA_SECTION_NODE
&& kid.getNodeValue().trim().length() == 0) {
LOGGER.finest("empty text element");
continue;
}
// debuging only
/*switch(kid.getNodeType()){
case Node.ELEMENT_NODE:
LOGGER.finer("element :"+kid);
break;
case Node.TEXT_NODE:
LOGGER.finer("text :"+kid);
break;
case Node.ATTRIBUTE_NODE:
LOGGER.finer("Attribute :"+kid);
break;
case Node.CDATA_SECTION_NODE:
LOGGER.finer("Cdata :"+kid);
break;
case Node.COMMENT_NODE:
LOGGER.finer("comment :"+kid);
break;
} */
String nodeValue = kid.getNodeValue();
LOGGER.finer("processing " + nodeValue);
try {
// always store internal values as strings. We might lose info otherwise.
return ff.literal(nodeValue);
} catch (IllegalFilterException ife) {
LOGGER.finer("Unable to build expression " + ife);
return null;
}
}
// creates an empty literal expression if there is nothing inside the literal
return ff.literal("");
}
if (childName.equalsIgnoreCase("add")) {
try {
LOGGER.fine("processing an Add");
// Node left = null;
// Node right = null;
Node value = child.getFirstChild();
while (value.getNodeType() != Node.ELEMENT_NODE) {
value = value.getNextSibling();
}
LOGGER.finer("add left value -> " + value + "<-");
Expression left = parseExpression(value);
value = value.getNextSibling();
while (value.getNodeType() != Node.ELEMENT_NODE) {
value = value.getNextSibling();
}
LOGGER.finer("add right value -> " + value + "<-");
Expression right = parseExpression(value);
return ff.add(left, right);
} catch (IllegalFilterException ife) {
LOGGER.warning("Unable to build expression " + ife);
return null;
}
}
if (childName.equalsIgnoreCase("sub")) {
try {
// NodeList kids = child.getChildNodes();
Node value = child.getFirstChild();
while (value.getNodeType() != Node.ELEMENT_NODE) {
value = value.getNextSibling();
}
LOGGER.finer("add left value -> " + value + "<-");
Expression left = parseExpression(value);
value = value.getNextSibling();
while (value.getNodeType() != Node.ELEMENT_NODE) {
value = value.getNextSibling();
}
LOGGER.finer("add right value -> " + value + "<-");
Expression right = parseExpression(value);
return ff.subtract(left, right);
} catch (IllegalFilterException ife) {
LOGGER.warning("Unable to build expression " + ife);
return null;
}
}
if (childName.equalsIgnoreCase("mul")) {
try {
// NodeList kids = child.getChildNodes();
Node value = child.getFirstChild();
while (value.getNodeType() != Node.ELEMENT_NODE) {
value = value.getNextSibling();
}
LOGGER.finer("add left value -> " + value + "<-");
Expression left = parseExpression(value);
value = value.getNextSibling();
while (value.getNodeType() != Node.ELEMENT_NODE) {
value = value.getNextSibling();
}
LOGGER.finer("add right value -> " + value + "<-");
Expression right = parseExpression(value);
return ff.multiply(left, right);
} catch (IllegalFilterException ife) {
LOGGER.warning("Unable to build expression " + ife);
return null;
}
}
if (childName.equalsIgnoreCase("div")) {
try {
Node value = child.getFirstChild();
while (value.getNodeType() != Node.ELEMENT_NODE) {
value = value.getNextSibling();
}
LOGGER.finer("add left value -> " + value + "<-");
Expression left = parseExpression(value);
value = value.getNextSibling();
while (value.getNodeType() != Node.ELEMENT_NODE) {
value = value.getNextSibling();
}
LOGGER.finer("add right value -> " + value + "<-");
Expression right = parseExpression(value);
return ff.divide(left, right);
} catch (IllegalFilterException ife) {
LOGGER.warning("Unable to build expression " + ife);
return null;
}
}
if (childName.equalsIgnoreCase("PropertyName")) {
try {
// JD: trim whitespace here
String value = child.getFirstChild().getNodeValue();
value = value != null ? value.trim() : value;
PropertyName attribute = ff.property(value, getNameSpaces(root));
// attribute.setAttributePath(child.getFirstChild().getNodeValue());
return attribute;
} catch (IllegalFilterException ife) {
LOGGER.warning("Unable to build expression: " + ife);
return null;
}
}
if (childName.equalsIgnoreCase("Function")) {
Element param = (Element) child;
NamedNodeMap map = param.getAttributes();
String funcName = null;
for (int k = 0; k < map.getLength(); k++) {
String res = map.item(k).getNodeValue();
String name = map.item(k).getLocalName();
if (name == null) {
name = map.item(k).getNodeName();
}
if (name.indexOf(':') != -1) {
// the DOM parser was not properly set to handle namespaces...
name = name.substring(name.indexOf(':') + 1);
}
LOGGER.fine("attribute " + name + " with value of " + res);
if (name.equalsIgnoreCase("name")) {
funcName = res;
}
}
if (funcName == null) {
LOGGER.severe("failed to find a function name in " + child);
return null;
}
ArrayList<Expression> args = new ArrayList<Expression>();
Node value = child.getFirstChild();
ARGS:
while (value != null) {
while (value.getNodeType() != Node.ELEMENT_NODE) {
value = value.getNextSibling();
if (value == null) break ARGS;
}
args.add(parseExpression(value));
value = value.getNextSibling();
}
Expression[] array = args.toArray(new Expression[0]);
return ff.function(funcName, array);
}
if (child.getNodeType() == Node.TEXT_NODE) {
LOGGER.finer("processing a text node " + root.getNodeValue());
String nodeValue = root.getNodeValue();
LOGGER.finer("Text name " + nodeValue);
// see if it's an int
try {
try {
Integer intLiteral = Integer.valueOf(nodeValue);
return ff.literal(intLiteral);
} catch (NumberFormatException e) {
/* really empty */
}
try {
Double doubleLit = new Double(nodeValue);
return ff.literal(doubleLit);
} catch (NumberFormatException e) {
/* really empty */
}
return ff.literal(nodeValue);
} catch (IllegalFilterException ife) {
LOGGER.finer("Unable to build expression " + ife);
}
}
return null;
}
/**
* @deprecated Please use ExpressionDOMParser.gml
* @param root
* @return the java representation of the geometry contained in root.
*/
public static Geometry parseGML(Node root) {
ExpressionDOMParser parser = new ExpressionDOMParser();
return parser.gml(root);
}
public Geometry gml(Node root) {
// look for the SRS name, if available
Node srsNameNode = root.getAttributes().getNamedItem("srsName");
CoordinateReferenceSystem crs = null;
if (srsNameNode != null) {
String srs = srsNameNode.getTextContent();
try {
crs = CRS.decode(srs);
} catch (Exception e) {
LOGGER.warning("Failed to parse the specified SRS " + srs);
}
}
// parse the geometry
Geometry g = _gml(root);
// force the crs if necessary
if (crs != null) {
g.setUserData(crs);
}
return g;
}
/**
* Parses the gml of this node to jts.
*
* @param root the parent node of the gml to parse.
* @return the java representation of the geometry contained in root.
*/
private Geometry _gml(Node root) {
LOGGER.finer("processing gml " + root);
List coordList;
Node child = root;
// Jesus I hate DOM. I have no idea why this was checking for localname
// and then nodename - lead to non-deterministic behavior, that for
// some reason only failed if the filter parser was used within the
// SLDparser. I really would like that class redone, so we don't have
// to use this crappy DOM GML parser.
String childName = child.getNodeName();
if (childName == null) {
childName = child.getLocalName();
}
if (!childName.startsWith("gml:")) {
childName = "gml:" + childName;
}
if (childName.equalsIgnoreCase("gml:box")) {
coordList =
new ExpressionDOMParser(CommonFactoryFinder.getFilterFactory2()).coords(child);
org.locationtech.jts.geom.Envelope env = new org.locationtech.jts.geom.Envelope();
for (int i = 0; i < coordList.size(); i++) {
env.expandToInclude((Coordinate) coordList.get(i));
}
Coordinate[] coords = new Coordinate[NUM_BOX_COORDS];
coords[0] = new Coordinate(env.getMinX(), env.getMinY());
coords[1] = new Coordinate(env.getMinX(), env.getMaxY());
coords[2] = new Coordinate(env.getMaxX(), env.getMaxY());
coords[3] = new Coordinate(env.getMaxX(), env.getMinY());
coords[4] = new Coordinate(env.getMinX(), env.getMinY());
// return new ReferencedEnvelope( env, null );
org.locationtech.jts.geom.LinearRing ring = null;
try {
ring = gfac.createLinearRing(coords);
} catch (org.locationtech.jts.geom.TopologyException tope) {
LOGGER.fine("Topology Exception in GMLBox" + tope);
return null;
}
return gfac.createPolygon(ring, null);
}
// check for geometry properties
if (childName.equalsIgnoreCase("gml:polygonmember")
|| childName.equalsIgnoreCase("gml:pointmember")
|| childName.equalsIgnoreCase("gml:linestringmember")
|| childName.equalsIgnoreCase("gml:linearringmember")) {
for (int i = 0; i < child.getChildNodes().getLength(); i++) {
Node newChild = child.getChildNodes().item(i);
if (newChild.getNodeType() == Node.ELEMENT_NODE) {
childName = newChild.getNodeName();
if (!childName.startsWith("gml:")) {
childName = "gml:" + childName;
}
root = newChild;
child = newChild;
break;
}
}
}
if (childName.equalsIgnoreCase("gml:polygon")) {
LOGGER.finer("polygon");
LinearRing outer = null;
List inner = new ArrayList();
NodeList kids = root.getChildNodes();
for (int i = 0; i < kids.getLength(); i++) {
Node kid = kids.item(i);
LOGGER.finer("doing " + kid);
String kidName = kid.getNodeName();
if (kidName == null) {
kidName = child.getLocalName();
}
if (!kidName.startsWith("gml:")) {
kidName = "gml:" + kidName;
}
if (kidName.equalsIgnoreCase("gml:outerBoundaryIs")) {
outer = (LinearRing) parseGML(kid);
}
if (kidName.equalsIgnoreCase("gml:innerBoundaryIs")) {
inner.add((LinearRing) parseGML(kid));
}
}
if (inner.size() > 0) {
return gfac.createPolygon(outer, (LinearRing[]) inner.toArray(new LinearRing[0]));
} else {
return gfac.createPolygon(outer, null);
}
}
if (childName.equalsIgnoreCase("gml:outerBoundaryIs")
|| childName.equalsIgnoreCase("gml:innerBoundaryIs")) {
LOGGER.finer("Boundary layer");
NodeList kids = ((Element) child).getElementsByTagName("gml:LinearRing");
if (kids.getLength() == 0) kids = ((Element) child).getElementsByTagName("LinearRing");
return parseGML(kids.item(0));
}
if (childName.equalsIgnoreCase("gml:linearRing")) {
LOGGER.finer("LinearRing");
coordList =
new ExpressionDOMParser(CommonFactoryFinder.getFilterFactory2()).coords(child);
org.locationtech.jts.geom.LinearRing ring = null;
try {
ring = gfac.createLinearRing((Coordinate[]) coordList.toArray(new Coordinate[] {}));
} catch (TopologyException te) {
LOGGER.finer("Topology Exception build linear ring: " + te);
return null;
}
return ring;
}
if (childName.equalsIgnoreCase("gml:linestring")) {
LOGGER.finer("linestring");
coordList =
new ExpressionDOMParser(CommonFactoryFinder.getFilterFactory2()).coords(child);
org.locationtech.jts.geom.LineString line = null;
line = gfac.createLineString((Coordinate[]) coordList.toArray(new Coordinate[] {}));
return line;
}
if (childName.equalsIgnoreCase("gml:point")) {
LOGGER.finer("point");
coordList =
new ExpressionDOMParser(CommonFactoryFinder.getFilterFactory2()).coords(child);
org.locationtech.jts.geom.Point point = null;
point = gfac.createPoint((Coordinate) coordList.get(0));
return point;
}
if (childName.toLowerCase().startsWith("gml:multipolygon")
|| childName.toLowerCase().startsWith("gml:multilinestring")
|| childName.toLowerCase().startsWith("gml:multipoint")) {
List multi = new ArrayList();
// parse all children thru parseGML
NodeList kids = child.getChildNodes();
for (int i = 0; i < kids.getLength(); i++) {
if (kids.item(i).getNodeType() == Node.ELEMENT_NODE) {
multi.add(parseGML(kids.item(i)));
}
}
if (childName.toLowerCase().startsWith("gml:multipolygon")) {
LOGGER.finer("MultiPolygon");
return gfac.createMultiPolygon((Polygon[]) multi.toArray(new Polygon[0]));
} else if (childName.toLowerCase().startsWith("gml:multilinestring")) {
LOGGER.finer("MultiLineString");
return gfac.createMultiLineString((LineString[]) multi.toArray(new LineString[0]));
} else {
LOGGER.finer("MultiPoint");
return gfac.createMultiPoint((Point[]) multi.toArray(new Point[0]));
}
}
return null;
}
/**
* Parses a dom node into a coordinate list.
*
* @param root the root node representation of gml:coordinates.
* @return the coordinates in a list.
*/
public java.util.List coords(Node root) {
LOGGER.finer("parsing coordinate(s) " + root);
List clist = new ArrayList();
NodeList kids = root.getChildNodes();
for (int i = 0; i < kids.getLength(); i++) {
Node child = kids.item(i);
LOGGER.finer("doing " + child);
// if (child.getLocalName().equalsIgnoreCase("gml:coordinate")) {
// String internal = child.getNodeValue();
// }
String childName = child.getNodeName();
if (childName == null) {
childName = child.getLocalName();
}
if (!childName.startsWith("gml:")) {
childName = "gml:" + childName;
}
if (childName.equalsIgnoreCase("gml:coord")) {
// DJB: adding support for:
// <gml:coord><gml:X>-180.0</gml:X><gml:Y>-90.0</gml:Y></gml:coord>
// <gml:coord><gml:X>180.0</gml:X><gml:Y>90.0</gml:Y></gml:coord>
Coordinate c = new Coordinate();
NodeList grandChildren = child.getChildNodes();
for (int t = 0; t < grandChildren.getLength(); t++) {
Node grandChild = grandChildren.item(t);
String grandChildName = grandChild.getNodeName();
if (grandChildName == null) grandChildName = grandChild.getLocalName();
if (!grandChildName.startsWith("gml:"))
grandChildName = "gml:" + grandChildName;
if (grandChildName.equalsIgnoreCase("gml:x")) {
c.x =
Double.parseDouble(
grandChild.getChildNodes().item(0).getNodeValue().trim());
} else if (grandChildName.equalsIgnoreCase("gml:y")) {
c.y =
Double.parseDouble(
grandChild.getChildNodes().item(0).getNodeValue().trim());
} else if (grandChildName.equalsIgnoreCase("gml:z")) {
c.setZ(
Double.parseDouble(
grandChild.getChildNodes().item(0).getNodeValue().trim()));
}
}
clist.add(c);
}
if (childName.equalsIgnoreCase("gml:coordinates")) {
LOGGER.finer("coordinates " + child.getFirstChild().getNodeValue());
NodeList grandKids = child.getChildNodes();
for (int k = 0; k < grandKids.getLength(); k++) {
Node grandKid = grandKids.item(k);
if (grandKid.getNodeValue() == null) {
continue;
}
if (grandKid.getNodeValue().trim().length() == 0) {
continue;
}
String outer = grandKid.getNodeValue().trim();
// handle newline and tab whitespace along with space
StringTokenizer ost = new StringTokenizer(outer, " \n\t");
while (ost.hasMoreTokens()) {
String internal = ost.nextToken();
StringTokenizer ist = new StringTokenizer(internal, ",");
double xCoord = Double.parseDouble(ist.nextToken());
double yCoord = Double.parseDouble(ist.nextToken());
double zCoord = Double.NaN;
if (ist.hasMoreTokens()) {
zCoord = Double.parseDouble(ist.nextToken());
}
clist.add(new Coordinate(xCoord, yCoord, zCoord));
}
}
}
}
return clist;
}
}
| modules/library/main/src/main/java/org/geotools/filter/ExpressionDOMParser.java | /*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2002-2008, Open Source Geospatial Foundation (OSGeo)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Created on 03 July 2002, 10:21
*/
package org.geotools.filter;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.logging.Logger;
import org.geotools.factory.CommonFactoryFinder;
import org.geotools.referencing.CRS;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.LineString;
import org.locationtech.jts.geom.LinearRing;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.geom.Polygon;
import org.locationtech.jts.geom.TopologyException;
import org.opengis.filter.FilterFactory2;
import org.opengis.filter.expression.Expression;
import org.opengis.filter.expression.PropertyName;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.helpers.NamespaceSupport;
/**
* parsez short sections of gml for use in expressions and filters Hopefully we can get away without
* a full parser here.
*
* @author iant
* @author Niels Charlier
*/
public final class ExpressionDOMParser {
/** The logger for the filter module. */
private static final Logger LOGGER =
org.geotools.util.logging.Logging.getLogger(ExpressionDOMParser.class);
/** Factory for creating filters. */
private FilterFactory2 ff;
/** Factory for creating geometry objects */
private static GeometryFactory gfac = new GeometryFactory();
/** number of coordinates in a box */
private static final int NUM_BOX_COORDS = 5;
/** Creates a new instance of ExpressionXmlParser */
private ExpressionDOMParser() {
this(CommonFactoryFinder.getFilterFactory2(null));
LOGGER.finer("made new logic factory");
}
/** Constructor injection */
public ExpressionDOMParser(FilterFactory2 factory) {
ff = factory != null ? factory : CommonFactoryFinder.getFilterFactory2(null);
}
/** Setter injection */
public void setFilterFactory(FilterFactory2 factory) {
ff = factory;
}
private static NamespaceSupport getNameSpaces(Node node) {
NamespaceSupport namespaces = new NamespaceSupport();
while (node != null) {
NamedNodeMap atts = node.getAttributes();
if (atts != null) {
for (int i = 0; i < atts.getLength(); i++) {
Node att = atts.item(i);
if (att.getNamespaceURI() != null
&& att.getNamespaceURI().equals("http://www.w3.org/2000/xmlns/")
&& namespaces.getURI(att.getLocalName()) == null) {
namespaces.declarePrefix(att.getLocalName(), att.getNodeValue());
}
}
}
node = node.getParentNode();
}
return namespaces;
}
/**
* @deprecated Please use ExpressionDOMParser.expression
* @param root
*/
public static Expression parseExpression(Node root) {
ExpressionDOMParser parser = new ExpressionDOMParser();
return parser.expression(root);
}
/**
* parses an expression for a filter.
*
* @param root the root node to parse, should be an filter expression.
* @return the geotools representation of the expression held in the node.
*/
public Expression expression(Node root) {
// NodeList children = root.getChildNodes();
// LOGGER.finest("children "+children);
if ((root == null) || (root.getNodeType() != Node.ELEMENT_NODE)) {
LOGGER.finer("bad node input ");
return null;
}
LOGGER.finer("processing root " + root.getLocalName());
Node child = root;
String childName =
(child.getLocalName() != null) ? child.getLocalName() : child.getNodeName();
if (childName.indexOf(':') != -1) {
// the DOM parser wasnt properly set to handle namespaces...
childName = childName.substring(childName.indexOf(':') + 1);
}
if (childName.equalsIgnoreCase("Literal")) {
LOGGER.finer("processing literal " + child);
NodeList kidList = child.getChildNodes();
LOGGER.finest("literal elements (" + kidList.getLength() + ") " + kidList.toString());
for (int i = 0; i < kidList.getLength(); i++) {
Node kid = kidList.item(i);
LOGGER.finest("kid " + i + " " + kid);
if (kid == null) {
LOGGER.finest("Skipping ");
continue;
}
if (kid.getNodeValue() == null) {
/* it might be a gml string so we need to convert it into
* a geometry this is a bit tricky since our standard
* gml parser is SAX based and we're a DOM here.
*/
LOGGER.finer(
"node " + kid.getNodeValue() + " namespace " + kid.getNamespaceURI());
LOGGER.fine("a literal gml string?");
try {
Geometry geom = parseGML(kid);
if (geom != null) {
LOGGER.finer("built a " + geom.getGeometryType() + " from gml");
LOGGER.finer("\tpoints: " + geom.getNumPoints());
} else {
LOGGER.finer("got a null geometry back from gml parser");
}
return ff.literal(geom);
} catch (IllegalFilterException ife) {
LOGGER.warning("Problem building GML/JTS object: " + ife);
}
return null;
}
// CDATA shouldn't be interpretted
if (kid.getNodeType() != Node.CDATA_SECTION_NODE
&& kid.getNodeValue().trim().length() == 0) {
LOGGER.finest("empty text element");
continue;
}
// debuging only
/*switch(kid.getNodeType()){
case Node.ELEMENT_NODE:
LOGGER.finer("element :"+kid);
break;
case Node.TEXT_NODE:
LOGGER.finer("text :"+kid);
break;
case Node.ATTRIBUTE_NODE:
LOGGER.finer("Attribute :"+kid);
break;
case Node.CDATA_SECTION_NODE:
LOGGER.finer("Cdata :"+kid);
break;
case Node.COMMENT_NODE:
LOGGER.finer("comment :"+kid);
break;
} */
String nodeValue = kid.getNodeValue();
LOGGER.finer("processing " + nodeValue);
try {
// always store internal values as strings. We might lose info otherwise.
return ff.literal(nodeValue);
} catch (IllegalFilterException ife) {
LOGGER.finer("Unable to build expression " + ife);
return null;
}
}
// creates an empty literal expression if there is nothing inside the literal
return ff.literal("");
}
if (childName.equalsIgnoreCase("add")) {
try {
LOGGER.fine("processing an Add");
// Node left = null;
// Node right = null;
Node value = child.getFirstChild();
while (value.getNodeType() != Node.ELEMENT_NODE) {
value = value.getNextSibling();
}
LOGGER.finer("add left value -> " + value + "<-");
Expression left = parseExpression(value);
value = value.getNextSibling();
while (value.getNodeType() != Node.ELEMENT_NODE) {
value = value.getNextSibling();
}
LOGGER.finer("add right value -> " + value + "<-");
Expression right = parseExpression(value);
return ff.add(left, right);
} catch (IllegalFilterException ife) {
LOGGER.warning("Unable to build expression " + ife);
return null;
}
}
if (childName.equalsIgnoreCase("sub")) {
try {
// NodeList kids = child.getChildNodes();
Node value = child.getFirstChild();
while (value.getNodeType() != Node.ELEMENT_NODE) {
value = value.getNextSibling();
}
LOGGER.finer("add left value -> " + value + "<-");
Expression left = parseExpression(value);
value = value.getNextSibling();
while (value.getNodeType() != Node.ELEMENT_NODE) {
value = value.getNextSibling();
}
LOGGER.finer("add right value -> " + value + "<-");
Expression right = parseExpression(value);
return ff.subtract(left, right);
} catch (IllegalFilterException ife) {
LOGGER.warning("Unable to build expression " + ife);
return null;
}
}
if (childName.equalsIgnoreCase("mul")) {
try {
// NodeList kids = child.getChildNodes();
Node value = child.getFirstChild();
while (value.getNodeType() != Node.ELEMENT_NODE) {
value = value.getNextSibling();
}
LOGGER.finer("add left value -> " + value + "<-");
Expression left = parseExpression(value);
value = value.getNextSibling();
while (value.getNodeType() != Node.ELEMENT_NODE) {
value = value.getNextSibling();
}
LOGGER.finer("add right value -> " + value + "<-");
Expression right = parseExpression(value);
return ff.multiply(left, right);
} catch (IllegalFilterException ife) {
LOGGER.warning("Unable to build expression " + ife);
return null;
}
}
if (childName.equalsIgnoreCase("div")) {
try {
Node value = child.getFirstChild();
while (value.getNodeType() != Node.ELEMENT_NODE) {
value = value.getNextSibling();
}
LOGGER.finer("add left value -> " + value + "<-");
Expression left = parseExpression(value);
value = value.getNextSibling();
while (value.getNodeType() != Node.ELEMENT_NODE) {
value = value.getNextSibling();
}
LOGGER.finer("add right value -> " + value + "<-");
Expression right = parseExpression(value);
return ff.divide(left, right);
} catch (IllegalFilterException ife) {
LOGGER.warning("Unable to build expression " + ife);
return null;
}
}
if (childName.equalsIgnoreCase("PropertyName")) {
try {
// JD: trim whitespace here
String value = child.getFirstChild().getNodeValue();
value = value != null ? value.trim() : value;
PropertyName attribute = ff.property(value, getNameSpaces(root));
// attribute.setAttributePath(child.getFirstChild().getNodeValue());
return attribute;
} catch (IllegalFilterException ife) {
LOGGER.warning("Unable to build expression: " + ife);
return null;
}
}
if (childName.equalsIgnoreCase("Function")) {
Element param = (Element) child;
NamedNodeMap map = param.getAttributes();
String funcName = null;
for (int k = 0; k < map.getLength(); k++) {
String res = map.item(k).getNodeValue();
String name = map.item(k).getLocalName();
if (name == null) {
name = map.item(k).getNodeName();
}
if (name.indexOf(':') != -1) {
// the DOM parser was not properly set to handle namespaces...
name = name.substring(name.indexOf(':') + 1);
}
LOGGER.fine("attribute " + name + " with value of " + res);
if (name.equalsIgnoreCase("name")) {
funcName = res;
}
}
if (funcName == null) {
LOGGER.severe("failed to find a function name in " + child);
return null;
}
ArrayList<Expression> args = new ArrayList<Expression>();
Node value = child.getFirstChild();
ARGS:
while (value != null) {
while (value.getNodeType() != Node.ELEMENT_NODE) {
value = value.getNextSibling();
if (value == null) break ARGS;
}
args.add(parseExpression(value));
value = value.getNextSibling();
}
Expression[] array = args.toArray(new Expression[0]);
return ff.function(funcName, array);
}
if (child.getNodeType() == Node.TEXT_NODE) {
LOGGER.finer("processing a text node " + root.getNodeValue());
String nodeValue = root.getNodeValue();
LOGGER.finer("Text name " + nodeValue);
// see if it's an int
try {
try {
Integer intLiteral = Integer.valueOf(nodeValue);
return ff.literal(intLiteral);
} catch (NumberFormatException e) {
/* really empty */
}
try {
Double doubleLit = new Double(nodeValue);
return ff.literal(doubleLit);
} catch (NumberFormatException e) {
/* really empty */
}
return ff.literal(nodeValue);
} catch (IllegalFilterException ife) {
LOGGER.finer("Unable to build expression " + ife);
}
}
return null;
}
/**
* @deprecated Please use ExpressionDOMParser.gml
* @param root
* @return the java representation of the geometry contained in root.
*/
public static Geometry parseGML(Node root) {
ExpressionDOMParser parser = new ExpressionDOMParser();
return parser.gml(root);
}
public Geometry gml(Node root) {
// look for the SRS name, if available
Node srsNameNode = root.getAttributes().getNamedItem("srsName");
CoordinateReferenceSystem crs = null;
if (srsNameNode != null) {
String srs = srsNameNode.getTextContent();
try {
crs = CRS.decode(srs);
} catch (Exception e) {
LOGGER.warning("Failed to parse the specified SRS " + srs);
}
}
// parse the geometry
Geometry g = _gml(root);
// force the crs if necessary
if (crs != null) {
g.setUserData(crs);
}
return g;
}
/**
* Parses the gml of this node to jts.
*
* @param root the parent node of the gml to parse.
* @return the java representation of the geometry contained in root.
*/
private Geometry _gml(Node root) {
LOGGER.finer("processing gml " + root);
List coordList;
Node child = root;
// Jesus I hate DOM. I have no idea why this was checking for localname
// and then nodename - lead to non-deterministic behavior, that for
// some reason only failed if the filter parser was used within the
// SLDparser. I really would like that class redone, so we don't have
// to use this crappy DOM GML parser.
String childName = child.getNodeName();
if (childName == null) {
childName = child.getLocalName();
}
if (!childName.startsWith("gml:")) {
childName = "gml:" + childName;
}
if (childName.equalsIgnoreCase("gml:box")) {
coordList = parseCoords(child);
org.locationtech.jts.geom.Envelope env = new org.locationtech.jts.geom.Envelope();
for (int i = 0; i < coordList.size(); i++) {
env.expandToInclude((Coordinate) coordList.get(i));
}
Coordinate[] coords = new Coordinate[NUM_BOX_COORDS];
coords[0] = new Coordinate(env.getMinX(), env.getMinY());
coords[1] = new Coordinate(env.getMinX(), env.getMaxY());
coords[2] = new Coordinate(env.getMaxX(), env.getMaxY());
coords[3] = new Coordinate(env.getMaxX(), env.getMinY());
coords[4] = new Coordinate(env.getMinX(), env.getMinY());
// return new ReferencedEnvelope( env, null );
org.locationtech.jts.geom.LinearRing ring = null;
try {
ring = gfac.createLinearRing(coords);
} catch (org.locationtech.jts.geom.TopologyException tope) {
LOGGER.fine("Topology Exception in GMLBox" + tope);
return null;
}
return gfac.createPolygon(ring, null);
}
// check for geometry properties
if (childName.equalsIgnoreCase("gml:polygonmember")
|| childName.equalsIgnoreCase("gml:pointmember")
|| childName.equalsIgnoreCase("gml:linestringmember")
|| childName.equalsIgnoreCase("gml:linearringmember")) {
for (int i = 0; i < child.getChildNodes().getLength(); i++) {
Node newChild = child.getChildNodes().item(i);
if (newChild.getNodeType() == Node.ELEMENT_NODE) {
childName = newChild.getNodeName();
if (!childName.startsWith("gml:")) {
childName = "gml:" + childName;
}
root = newChild;
child = newChild;
break;
}
}
}
if (childName.equalsIgnoreCase("gml:polygon")) {
LOGGER.finer("polygon");
LinearRing outer = null;
List inner = new ArrayList();
NodeList kids = root.getChildNodes();
for (int i = 0; i < kids.getLength(); i++) {
Node kid = kids.item(i);
LOGGER.finer("doing " + kid);
String kidName = kid.getNodeName();
if (kidName == null) {
kidName = child.getLocalName();
}
if (!kidName.startsWith("gml:")) {
kidName = "gml:" + kidName;
}
if (kidName.equalsIgnoreCase("gml:outerBoundaryIs")) {
outer = (LinearRing) parseGML(kid);
}
if (kidName.equalsIgnoreCase("gml:innerBoundaryIs")) {
inner.add((LinearRing) parseGML(kid));
}
}
if (inner.size() > 0) {
return gfac.createPolygon(outer, (LinearRing[]) inner.toArray(new LinearRing[0]));
} else {
return gfac.createPolygon(outer, null);
}
}
if (childName.equalsIgnoreCase("gml:outerBoundaryIs")
|| childName.equalsIgnoreCase("gml:innerBoundaryIs")) {
LOGGER.finer("Boundary layer");
NodeList kids = ((Element) child).getElementsByTagName("gml:LinearRing");
if (kids.getLength() == 0) kids = ((Element) child).getElementsByTagName("LinearRing");
return parseGML(kids.item(0));
}
if (childName.equalsIgnoreCase("gml:linearRing")) {
LOGGER.finer("LinearRing");
coordList = parseCoords(child);
org.locationtech.jts.geom.LinearRing ring = null;
try {
ring = gfac.createLinearRing((Coordinate[]) coordList.toArray(new Coordinate[] {}));
} catch (TopologyException te) {
LOGGER.finer("Topology Exception build linear ring: " + te);
return null;
}
return ring;
}
if (childName.equalsIgnoreCase("gml:linestring")) {
LOGGER.finer("linestring");
coordList = parseCoords(child);
org.locationtech.jts.geom.LineString line = null;
line = gfac.createLineString((Coordinate[]) coordList.toArray(new Coordinate[] {}));
return line;
}
if (childName.equalsIgnoreCase("gml:point")) {
LOGGER.finer("point");
coordList = parseCoords(child);
org.locationtech.jts.geom.Point point = null;
point = gfac.createPoint((Coordinate) coordList.get(0));
return point;
}
if (childName.toLowerCase().startsWith("gml:multipolygon")
|| childName.toLowerCase().startsWith("gml:multilinestring")
|| childName.toLowerCase().startsWith("gml:multipoint")) {
List multi = new ArrayList();
// parse all children thru parseGML
NodeList kids = child.getChildNodes();
for (int i = 0; i < kids.getLength(); i++) {
if (kids.item(i).getNodeType() == Node.ELEMENT_NODE) {
multi.add(parseGML(kids.item(i)));
}
}
if (childName.toLowerCase().startsWith("gml:multipolygon")) {
LOGGER.finer("MultiPolygon");
return gfac.createMultiPolygon((Polygon[]) multi.toArray(new Polygon[0]));
} else if (childName.toLowerCase().startsWith("gml:multilinestring")) {
LOGGER.finer("MultiLineString");
return gfac.createMultiLineString((LineString[]) multi.toArray(new LineString[0]));
} else {
LOGGER.finer("MultiPoint");
return gfac.createMultiPoint((Point[]) multi.toArray(new Point[0]));
}
}
return null;
}
/**
* Parse a DOM node into a coordiante list.
*
* @deprecated please use ExpressionDOMParser.coords()
* @param root the root node representation of gml:coordinates.
* @return the coordinates in a list.
*/
public static java.util.List parseCoords(Node root) {
ExpressionDOMParser parser = new ExpressionDOMParser();
return parser.coords(root);
}
/**
* Parses a dom node into a coordinate list.
*
* @param root the root node representation of gml:coordinates.
* @return the coordinates in a list.
*/
public java.util.List coords(Node root) {
LOGGER.finer("parsing coordinate(s) " + root);
List clist = new ArrayList();
NodeList kids = root.getChildNodes();
for (int i = 0; i < kids.getLength(); i++) {
Node child = kids.item(i);
LOGGER.finer("doing " + child);
// if (child.getLocalName().equalsIgnoreCase("gml:coordinate")) {
// String internal = child.getNodeValue();
// }
String childName = child.getNodeName();
if (childName == null) {
childName = child.getLocalName();
}
if (!childName.startsWith("gml:")) {
childName = "gml:" + childName;
}
if (childName.equalsIgnoreCase("gml:coord")) {
// DJB: adding support for:
// <gml:coord><gml:X>-180.0</gml:X><gml:Y>-90.0</gml:Y></gml:coord>
// <gml:coord><gml:X>180.0</gml:X><gml:Y>90.0</gml:Y></gml:coord>
Coordinate c = new Coordinate();
NodeList grandChildren = child.getChildNodes();
for (int t = 0; t < grandChildren.getLength(); t++) {
Node grandChild = grandChildren.item(t);
String grandChildName = grandChild.getNodeName();
if (grandChildName == null) grandChildName = grandChild.getLocalName();
if (!grandChildName.startsWith("gml:"))
grandChildName = "gml:" + grandChildName;
if (grandChildName.equalsIgnoreCase("gml:x")) {
c.x =
Double.parseDouble(
grandChild.getChildNodes().item(0).getNodeValue().trim());
} else if (grandChildName.equalsIgnoreCase("gml:y")) {
c.y =
Double.parseDouble(
grandChild.getChildNodes().item(0).getNodeValue().trim());
} else if (grandChildName.equalsIgnoreCase("gml:z")) {
c.setZ(
Double.parseDouble(
grandChild.getChildNodes().item(0).getNodeValue().trim()));
}
}
clist.add(c);
}
if (childName.equalsIgnoreCase("gml:coordinates")) {
LOGGER.finer("coordinates " + child.getFirstChild().getNodeValue());
NodeList grandKids = child.getChildNodes();
for (int k = 0; k < grandKids.getLength(); k++) {
Node grandKid = grandKids.item(k);
if (grandKid.getNodeValue() == null) {
continue;
}
if (grandKid.getNodeValue().trim().length() == 0) {
continue;
}
String outer = grandKid.getNodeValue().trim();
// handle newline and tab whitespace along with space
StringTokenizer ost = new StringTokenizer(outer, " \n\t");
while (ost.hasMoreTokens()) {
String internal = ost.nextToken();
StringTokenizer ist = new StringTokenizer(internal, ",");
double xCoord = Double.parseDouble(ist.nextToken());
double yCoord = Double.parseDouble(ist.nextToken());
double zCoord = Double.NaN;
if (ist.hasMoreTokens()) {
zCoord = Double.parseDouble(ist.nextToken());
}
clist.add(new Coordinate(xCoord, yCoord, zCoord));
}
}
}
}
return clist;
}
}
| Removing deprecated method is ExpressionDOMParser
| modules/library/main/src/main/java/org/geotools/filter/ExpressionDOMParser.java | Removing deprecated method is ExpressionDOMParser |
|
Java | lgpl-2.1 | 1ae4ba54aea86d1c9fcc9aead6dafe58b7ef8e42 | 0 | xwiki/xwiki-commons,xwiki/xwiki-commons | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.job;
/**
* A Job which is part of a group of jobs. Grouped jobs are executed synchronously usually in the same thread.
* <p>
* The {@link GroupedJob} return a group hierarchy interpreted as follow:
* <ul>
* <li>a {@link GroupedJob} from group ["group", "subgroup"] won't be executed at the same time of another
* {@link GroupedJob} from group ["group", "subgroup"]
* <li>a {@link GroupedJob} from group ["group", "subgroup1"] can be executed at the same time of a {@link GroupedJob}
* from group ["group", "subgroup2"]
* <li>a {@link GroupedJob} from group ["group", "subgroup"] won't be executed at the same time of a {@link GroupedJob}
* from group ["group"]
* </ul>
*
* @version $Id$
* @since 6.1M2
*/
public interface GroupedJob extends Job
{
/**
* @return the group hierarchy of the job. If null the job won't be grouped.
*/
JobGroupPath getGroupPath();
}
| xwiki-commons-core/xwiki-commons-job/src/main/java/org/xwiki/job/GroupedJob.java | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.job;
/**
* A Job which is part of a group of jobs. Grouped jobs are executed synchronously usually in the same thread.
* <p>
* The {@link GroupedJob} return a group hierarchy interpreted as follow:
* <ul>
* <li>a {@link GroupedJob} from group ["group", "subgroup"] won't be executed at the same time of another
* {@link GroupedJob} from group ["group", "subgroup"]
* <li>a {@link GroupedJob} from group ["group", "subgroup1"] can be executed at the same time of a {@link GroupedJob}
* from group ["group", "subgroup2"]
* <li>a {@link GroupedJob} from group ["group", "subgroup"] won't be executed at the same time of a {@link GroupedJob}
* from group ["group"]
* </ul>
*
* @version $Id$
* @since 6.1M2
*/
public interface GroupedJob extends Job
{
/**
* @return the group hierarchy of the job
*/
JobGroupPath getGroupPath();
}
| XCOMMONS-932: Grouped job with null path should be executed as non grouped
| xwiki-commons-core/xwiki-commons-job/src/main/java/org/xwiki/job/GroupedJob.java | XCOMMONS-932: Grouped job with null path should be executed as non grouped |
|
Java | lgpl-2.1 | 9f83b60f6a4caca94c8d00854cf3dcbecd296e16 | 0 | geotools/geotools,geotools/geotools,geotools/geotools,geotools/geotools | /*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2011, Open Source Geospatial Foundation (OSGeo)
* (C) 2003-2005, Open Geospatial Consortium Inc.
*
* All Rights Reserved. http://www.opengis.org/legal/
*/
package org.opengis.util;
import static org.junit.Assert.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.logging.Logger;
import org.junit.*;
import org.opengis.metadata.identification.CharacterSet;
/**
* Tests every {@link CodeList}.
*
* @author Martin desruisseaux (IRD)
*/
public final class CodeListTest {
/** The logger to use. */
private static final Logger LOGGER = Logger.getLogger("org.opengis");
/**
* Tests the {@link CharacterSet} code list. At the difference of other code lists, its {@link
* CodeList#matches} method is overriden.
*/
@Test
public void testCharacterSet() {
final CodeList code = CharacterSet.UTF_8;
assertEquals("UTF_8", code.name());
assertEquals("utf8", code.identifier());
assertTrue(code.matches("UTF8"));
assertTrue(code.matches("UTF_8"));
assertTrue(code.matches("UTF-8"));
assertFalse(code.matches("UTF 8"));
assertSame(code, CharacterSet.valueOf("UTF_8"));
assertSame(code, CharacterSet.valueOf("UTF-8"));
assertSame(code, CharacterSet.valueOf("UTF8"));
assertSame(code, CharacterSet.valueOf("utf8"));
assertNotSame(code, CharacterSet.valueOf("UTF_7"));
}
/** Tests the instantiation of every code lists. */
@Test
public void testAll() {
int count = 0;
final Class<CodeList> base = CodeList.class;
final ClassScanner scanner = new ClassScanner();
while (scanner.hasNext()) {
final Class<?> candidate = scanner.next();
if (!base.equals(candidate) && base.isAssignableFrom(candidate)) {
// SimpleEnumeratioType is a special case to avoid for now.
final String name = candidate.getName();
if (name.equals("org.opengis.util.SimpleEnumerationType")) {
continue;
}
if (name.equals("org.opengis.filter.sort.SortOrder")) {
continue;
}
assertValid(candidate.asSubclass(CodeList.class));
count++;
}
}
LOGGER.fine("Found " + count + " code lists.");
if (count == 0) {
LOGGER.warning("No CodeList found.");
}
}
/** Ensures that the name declared in the code list match the field names. */
private static void assertValid(final Class<? extends CodeList> classe) {
Method method;
int modifiers;
String fullName;
/*
* Gets the values() method, which should public and static.
* Then gets every CodeList instances returned by values().
*/
final String className = classe.getName();
fullName = className + ".values()";
try {
method = classe.getMethod("values", (Class[]) null);
} catch (NoSuchMethodException e) {
fail(fullName + " method is missing.");
return;
}
assertNotNull(method);
modifiers = method.getModifiers();
assertTrue(fullName + " is not public.", Modifier.isPublic(modifiers));
assertTrue(fullName + " is not static.", Modifier.isStatic(modifiers));
final CodeList[] values;
try {
values = (CodeList[]) method.invoke(null, (Object[]) null);
} catch (IllegalAccessException e) {
fail(fullName + " is not accessible.");
return;
} catch (InvocationTargetException e) {
fail("Call to " + fullName + " failed.\n" + e.getTargetException());
return;
}
assertNotNull(fullName + " returned null.", values);
/*
* Gets the family() method, to be used when we will test every
* code list instances.
*/
fullName = className + ".family()";
try {
method = classe.getMethod("family", (Class[]) null);
} catch (NoSuchMethodException e) {
fail(fullName + " method is missing.");
return;
}
assertNotNull(method);
modifiers = method.getModifiers();
assertTrue(fullName + " is not public.", Modifier.isPublic(modifiers));
assertFalse(fullName + " is static.", Modifier.isStatic(modifiers));
/*
* Tests every CodeList instances returned by values().
* Every field should be public, static and final.
*/
for (final CodeList value : values) {
final String name = value.name();
fullName = className + '.' + name;
assertTrue(fullName + ": unexpected type.", classe.isInstance(value));
final Field field;
try {
field = classe.getField(name);
} catch (NoSuchFieldException e) {
final Class<? extends CodeList> valueClass = value.getClass();
if (!classe.equals(valueClass) && classe.isAssignableFrom(valueClass)) {
// Do not fails if valueClass is a subclass of classe.
continue;
}
fail(fullName + " field not found.");
continue;
}
assertNotNull(field);
modifiers = field.getModifiers();
assertEquals(fullName + ": unexpected name mismatch.", name, field.getName());
assertTrue(fullName + " is not public.", Modifier.isPublic(modifiers));
assertTrue(fullName + " is not static.", Modifier.isStatic(modifiers));
assertTrue(fullName + " is not final.", Modifier.isFinal(modifiers));
Object constant;
try {
constant = field.get(null);
} catch (IllegalAccessException e) {
fail(fullName + " is not accessible.");
continue;
}
assertSame(fullName + " is not the expected instance.", value, constant);
final CodeList[] family;
try {
family = (CodeList[]) method.invoke(constant, (Object[]) null);
} catch (IllegalAccessException e) {
fail(className + ".family() is not accessible.");
return;
} catch (InvocationTargetException e) {
fail("Call to " + className + ".family() failed.\n" + e.getTargetException());
return;
}
assertTrue(className + ".family() mismatch.", Arrays.equals(values, family));
}
/*
* Gets the private VALUES field only if CodeList is the direct parent.
*/
if (classe.getSuperclass().equals(CodeList.class)) {
fullName = className + ".VALUES";
final Field field;
try {
field = classe.getDeclaredField("VALUES");
} catch (NoSuchFieldException e) {
fail(fullName + " private list is missing.");
return;
}
modifiers = field.getModifiers();
assertTrue(Modifier.isStatic(modifiers));
assertTrue(Modifier.isFinal(modifiers));
assertFalse(Modifier.isPublic(modifiers));
assertFalse(Modifier.isProtected(modifiers));
field.setAccessible(true);
final ArrayList<?> asList;
try {
final Object candidate = field.get(null);
assertEquals(
fullName + " is not an ArrayList.", ArrayList.class, candidate.getClass());
asList = (ArrayList<?>) candidate;
} catch (IllegalAccessException e) {
fail(className + ".VALUES is not accessible.");
return;
}
assertEquals(Arrays.asList(values), asList);
}
/*
* Tries to create a new element.
*/
try {
method = classe.getMethod("valueOf", String.class);
} catch (NoSuchMethodException e) {
return;
}
final CodeList value;
try {
value = classe.cast(method.invoke(null, "Dummy"));
} catch (IllegalAccessException e) {
fail(e.toString());
return;
} catch (InvocationTargetException e) {
java.util.logging.Logger.getGlobal().log(java.util.logging.Level.INFO, "", e);
fail(e.getTargetException().toString());
return;
}
assertEquals("Dummy", value.name());
}
}
| modules/library/opengis/src/test/java/org/opengis/util/CodeListTest.java | /*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2011, Open Source Geospatial Foundation (OSGeo)
* (C) 2003-2005, Open Geospatial Consortium Inc.
*
* All Rights Reserved. http://www.opengis.org/legal/
*/
package org.opengis.util;
import static org.junit.Assert.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import org.junit.*;
import org.opengis.metadata.identification.CharacterSet;
/**
* Tests every {@link CodeList}.
*
* @author Martin desruisseaux (IRD)
*/
public final class CodeListTest {
/** The logger to use. */
private static final Logger LOGGER = Logger.getLogger("org.opengis");
/**
* For avoiding to pollute the output stream if {@code ArrayList.capacity()} method invocation
* failed.
*/
private static boolean capacityFailed = false;
/**
* Tests the {@link CharacterSet} code list. At the difference of other code lists, its {@link
* CodeList#matches} method is overriden.
*/
@Test
public void testCharacterSet() {
final CodeList code = CharacterSet.UTF_8;
assertEquals("UTF_8", code.name());
assertEquals("utf8", code.identifier());
assertTrue(code.matches("UTF8"));
assertTrue(code.matches("UTF_8"));
assertTrue(code.matches("UTF-8"));
assertFalse(code.matches("UTF 8"));
assertSame(code, CharacterSet.valueOf("UTF_8"));
assertSame(code, CharacterSet.valueOf("UTF-8"));
assertSame(code, CharacterSet.valueOf("UTF8"));
assertSame(code, CharacterSet.valueOf("utf8"));
assertNotSame(code, CharacterSet.valueOf("UTF_7"));
}
/** Tests the instantiation of every code lists. */
@Test
public void testAll() {
int count = 0;
final Class<CodeList> base = CodeList.class;
final ClassScanner scanner = new ClassScanner();
while (scanner.hasNext()) {
final Class<?> candidate = scanner.next();
if (!base.equals(candidate) && base.isAssignableFrom(candidate)) {
// SimpleEnumeratioType is a special case to avoid for now.
final String name = candidate.getName();
if (name.equals("org.opengis.util.SimpleEnumerationType")) {
continue;
}
if (name.equals("org.opengis.filter.sort.SortOrder")) {
continue;
}
assertValid(candidate.asSubclass(CodeList.class));
count++;
}
}
LOGGER.fine("Found " + count + " code lists.");
if (count == 0) {
LOGGER.warning("No CodeList found.");
}
}
/** Ensures that the name declared in the code list match the field names. */
private static void assertValid(final Class<? extends CodeList> classe) {
Method method;
int modifiers;
String fullName;
/*
* Gets the values() method, which should public and static.
* Then gets every CodeList instances returned by values().
*/
final String className = classe.getName();
fullName = className + ".values()";
try {
method = classe.getMethod("values", (Class[]) null);
} catch (NoSuchMethodException e) {
fail(fullName + " method is missing.");
return;
}
assertNotNull(method);
modifiers = method.getModifiers();
assertTrue(fullName + " is not public.", Modifier.isPublic(modifiers));
assertTrue(fullName + " is not static.", Modifier.isStatic(modifiers));
final CodeList[] values;
try {
values = (CodeList[]) method.invoke(null, (Object[]) null);
} catch (IllegalAccessException e) {
fail(fullName + " is not accessible.");
return;
} catch (InvocationTargetException e) {
fail("Call to " + fullName + " failed.\n" + e.getTargetException());
return;
}
assertNotNull(fullName + " returned null.", values);
/*
* Gets the family() method, to be used when we will test every
* code list instances.
*/
fullName = className + ".family()";
try {
method = classe.getMethod("family", (Class[]) null);
} catch (NoSuchMethodException e) {
fail(fullName + " method is missing.");
return;
}
assertNotNull(method);
modifiers = method.getModifiers();
assertTrue(fullName + " is not public.", Modifier.isPublic(modifiers));
assertFalse(fullName + " is static.", Modifier.isStatic(modifiers));
/*
* Tests every CodeList instances returned by values().
* Every field should be public, static and final.
*/
for (final CodeList value : values) {
final String name = value.name();
fullName = className + '.' + name;
assertTrue(fullName + ": unexpected type.", classe.isInstance(value));
final Field field;
try {
field = classe.getField(name);
} catch (NoSuchFieldException e) {
final Class<? extends CodeList> valueClass = value.getClass();
if (!classe.equals(valueClass) && classe.isAssignableFrom(valueClass)) {
// Do not fails if valueClass is a subclass of classe.
continue;
}
fail(fullName + " field not found.");
continue;
}
assertNotNull(field);
modifiers = field.getModifiers();
assertEquals(fullName + ": unexpected name mismatch.", name, field.getName());
assertTrue(fullName + " is not public.", Modifier.isPublic(modifiers));
assertTrue(fullName + " is not static.", Modifier.isStatic(modifiers));
assertTrue(fullName + " is not final.", Modifier.isFinal(modifiers));
Object constant;
try {
constant = field.get(null);
} catch (IllegalAccessException e) {
fail(fullName + " is not accessible.");
continue;
}
assertSame(fullName + " is not the expected instance.", value, constant);
final CodeList[] family;
try {
family = (CodeList[]) method.invoke(constant, (Object[]) null);
} catch (IllegalAccessException e) {
fail(className + ".family() is not accessible.");
return;
} catch (InvocationTargetException e) {
fail("Call to " + className + ".family() failed.\n" + e.getTargetException());
return;
}
assertTrue(className + ".family() mismatch.", Arrays.equals(values, family));
}
/*
* Gets the private VALUES field only if CodeList is the direct parent.
*/
if (classe.getSuperclass().equals(CodeList.class)) {
fullName = className + ".VALUES";
final Field field;
try {
field = classe.getDeclaredField("VALUES");
} catch (NoSuchFieldException e) {
fail(fullName + " private list is missing.");
return;
}
modifiers = field.getModifiers();
assertTrue(Modifier.isStatic(modifiers));
assertTrue(Modifier.isFinal(modifiers));
assertFalse(Modifier.isPublic(modifiers));
assertFalse(Modifier.isProtected(modifiers));
field.setAccessible(true);
final ArrayList<?> asList;
try {
final Object candidate = field.get(null);
assertEquals(
fullName + " is not an ArrayList.", ArrayList.class, candidate.getClass());
asList = (ArrayList<?>) candidate;
} catch (IllegalAccessException e) {
fail(className + ".VALUES is not accessible.");
return;
}
assertEquals(Arrays.asList(values), asList);
/*
* Verifies if the VALUES ArrayList size was properly sized. We need to access to
* private ArrayList.elementData field in order to perform this check. Tested on
* Sun's JSE 6.0. It is not mandatory to have the VALUES list properly dimensioned;
* it just avoid a little bit of memory reallocation at application startup time.
*/
if (!capacityFailed) {
final int capacity;
try {
final Field candidate = ArrayList.class.getDeclaredField("elementData");
candidate.setAccessible(true);
final Object array = candidate.get(asList);
capacity = ((Object[]) array).length;
} catch (Exception e) {
// Not an error, since this test relies on an implementation-specific method.
capacityFailed = true;
final LogRecord record = new LogRecord(Level.WARNING, e.toString());
record.setThrown(e);
record.setLoggerName(LOGGER.getName());
LOGGER.log(record);
return;
}
assertEquals(fullName + " not properly sized.", asList.size(), capacity);
}
}
/*
* Tries to create a new element.
*/
try {
method = classe.getMethod("valueOf", String.class);
} catch (NoSuchMethodException e) {
return;
}
final CodeList value;
try {
value = classe.cast(method.invoke(null, "Dummy"));
} catch (IllegalAccessException e) {
fail(e.toString());
return;
} catch (InvocationTargetException e) {
java.util.logging.Logger.getGlobal().log(java.util.logging.Level.INFO, "", e);
fail(e.getTargetException().toString());
return;
}
assertEquals("Dummy", value.name());
}
}
| remove check of capacity of arraylist. It accesses an illegal field via reflection. The proposal here is to dump the test section, since there is no other way to get the capacity from the arraylist and the part doesn't seem relevant to the domain of the test. (#2134)
| modules/library/opengis/src/test/java/org/opengis/util/CodeListTest.java | remove check of capacity of arraylist. It accesses an illegal field via reflection. The proposal here is to dump the test section, since there is no other way to get the capacity from the arraylist and the part doesn't seem relevant to the domain of the test. (#2134) |
|
Java | unlicense | 105021b2833ebee94ae2edf1fb80b36062e7e802 | 0 | charlesmadere/smash-ranks-android | package com.garpr.android.activities;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.garpr.android.R;
import com.garpr.android.data.Matches;
import com.garpr.android.data.Matches.MatchesCallback;
import com.garpr.android.data.Players;
import com.garpr.android.data.User;
import com.garpr.android.misc.Analytics;
import com.garpr.android.misc.Constants;
import com.garpr.android.misc.GooglePlayServicesUnavailableException;
import com.garpr.android.misc.RequestCodes;
import com.garpr.android.misc.ResultCodes;
import com.garpr.android.misc.ResultData;
import com.garpr.android.misc.Utils;
import com.garpr.android.models.Match;
import com.garpr.android.models.Player;
import com.garpr.android.models.Region;
import com.garpr.android.models.Result;
import com.garpr.android.models.Tournament;
import java.util.ArrayList;
import java.util.Collections;
public class PlayerActivity extends BaseListActivity implements
MenuItemCompat.OnActionExpandListener,
SearchView.OnQueryTextListener {
private static final String CNAME = PlayerActivity.class.getCanonicalName();
private static final String EXTRA_PLAYER = CNAME + ".EXTRA_PLAYER";
private static final String TAG = PlayerActivity.class.getSimpleName();
private ArrayList<ListItem> mListItems;
private ArrayList<ListItem> mListItemsShown;
private boolean mInUsersRegion;
private boolean mSetMenuItemsVisible;
private Intent mShareIntent;
private MatchesFilter mFilter;
private MenuItem mSearch;
private MenuItem mShare;
private MenuItem mShow;
private MenuItem mShowAll;
private MenuItem mShowLoses;
private MenuItem mShowWins;
private Player mPlayer;
private Player mUserPlayer;
public static void startForResult(final Activity activity, final Player player) {
final Intent intent = new Intent(activity, PlayerActivity.class);
intent.putExtra(EXTRA_PLAYER, player);
activity.startActivityForResult(intent, RequestCodes.REQUEST_DEFAULT);
}
private void createListItems(final ArrayList<Match> matches) {
mListItems = new ArrayList<>();
Tournament lastTournament = null;
for (final Match match : matches) {
final Tournament tournament = match.getTournament();
if (!tournament.equals(lastTournament)) {
lastTournament = tournament;
final ListItem listItem = ListItem.createTournament(tournament);
mListItems.add(listItem);
}
final ListItem listItem = ListItem.createMatch(match);
mListItems.add(listItem);
}
mListItems.trimToSize();
mListItemsShown = mListItems;
}
private void fetchMatches() {
setLoading(true);
final MatchesCallback callback = new MatchesCallback(this, mPlayer.getId()) {
@Override
public void error(final Exception e) {
Log.e(TAG, "Exception when fetching matches for " + mPlayer, e);
showError();
try {
Analytics.report(TAG).setExtra(e).sendEvent(Constants.NETWORK_EXCEPTION, Constants.MATCHES);
} catch (final GooglePlayServicesUnavailableException gpsue) {
Log.w(TAG, "Unable to report matches exception to analytics", gpsue);
}
}
@Override
public void response(final ArrayList<Match> list) {
Collections.sort(list, Match.DATE_ORDER);
mPlayer.setMatches(list);
Players.save(mPlayer);
createListItems(list);
setAdapter(new MatchesAdapter());
final Intent data = new Intent();
data.putExtra(ResultData.PLAYER, mPlayer);
setResult(ResultCodes.PLAYER_UPDATED, data);
}
};
Matches.get(callback);
}
@Override
protected String getActivityName() {
return TAG;
}
@Override
protected String getErrorText() {
return getString(R.string.error_fetching_x_matches, mPlayer.getName());
}
@Override
protected int getOptionsMenu() {
return R.menu.activity_player;
}
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(mPlayer.getName());
final Toolbar toolbar = getToolbar();
toolbar.setSubtitle(getString(R.string.rank_x, mPlayer.getRank()));
mInUsersRegion = User.areWeInTheUsersRegion();
mUserPlayer = User.getPlayer();
if (mPlayer.hasMatches()) {
final ArrayList<Match> matches = mPlayer.getMatches();
Collections.sort(matches, Match.DATE_ORDER);
createListItems(matches);
setAdapter(new MatchesAdapter());
} else {
fetchMatches();
}
}
@Override
protected void onDrawerClosed() {
if (!isLoading()) {
Utils.showMenuItems(mSearch, mShare, mShow);
}
}
@Override
protected void onDrawerOpened() {
MenuItemCompat.collapseActionView(mSearch);
Utils.hideMenuItems(mSearch, mShare, mShow);
}
@Override
public boolean onMenuItemActionCollapse(final MenuItem item) {
mListItemsShown = mListItems;
notifyDataSetChanged();
return true;
}
@Override
public boolean onMenuItemActionExpand(final MenuItem item) {
return true;
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case R.id.activity_player_menu_share:
share();
break;
case R.id.activity_player_menu_show_all:
mShowAll.setEnabled(false);
mShowLoses.setEnabled(true);
mShowWins.setEnabled(true);
mListItemsShown = mListItems;
notifyDataSetChanged();
break;
case R.id.activity_player_menu_show_loses:
mShowAll.setEnabled(true);
mShowLoses.setEnabled(false);
mShowWins.setEnabled(true);
show(Result.LOSE);
break;
case R.id.activity_player_menu_show_wins:
mShowAll.setEnabled(true);
mShowLoses.setEnabled(true);
mShowWins.setEnabled(false);
show(Result.WIN);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
@Override
public boolean onPrepareOptionsMenu(final Menu menu) {
mSearch = menu.findItem(R.id.activity_player_menu_search);
mShare = menu.findItem(R.id.activity_player_menu_share);
mShow = menu.findItem(R.id.activity_player_menu_show);
mShowAll = menu.findItem(R.id.activity_player_menu_show_all);
mShowLoses = menu.findItem(R.id.activity_player_menu_show_loses);
mShowWins = menu.findItem(R.id.activity_player_menu_show_wins);
MenuItemCompat.setOnActionExpandListener(mSearch, this);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(mSearch);
searchView.setQueryHint(getString(R.string.search_matches));
searchView.setOnQueryTextListener(this);
if (mSetMenuItemsVisible) {
Utils.showMenuItems(mSearch, mShare, mShow);
mSetMenuItemsVisible = false;
}
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onQueryTextChange(final String newText) {
mFilter.filter(newText);
return false;
}
@Override
public boolean onQueryTextSubmit(final String query) {
return false;
}
@Override
public void onRefresh() {
super.onRefresh();
if (!isLoading()) {
MenuItemCompat.collapseActionView(mSearch);
fetchMatches();
}
}
@Override
public void onRegionChanged(final Region region) {
super.onRegionChanged(region);
RankingsActivity.start(this);
}
@Override
protected void readIntentData(final Intent intent) {
mPlayer = intent.getParcelableExtra(EXTRA_PLAYER);
}
@Override
protected void setAdapter(final BaseListAdapter adapter) {
super.setAdapter(adapter);
mFilter = new MatchesFilter();
// it's possible for us to have gotten here before onPrepareOptionsMenu() has run
if (Utils.areAnyMenuItemsNull(mSearch, mShare, mShow)) {
mSetMenuItemsVisible = true;
} else {
Utils.showMenuItems(mSearch, mShare, mShow);
}
}
private void share() {
if (mShareIntent == null) {
String text = getString(R.string.x_is_ranked_y_on_gar_pr_z, mPlayer.getName(),
mPlayer.getRank(), mPlayer.getProfileUrl());
if (text.length() > Constants.TWITTER_LENGTH) {
text = getString(R.string.x_on_gar_pr_y, mPlayer.getName(), mPlayer.getProfileUrl());
}
if (text.length() > Constants.TWITTER_LENGTH) {
text = getString(R.string.gar_pr_x, mPlayer.getProfileUrl());
}
if (text.length() > Constants.TWITTER_LENGTH) {
text = mPlayer.getProfileUrl();
}
final String title = getString(R.string.x_on_gar_pr, mPlayer.getName());
mShareIntent = new Intent(Intent.ACTION_SEND)
.putExtra(Intent.EXTRA_TEXT, text)
.putExtra(Intent.EXTRA_TITLE, title)
.setType(Constants.MIMETYPE_TEXT_PLAIN);
mShareIntent = Intent.createChooser(mShareIntent, getString(R.string.share_to));
}
startActivity(mShareIntent);
try {
Analytics.report(TAG).sendEvent(Constants.SHARE, Constants.PLAYER);
} catch (final GooglePlayServicesUnavailableException e) {
Log.w(TAG, "Unable to report share to analytics", e);
}
}
private void show(final Result result) {
final ArrayList<ListItem> listItems = new ArrayList<>(mListItems.size());
for (int i = 0; i < mListItems.size(); ++i) {
final ListItem listItem = mListItems.get(i);
if (listItem.isMatch() && listItem.mMatch.getResult() == result) {
ListItem tournament = null;
for (int j = i - 1; tournament == null; --j) {
final ListItem li = mListItems.get(j);
if (li.isTournament()) {
tournament = li;
}
}
// make sure we haven't already added this tournament to the list
if (!listItems.contains(tournament)) {
listItems.add(tournament);
}
listItems.add(listItem);
}
}
mListItemsShown = listItems;
notifyDataSetChanged();
}
@Override
protected boolean showDrawerIndicator() {
return false;
}
private static final class ListItem {
private Match mMatch;
private Tournament mTournament;
private Type mType;
private static ListItem createMatch(final Match match) {
final ListItem item = new ListItem();
item.mMatch = match;
item.mType = Type.MATCH;
return item;
}
private static ListItem createTournament(final Tournament tournament) {
final ListItem item = new ListItem();
item.mTournament = tournament;
item.mType = Type.TOURNAMENT;
return item;
}
@Override
public boolean equals(final Object o) {
final boolean isEqual;
if (this == o) {
isEqual = true;
} else if (o instanceof ListItem) {
final ListItem li = (ListItem) o;
if (isMatch() && li.isMatch()) {
isEqual = mMatch.equals(li.mMatch);
} else if (isTournament() && li.isTournament()) {
isEqual = mTournament.equals(li.mTournament);
} else {
isEqual = false;
}
} else {
isEqual = false;
}
return isEqual;
}
private boolean isMatch() {
return mType == Type.MATCH;
}
private boolean isTournament() {
return mType == Type.TOURNAMENT;
}
private static enum Type {
MATCH, TOURNAMENT;
private static Type create(final int ordinal) {
final Type type;
if (ordinal == MATCH.ordinal()) {
type = MATCH;
} else if (ordinal == TOURNAMENT.ordinal()) {
type = TOURNAMENT;
} else {
throw new IllegalArgumentException("Ordinal is invalid: \"" + ordinal + "\"");
}
return type;
}
}
}
private final class MatchesAdapter extends BaseListAdapter {
private final int mBgGray;
private final int mBgHighlight;
private final int mColorLose;
private final int mColorWin;
private MatchesAdapter() {
final Resources resources = getResources();
mBgGray = resources.getColor(R.color.gray);
mBgHighlight = resources.getColor(R.color.overlay_bright);
mColorLose = resources.getColor(R.color.lose_pink);
mColorWin = resources.getColor(R.color.win_green);
}
@Override
public int getItemCount() {
return mListItemsShown.size();
}
@Override
public int getItemViewType(final int position) {
return mListItemsShown.get(position).mType.ordinal();
}
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
final ListItem listItem = mListItemsShown.get(position);
if (listItem.isMatch()) {
final MatchViewHolder viewHolder = (MatchViewHolder) holder;
viewHolder.mOpponent.setText(listItem.mMatch.getOpponentName());
if (listItem.mMatch.isWin()) {
viewHolder.mOpponent.setTextColor(mColorWin);
} else {
viewHolder.mOpponent.setTextColor(mColorLose);
}
if (mInUsersRegion && mUserPlayer != null) {
final String opponentId = listItem.mMatch.getOpponentId();
if (opponentId.equals(mUserPlayer.getId())) {
viewHolder.mRoot.setBackgroundColor(mBgHighlight);
} else {
viewHolder.mRoot.setBackgroundColor(mBgGray);
}
}
} else if (listItem.isTournament()) {
final TournamentViewHolder viewHolder = (TournamentViewHolder) holder;
viewHolder.mDate.setText(listItem.mTournament.getDate());
viewHolder.mName.setText(listItem.mTournament.getName());
}
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(final ViewGroup parent,
final int viewType) {
final LayoutInflater inflater = getLayoutInflater();
final ListItem.Type listItemType = ListItem.Type.create(viewType);
final View view;
final RecyclerView.ViewHolder holder;
switch (listItemType) {
case MATCH:
view = inflater.inflate(R.layout.model_match, parent, false);
holder = new MatchViewHolder(view);
break;
case TOURNAMENT:
view = inflater.inflate(R.layout.separator_tournament, parent, false);
holder = new TournamentViewHolder(view);
break;
default:
throw new RuntimeException("Illegal ListItem Type detected: " + viewType);
}
return holder;
}
}
private final class MatchesFilter extends Filter {
@Override
protected FilterResults performFiltering(final CharSequence constraint) {
final ArrayList<ListItem> listItems = new ArrayList<>(mListItems.size());
final String query = constraint.toString().trim().toLowerCase();
for (int i = 0; i < mListItems.size(); ++i) {
final ListItem match = mListItems.get(i);
if (match.isMatch()) {
final String name = match.mMatch.getOpponentName().toLowerCase();
if (name.contains(query)) {
// So we've now found a match with an opponent name that matches what the
// user typed into the search field. Now let's find its corresponding
// Tournament ListItem.
ListItem tournament = null;
for (int j = i - 1; tournament == null; --j) {
final ListItem li = mListItems.get(j);
if (li.isTournament()) {
tournament = li;
}
}
// make sure we haven't already added this tournament to the list
if (!listItems.contains(tournament)) {
listItems.add(tournament);
}
listItems.add(match);
}
}
}
final FilterResults results = new FilterResults();
results.count = listItems.size();
results.values = listItems;
return results;
}
@Override
@SuppressWarnings("unchecked")
protected void publishResults(final CharSequence constraint, final FilterResults results) {
mListItemsShown = (ArrayList<ListItem>) results.values;
notifyDataSetChanged();
}
}
private static final class BufferViewHolder extends RecyclerView.ViewHolder {
private BufferViewHolder(final View view) {
super(view);
}
}
private static final class MatchViewHolder extends RecyclerView.ViewHolder {
private final FrameLayout mRoot;
private final TextView mOpponent;
private MatchViewHolder(final View view) {
super(view);
mRoot = (FrameLayout) view.findViewById(R.id.model_match_root);
mOpponent = (TextView) view.findViewById(R.id.model_match_opponent);
}
}
private static final class TournamentViewHolder extends RecyclerView.ViewHolder {
private final TextView mDate;
private final TextView mName;
private TournamentViewHolder(final View view) {
super(view);
mDate = (TextView) view.findViewById(R.id.separator_tournament_date);
mName = (TextView) view.findViewById(R.id.separator_tournament_name);
}
}
}
| smash-ranks-android/app/src/main/java/com/garpr/android/activities/PlayerActivity.java | package com.garpr.android.activities;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.garpr.android.R;
import com.garpr.android.data.Matches;
import com.garpr.android.data.Matches.MatchesCallback;
import com.garpr.android.data.Players;
import com.garpr.android.data.User;
import com.garpr.android.misc.Analytics;
import com.garpr.android.misc.Constants;
import com.garpr.android.misc.GooglePlayServicesUnavailableException;
import com.garpr.android.misc.RequestCodes;
import com.garpr.android.misc.ResultCodes;
import com.garpr.android.misc.ResultData;
import com.garpr.android.misc.Utils;
import com.garpr.android.models.Match;
import com.garpr.android.models.Player;
import com.garpr.android.models.Region;
import com.garpr.android.models.Result;
import com.garpr.android.models.Tournament;
import java.util.ArrayList;
import java.util.Collections;
public class PlayerActivity extends BaseListActivity implements
MenuItemCompat.OnActionExpandListener,
SearchView.OnQueryTextListener {
private static final String CNAME = PlayerActivity.class.getCanonicalName();
private static final String EXTRA_PLAYER = CNAME + ".EXTRA_PLAYER";
private static final String TAG = PlayerActivity.class.getSimpleName();
private ArrayList<ListItem> mListItems;
private ArrayList<ListItem> mListItemsShown;
private boolean mInUsersRegion;
private boolean mSetMenuItemsVisible;
private Intent mShareIntent;
private MatchesFilter mFilter;
private MenuItem mSearch;
private MenuItem mShare;
private MenuItem mShow;
private MenuItem mShowAll;
private MenuItem mShowLoses;
private MenuItem mShowWins;
private Player mPlayer;
private Player mUserPlayer;
public static void startForResult(final Activity activity, final Player player) {
final Intent intent = new Intent(activity, PlayerActivity.class);
intent.putExtra(EXTRA_PLAYER, player);
activity.startActivityForResult(intent, RequestCodes.REQUEST_DEFAULT);
}
private void createListItems(final ArrayList<Match> matches) {
mListItems = new ArrayList<>();
Tournament lastTournament = null;
for (final Match match : matches) {
final Tournament tournament = match.getTournament();
if (!tournament.equals(lastTournament)) {
if (lastTournament != null) {
mListItems.add(ListItem.createBuffer());
}
lastTournament = tournament;
final ListItem listItem = ListItem.createTournament(tournament);
mListItems.add(listItem);
}
final ListItem listItem = ListItem.createMatch(match);
mListItems.add(listItem);
}
mListItems.trimToSize();
mListItemsShown = mListItems;
}
private void fetchMatches() {
setLoading(true);
final MatchesCallback callback = new MatchesCallback(this, mPlayer.getId()) {
@Override
public void error(final Exception e) {
Log.e(TAG, "Exception when fetching matches for " + mPlayer, e);
showError();
try {
Analytics.report(TAG).setExtra(e).sendEvent(Constants.NETWORK_EXCEPTION, Constants.MATCHES);
} catch (final GooglePlayServicesUnavailableException gpsue) {
Log.w(TAG, "Unable to report matches exception to analytics", gpsue);
}
}
@Override
public void response(final ArrayList<Match> list) {
Collections.sort(list, Match.DATE_ORDER);
mPlayer.setMatches(list);
Players.save(mPlayer);
createListItems(list);
setAdapter(new MatchesAdapter());
final Intent data = new Intent();
data.putExtra(ResultData.PLAYER, mPlayer);
setResult(ResultCodes.PLAYER_UPDATED, data);
}
};
Matches.get(callback);
}
@Override
protected String getActivityName() {
return TAG;
}
@Override
protected String getErrorText() {
return getString(R.string.error_fetching_x_matches, mPlayer.getName());
}
@Override
protected int getOptionsMenu() {
return R.menu.activity_player;
}
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(mPlayer.getName());
final Toolbar toolbar = getToolbar();
toolbar.setSubtitle(getString(R.string.rank_x, mPlayer.getRank()));
mInUsersRegion = User.areWeInTheUsersRegion();
mUserPlayer = User.getPlayer();
if (mPlayer.hasMatches()) {
final ArrayList<Match> matches = mPlayer.getMatches();
Collections.sort(matches, Match.DATE_ORDER);
createListItems(matches);
setAdapter(new MatchesAdapter());
} else {
fetchMatches();
}
}
@Override
protected void onDrawerClosed() {
if (!isLoading()) {
Utils.showMenuItems(mSearch, mShare, mShow);
}
}
@Override
protected void onDrawerOpened() {
MenuItemCompat.collapseActionView(mSearch);
Utils.hideMenuItems(mSearch, mShare, mShow);
}
@Override
public boolean onMenuItemActionCollapse(final MenuItem item) {
mListItemsShown = mListItems;
notifyDataSetChanged();
return true;
}
@Override
public boolean onMenuItemActionExpand(final MenuItem item) {
return true;
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case R.id.activity_player_menu_share:
share();
break;
case R.id.activity_player_menu_show_all:
mShowAll.setEnabled(false);
mShowLoses.setEnabled(true);
mShowWins.setEnabled(true);
mListItemsShown = mListItems;
notifyDataSetChanged();
break;
case R.id.activity_player_menu_show_loses:
mShowAll.setEnabled(true);
mShowLoses.setEnabled(false);
mShowWins.setEnabled(true);
show(Result.LOSE);
break;
case R.id.activity_player_menu_show_wins:
mShowAll.setEnabled(true);
mShowLoses.setEnabled(true);
mShowWins.setEnabled(false);
show(Result.WIN);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
@Override
public boolean onPrepareOptionsMenu(final Menu menu) {
mSearch = menu.findItem(R.id.activity_player_menu_search);
mShare = menu.findItem(R.id.activity_player_menu_share);
mShow = menu.findItem(R.id.activity_player_menu_show);
mShowAll = menu.findItem(R.id.activity_player_menu_show_all);
mShowLoses = menu.findItem(R.id.activity_player_menu_show_loses);
mShowWins = menu.findItem(R.id.activity_player_menu_show_wins);
MenuItemCompat.setOnActionExpandListener(mSearch, this);
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(mSearch);
searchView.setQueryHint(getString(R.string.search_matches));
searchView.setOnQueryTextListener(this);
if (mSetMenuItemsVisible) {
Utils.showMenuItems(mSearch, mShare, mShow);
mSetMenuItemsVisible = false;
}
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onQueryTextChange(final String newText) {
mFilter.filter(newText);
return false;
}
@Override
public boolean onQueryTextSubmit(final String query) {
return false;
}
@Override
public void onRefresh() {
super.onRefresh();
if (!isLoading()) {
MenuItemCompat.collapseActionView(mSearch);
fetchMatches();
}
}
@Override
public void onRegionChanged(final Region region) {
super.onRegionChanged(region);
RankingsActivity.start(this);
}
@Override
protected void readIntentData(final Intent intent) {
mPlayer = intent.getParcelableExtra(EXTRA_PLAYER);
}
@Override
protected void setAdapter(final BaseListAdapter adapter) {
super.setAdapter(adapter);
mFilter = new MatchesFilter();
// it's possible for us to have gotten here before onPrepareOptionsMenu() has run
if (Utils.areAnyMenuItemsNull(mSearch, mShare, mShow)) {
mSetMenuItemsVisible = true;
} else {
Utils.showMenuItems(mSearch, mShare, mShow);
}
}
private void share() {
if (mShareIntent == null) {
String text = getString(R.string.x_is_ranked_y_on_gar_pr_z, mPlayer.getName(),
mPlayer.getRank(), mPlayer.getProfileUrl());
if (text.length() > Constants.TWITTER_LENGTH) {
text = getString(R.string.x_on_gar_pr_y, mPlayer.getName(), mPlayer.getProfileUrl());
}
if (text.length() > Constants.TWITTER_LENGTH) {
text = getString(R.string.gar_pr_x, mPlayer.getProfileUrl());
}
if (text.length() > Constants.TWITTER_LENGTH) {
text = mPlayer.getProfileUrl();
}
final String title = getString(R.string.x_on_gar_pr, mPlayer.getName());
mShareIntent = new Intent(Intent.ACTION_SEND)
.putExtra(Intent.EXTRA_TEXT, text)
.putExtra(Intent.EXTRA_TITLE, title)
.setType(Constants.MIMETYPE_TEXT_PLAIN);
mShareIntent = Intent.createChooser(mShareIntent, getString(R.string.share_to));
}
startActivity(mShareIntent);
try {
Analytics.report(TAG).sendEvent(Constants.SHARE, Constants.PLAYER);
} catch (final GooglePlayServicesUnavailableException e) {
Log.w(TAG, "Unable to report share to analytics", e);
}
}
private void show(final Result result) {
final ArrayList<ListItem> listItems = new ArrayList<>(mListItems.size());
for (int i = 0; i < mListItems.size(); ++i) {
final ListItem listItem = mListItems.get(i);
if (listItem.isMatch() && listItem.mMatch.getResult() == result) {
ListItem tournament = null;
for (int j = i - 1; tournament == null; --j) {
final ListItem li = mListItems.get(j);
if (li.isTournament()) {
tournament = li;
}
}
// make sure we haven't already added this tournament to the list
if (!listItems.contains(tournament)) {
listItems.add(tournament);
}
listItems.add(listItem);
}
}
mListItemsShown = listItems;
notifyDataSetChanged();
}
@Override
protected boolean showDrawerIndicator() {
return false;
}
private static final class ListItem {
private Match mMatch;
private Tournament mTournament;
private Type mType;
private static ListItem createBuffer() {
final ListItem item = new ListItem();
item.mType = Type.BUFFER;
return item;
}
private static ListItem createMatch(final Match match) {
final ListItem item = new ListItem();
item.mMatch = match;
item.mType = Type.MATCH;
return item;
}
private static ListItem createTournament(final Tournament tournament) {
final ListItem item = new ListItem();
item.mTournament = tournament;
item.mType = Type.TOURNAMENT;
return item;
}
@Override
public boolean equals(final Object o) {
final boolean isEqual;
if (this == o) {
isEqual = true;
} else if (o instanceof ListItem) {
final ListItem li = (ListItem) o;
if (isMatch() && li.isMatch()) {
isEqual = mMatch.equals(li.mMatch);
} else if (isTournament() && li.isTournament()) {
isEqual = mTournament.equals(li.mTournament);
} else {
isEqual = false;
}
} else {
isEqual = false;
}
return isEqual;
}
private boolean isBuffer() {
return mType == Type.BUFFER;
}
private boolean isMatch() {
return mType == Type.MATCH;
}
private boolean isTournament() {
return mType == Type.TOURNAMENT;
}
private static enum Type {
BUFFER, MATCH, TOURNAMENT;
private static Type create(final int ordinal) {
final Type type;
if (ordinal == BUFFER.ordinal()) {
type = BUFFER;
} else if (ordinal == MATCH.ordinal()) {
type = MATCH;
} else if (ordinal == TOURNAMENT.ordinal()) {
type = TOURNAMENT;
} else {
throw new IllegalArgumentException("Ordinal is invalid: \"" + ordinal + "\"");
}
return type;
}
}
}
private final class MatchesAdapter extends BaseListAdapter {
private final int mBgGray;
private final int mBgHighlight;
private final int mColorLose;
private final int mColorWin;
private MatchesAdapter() {
final Resources resources = getResources();
mBgGray = resources.getColor(R.color.gray);
mBgHighlight = resources.getColor(R.color.overlay_bright);
mColorLose = resources.getColor(R.color.lose_pink);
mColorWin = resources.getColor(R.color.win_green);
}
@Override
public int getItemCount() {
return mListItemsShown.size();
}
@Override
public int getItemViewType(final int position) {
return mListItemsShown.get(position).mType.ordinal();
}
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
final ListItem listItem = mListItemsShown.get(position);
if (listItem.isMatch()) {
final MatchViewHolder viewHolder = (MatchViewHolder) holder;
viewHolder.mOpponent.setText(listItem.mMatch.getOpponentName());
if (listItem.mMatch.isWin()) {
viewHolder.mOpponent.setTextColor(mColorWin);
} else {
viewHolder.mOpponent.setTextColor(mColorLose);
}
if (mInUsersRegion && mUserPlayer != null) {
final String opponentId = listItem.mMatch.getOpponentId();
if (opponentId.equals(mUserPlayer.getId())) {
viewHolder.mRoot.setBackgroundColor(mBgHighlight);
} else {
viewHolder.mRoot.setBackgroundColor(mBgGray);
}
}
} else if (listItem.isTournament()) {
final TournamentViewHolder viewHolder = (TournamentViewHolder) holder;
viewHolder.mDate.setText(listItem.mTournament.getDate());
viewHolder.mName.setText(listItem.mTournament.getName());
}
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(final ViewGroup parent,
final int viewType) {
final LayoutInflater inflater = getLayoutInflater();
final ListItem.Type listItemType = ListItem.Type.create(viewType);
final View view;
final RecyclerView.ViewHolder holder;
switch (listItemType) {
case BUFFER:
view = inflater.inflate(R.layout.buffer, parent, false);
holder = new BufferViewHolder(view);
break;
case MATCH:
view = inflater.inflate(R.layout.model_match, parent, false);
holder = new MatchViewHolder(view);
break;
case TOURNAMENT:
view = inflater.inflate(R.layout.separator_tournament, parent, false);
holder = new TournamentViewHolder(view);
break;
default:
throw new RuntimeException("Illegal ListItem Type detected: " + viewType);
}
return holder;
}
}
private final class MatchesFilter extends Filter {
@Override
protected FilterResults performFiltering(final CharSequence constraint) {
final ArrayList<ListItem> listItems = new ArrayList<>(mListItems.size());
final String query = constraint.toString().trim().toLowerCase();
for (int i = 0; i < mListItems.size(); ++i) {
final ListItem match = mListItems.get(i);
if (match.isMatch()) {
final String name = match.mMatch.getOpponentName().toLowerCase();
if (name.contains(query)) {
// So we've now found a match with an opponent name that matches what the
// user typed into the search field. Now let's find its corresponding
// Tournament ListItem.
ListItem tournament = null;
for (int j = i - 1; tournament == null; --j) {
final ListItem li = mListItems.get(j);
if (li.isTournament()) {
tournament = li;
}
}
// make sure we haven't already added this tournament to the list
if (!listItems.contains(tournament)) {
listItems.add(tournament);
}
listItems.add(match);
}
}
}
final FilterResults results = new FilterResults();
results.count = listItems.size();
results.values = listItems;
return results;
}
@Override
@SuppressWarnings("unchecked")
protected void publishResults(final CharSequence constraint, final FilterResults results) {
mListItemsShown = (ArrayList<ListItem>) results.values;
notifyDataSetChanged();
}
}
private static final class BufferViewHolder extends RecyclerView.ViewHolder {
private BufferViewHolder(final View view) {
super(view);
}
}
private static final class MatchViewHolder extends RecyclerView.ViewHolder {
private final FrameLayout mRoot;
private final TextView mOpponent;
private MatchViewHolder(final View view) {
super(view);
mRoot = (FrameLayout) view.findViewById(R.id.model_match_root);
mOpponent = (TextView) view.findViewById(R.id.model_match_opponent);
}
}
private static final class TournamentViewHolder extends RecyclerView.ViewHolder {
private final TextView mDate;
private final TextView mName;
private TournamentViewHolder(final View view) {
super(view);
mDate = (TextView) view.findViewById(R.id.separator_tournament_date);
mName = (TextView) view.findViewById(R.id.separator_tournament_name);
}
}
}
| removed buffer view from PlayerActivity
| smash-ranks-android/app/src/main/java/com/garpr/android/activities/PlayerActivity.java | removed buffer view from PlayerActivity |
|
Java | unlicense | 7fe8e039eea9cca973e1efb44b73a56a006c11c7 | 0 | MyEssentials/MyEssentials-Core | package myessentials.chat.api;
import myessentials.exception.FormatException;
import myessentials.utils.ColorUtils;
import net.minecraft.util.ChatComponentStyle;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.ChatStyle;
import net.minecraft.util.IChatComponent;
import org.apache.commons.lang.StringUtils;
public class ChatComponentFormatted extends ChatComponentStyle {
public ChatComponentFormatted(String format, Object... args) {
String[] components = StringUtils.split(format, "{}");
int argNumber = 0;
for (String component : components) {
String[] parts = component.split("\\|");
if(parts.length == 2) {
ChatStyle chatStyle = getStyle(parts[0]);
String actualText = parts[1];
while (actualText.contains("%s")) {
actualText = actualText.replaceFirst("%s", args[argNumber++].toString());
}
//text += actualText;
this.appendSibling(new ChatComponentText(actualText).setChatStyle(chatStyle));
} else if (parts.length == 1 && parts[0].equals("%s")) {
if (args[argNumber] instanceof IChatFormat) {
IChatComponent formattedArgument = ((IChatFormat) args[argNumber++]).toChatMessage();
//this.text += formattedArgument.getUnformattedText();
this.appendSibling(formattedArgument);
} else {
throw new FormatException("Argument at position " + argNumber + " does not implement IChatFormat interface");
}
} else {
throw new FormatException("Format " + component + " is not valid. Valid format: [modifiers|text]");
}
}
}
/**
* Converts the modifiers String to a ChatStyle
* [modifiers| some text]
* ^^^^^^^^ ^^^^^^^^^
* STYLE for THIS TEXT
*/
private ChatStyle getStyle(String modifiers) {
ChatStyle chatStyle = new ChatStyle();
for (char c : modifiers.toCharArray()) {
applyModifier(chatStyle, c);
}
return chatStyle;
}
/**
* Applies modifier to the style
* Returns whether or not the modifier was valid
*/
private boolean applyModifier(ChatStyle chatStyle, char modifier) {
if (modifier >= '0' && modifier <= '9' || modifier >= 'a' && modifier <= 'f') {
chatStyle.setColor(ColorUtils.colorMap.get(modifier));
return true;
}
switch (modifier) {
case 'k': chatStyle.setObfuscated(true); return true;
case 'l': chatStyle.setBold(true); return true;
case 'm': chatStyle.setStrikethrough(true); return true;
case 'n': chatStyle.setUnderlined(true); return true;
case 'o': chatStyle.setItalic(true); return true;
}
return false;
}
@Override
public String getUnformattedTextForChat() {
return "";
}
@Override
public IChatComponent createCopy() {
return null;
}
}
| src/main/java/myessentials/chat/api/ChatComponentFormatted.java | package myessentials.chat.api;
import myessentials.exception.FormatException;
import myessentials.utils.ColorUtils;
import net.minecraft.util.ChatComponentStyle;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.ChatStyle;
import net.minecraft.util.IChatComponent;
import org.apache.commons.lang.StringUtils;
public class ChatComponentFormatted extends ChatComponentStyle {
public ChatComponentFormatted(String format, Object... args) {
String[] components = StringUtils.split(format, "[]");
int argNumber = 0;
for (String component : components) {
String[] parts = component.split("\\|");
if(parts.length == 2) {
ChatStyle chatStyle = getStyle(parts[0]);
String actualText = parts[1];
while (actualText.contains("%s")) {
actualText = actualText.replaceFirst("%s", args[argNumber++].toString());
}
//text += actualText;
this.appendSibling(new ChatComponentText(actualText).setChatStyle(chatStyle));
} else if (parts.length == 1 && parts[0].equals("%s")) {
if (args[argNumber] instanceof IChatFormat) {
IChatComponent formattedArgument = ((IChatFormat) args[argNumber++]).toChatMessage();
//this.text += formattedArgument.getUnformattedText();
this.appendSibling(formattedArgument);
} else {
throw new FormatException("Argument at position " + argNumber + " does not implement IChatFormat interface");
}
} else {
throw new FormatException("Format " + component + " is not valid. Valid format: [modifiers|text]");
}
}
}
/**
* Converts the modifiers String to a ChatStyle
* [modifiers| some text]
* ^^^^^^^^ ^^^^^^^^^
* STYLE for THIS TEXT
*/
private ChatStyle getStyle(String modifiers) {
ChatStyle chatStyle = new ChatStyle();
for (char c : modifiers.toCharArray()) {
applyModifier(chatStyle, c);
}
return chatStyle;
}
/**
* Applies modifier to the style
* Returns whether or not the modifier was valid
*/
private boolean applyModifier(ChatStyle chatStyle, char modifier) {
if (modifier >= '0' && modifier <= '9' || modifier >= 'a' && modifier <= 'f') {
chatStyle.setColor(ColorUtils.colorMap.get(modifier));
return true;
}
switch (modifier) {
case 'k': chatStyle.setObfuscated(true); return true;
case 'l': chatStyle.setBold(true); return true;
case 'm': chatStyle.setStrikethrough(true); return true;
case 'n': chatStyle.setUnderlined(true); return true;
case 'o': chatStyle.setItalic(true); return true;
}
return false;
}
@Override
public String getUnformattedTextForChat() {
return "";
}
@Override
public IChatComponent createCopy() {
return null;
}
}
| Changed from [] to {} for chat component identifier in the new format
| src/main/java/myessentials/chat/api/ChatComponentFormatted.java | Changed from [] to {} for chat component identifier in the new format |
|
Java | apache-2.0 | f915a3cf13d91fa83be6e6f2dd55b33c8f1d8b50 | 0 | allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.process;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.openapi.util.Key;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
/**
* <p>This process handler supports ANSI coloring.</p>
* <p>Although it supports the {@link KillableProcessHandler"soft-kill" feature}, it is turned off by default for compatibility reasons.
* To turn it on either call {@link #setShouldKillProcessSoftly(boolean)}, or extend from {@link KillableColoredProcessHandler}.
*/
public class ColoredProcessHandler extends KillableProcessHandler implements AnsiEscapeDecoder.ColoredTextAcceptor {
private final AnsiEscapeDecoder myAnsiEscapeDecoder = new AnsiEscapeDecoder();
private final List<AnsiEscapeDecoder.ColoredTextAcceptor> myColoredTextListeners = new ArrayList<>();
public ColoredProcessHandler(@NotNull GeneralCommandLine commandLine) throws ExecutionException {
super(commandLine);
setShouldKillProcessSoftly(false);
}
/**
* {@code commandLine} must not be not empty (for correct thread attribution in the stacktrace)
*/
public ColoredProcessHandler(@NotNull Process process, /*@NotNull*/ String commandLine) {
super(process, commandLine);
setShouldKillProcessSoftly(false);
}
/**
* {@code commandLine} must not be not empty (for correct thread attribution in the stacktrace)
*/
public ColoredProcessHandler(@NotNull Process process, /*@NotNull*/ String commandLine, @NotNull Charset charset) {
super(process, commandLine, charset);
setShouldKillProcessSoftly(false);
}
@Override
public final void notifyTextAvailable(@NotNull final String text, @NotNull final Key outputType) {
myAnsiEscapeDecoder.escapeText(text, outputType, this);
}
/**
* Override this method to handle colored text lines.
* Overrides should call super.coloredTextAvailable() if they want to pass lines to registered listeners
* To receive chunks of data instead of fragments inherit your class from ColoredChunksAcceptor interface and
* override coloredChunksAvailable method.
*/
@Override
public void coloredTextAvailable(@NotNull String text, @NotNull Key attributes) {
textAvailable(text, attributes);
notifyColoredListeners(text, attributes);
}
protected void notifyColoredListeners(String text, Key attributes) { //TODO: call super.coloredTextAvailable after textAvailable removed
for (AnsiEscapeDecoder.ColoredTextAcceptor listener: myColoredTextListeners) {
listener.coloredTextAvailable(text, attributes);
}
}
public void addColoredTextListener(AnsiEscapeDecoder.ColoredTextAcceptor listener) {
myColoredTextListeners.add(listener);
}
public void removeColoredTextListener(AnsiEscapeDecoder.ColoredTextAcceptor listener) {
myColoredTextListeners.remove(listener);
}
/**
* @deprecated Inheritors should override coloredTextAvailable method
* or implement {@link com.intellij.execution.process.AnsiEscapeDecoder.ColoredChunksAcceptor}
* and override method coloredChunksAvailable to process colored chunks.
* To be removed in IDEA 14.
*/
@Deprecated
@ApiStatus.ScheduledForRemoval(inVersion = "2014")
protected void textAvailable(final String text, final Key attributes) {
super.notifyTextAvailable(text, attributes);
}
} | platform/platform-impl/src/com/intellij/execution/process/ColoredProcessHandler.java | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.process;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.openapi.util.Key;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
/**
* <p>This process handler supports ANSI coloring.</p>
* <p>Although it supports the {@link KillableProcessHandler"soft-kill" feature}, it is turned off by default for compatibility reasons.
* To turn it on either call {@link #setShouldKillProcessSoftly(boolean)}, or extend from {@link KillableColoredProcessHandler}.
*/
public class ColoredProcessHandler extends KillableProcessHandler implements AnsiEscapeDecoder.ColoredTextAcceptor {
private final AnsiEscapeDecoder myAnsiEscapeDecoder = new AnsiEscapeDecoder();
private final List<AnsiEscapeDecoder.ColoredTextAcceptor> myColoredTextListeners = new ArrayList<>();
public ColoredProcessHandler(@NotNull GeneralCommandLine commandLine) throws ExecutionException {
super(commandLine);
setShouldKillProcessSoftly(false);
}
/**
* {@code commandLine} must not be not empty (for correct thread attribution in the stacktrace)
*/
public ColoredProcessHandler(@NotNull Process process, /*@NotNull*/ String commandLine) {
super(process, commandLine);
setShouldKillProcessSoftly(false);
}
/**
* {@code commandLine} must not be not empty (for correct thread attribution in the stacktrace)
*/
public ColoredProcessHandler(@NotNull Process process, /*@NotNull*/ String commandLine, @NotNull Charset charset) {
super(process, commandLine, charset);
setShouldKillProcessSoftly(false);
}
@Override
public final void notifyTextAvailable(@NotNull final String text, @NotNull final Key outputType) {
myAnsiEscapeDecoder.escapeText(text, outputType, this);
}
/**
* Override this method to handle colored text lines.
* Overrides should call super.coloredTextAvailable() if they want to pass lines to registered listeners
* To receive chunks of data instead of fragments inherit your class from ColoredChunksAcceptor interface and
* override coloredChunksAvailable method.
*/
@Override
public void coloredTextAvailable(@NotNull String text, @NotNull Key attributes) {
notifyColoredListeners(text, attributes);
}
protected void notifyColoredListeners(String text, Key attributes) { //TODO: call super.coloredTextAvailable after textAvailable removed
for (AnsiEscapeDecoder.ColoredTextAcceptor listener: myColoredTextListeners) {
listener.coloredTextAvailable(text, attributes);
}
}
public void addColoredTextListener(AnsiEscapeDecoder.ColoredTextAcceptor listener) {
myColoredTextListeners.add(listener);
}
public void removeColoredTextListener(AnsiEscapeDecoder.ColoredTextAcceptor listener) {
myColoredTextListeners.remove(listener);
}
}
| Revert "Remove deprecated method"
This reverts commit 5d15a74d
GitOrigin-RevId: 74ed8f163f9cf0fa7cec16feb05947df2297723d | platform/platform-impl/src/com/intellij/execution/process/ColoredProcessHandler.java | Revert "Remove deprecated method" |
|
Java | apache-2.0 | a69a472e7191eff7dbb26e03f2a66a750fb408c1 | 0 | romainreuillon/JGlobus,gbehrmann/JGlobus,dCache/JGlobus,romainreuillon/JGlobus,jrevillard/JGlobus,gbehrmann/JGlobus,romainreuillon/JGlobus,ellert/JGlobus,ellert/JGlobus,jrevillard/JGlobus,dCache/JGlobus,gridftp/Gridftp,ellert/JGlobus,gridftp/Gridftp,gridftp/Gridftp,jglobus/JGlobus,jglobus/JGlobus,jglobus/JGlobus,jrevillard/JGlobus | /*
* Copyright 1999-2010 University of Chicago
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied.
*
* See the License for the specific language governing permissions and limitations under the License.
*/
package org.globus.gsi.stores;
import org.globus.gsi.provider.SigningPolicyStore;
import org.globus.gsi.provider.SigningPolicyStoreException;
import org.globus.gsi.provider.SigningPolicyStoreParameters;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;
import java.io.IOException;
import java.net.URI;
import java.security.InvalidAlgorithmParameterException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.security.auth.x500.X500Principal;
import org.globus.gsi.SigningPolicy;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
/**
* FILL ME
*
* @author [email protected]
*/
public class ResourceSigningPolicyStore implements SigningPolicyStore {
private PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
private Map<URI, ResourceSigningPolicy> signingPolicyFileMap = new HashMap<URI, ResourceSigningPolicy>();
private Map<String, SigningPolicy> policyMap = new HashMap<String, SigningPolicy>();
private ResourceSigningPolicyStoreParameters parameters;
private Log logger = LogFactory.getLog(ResourceSigningPolicyStore.class.getCanonicalName());
private final Map<String, Long> invalidPoliciesCache = new HashMap<String, Long>();
private final static long CACHE_TIME_MILLIS = 3600*1000;
private String oldLocations = null;
private long lastUpdate = 0;
public ResourceSigningPolicyStore(SigningPolicyStoreParameters param) throws InvalidAlgorithmParameterException {
if (param == null) {
throw new IllegalArgumentException();
}
if (!(param instanceof ResourceSigningPolicyStoreParameters)) {
throw new InvalidAlgorithmParameterException();
}
this.parameters = (ResourceSigningPolicyStoreParameters) param;
}
public SigningPolicy getSigningPolicy(X500Principal caPrincipal) throws SigningPolicyStoreException {
if (caPrincipal == null) {
return null;
}
loadPolicies();
return this.policyMap.get(caPrincipal.getName());
}
private void loadPolicies() throws SigningPolicyStoreException {
String locations = this.parameters.getTrustRootLocations();
Resource[] resources;
long curTime = System.currentTimeMillis();
if(locations.equals(this.oldLocations) && (curTime - lastUpdate > CACHE_TIME_MILLIS))
{
return;
}
try {
resources = resolver.getResources(locations);
} catch (IOException e) {
throw new SigningPolicyStoreException(e);
}
Map<String, SigningPolicy> newPolicyMap =
new HashMap<String, SigningPolicy>();
Map<URI, ResourceSigningPolicy> newPolicyFileMap =
new HashMap<URI, ResourceSigningPolicy>();
long now = System.currentTimeMillis();
for (Resource resource : resources) {
if (!resource.isReadable()) {
logger.debug("Cannot read: " + resource.getFilename());
continue;
}
String filename = resource.getFilename();
Long cacheTime = invalidPoliciesCache.get(filename);
if ((cacheTime != null) && (cacheTime - now < 10*CACHE_TIME_MILLIS)) {
continue;
}
try {
loadSigningPolicy(resource, newPolicyMap, newPolicyFileMap);
} catch (Exception e) {
if (!invalidPoliciesCache.containsKey(filename)) {
logger.warn("Failed to load signing policy: " + filename, e);
invalidPoliciesCache.put(filename, now);
}
}
}
this.policyMap = newPolicyMap;
this.signingPolicyFileMap = newPolicyFileMap;
this.oldLocations = locations;
}
private void loadSigningPolicy(
Resource policyResource, Map<String, SigningPolicy> policyMapToLoad,
Map<URI, ResourceSigningPolicy> currentPolicyFileMap) throws SigningPolicyStoreException {
URI uri;
if (!policyResource.isReadable()) {
throw new SigningPolicyStoreException("Cannot read file");
}
try {
uri = policyResource.getURI();
} catch (IOException e) {
throw new SigningPolicyStoreException(e);
}
ResourceSigningPolicy filePolicy = this.signingPolicyFileMap.get(uri);
if (filePolicy == null) {
try {
filePolicy = new ResourceSigningPolicy(policyResource);
} catch (ResourceStoreException e) {
throw new SigningPolicyStoreException(e);
}
}
Collection<SigningPolicy> policies = filePolicy.getSigningPolicies();
currentPolicyFileMap.put(uri, filePolicy);
if (policies != null) {
for (SigningPolicy policy : policies) {
policyMapToLoad.put(policy.getCASubjectDN().getName(), policy);
}
}
}
}
| ssl-proxies/src/main/java/org/globus/gsi/stores/ResourceSigningPolicyStore.java | /*
* Copyright 1999-2010 University of Chicago
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied.
*
* See the License for the specific language governing permissions and limitations under the License.
*/
package org.globus.gsi.stores;
import org.globus.gsi.provider.SigningPolicyStore;
import org.globus.gsi.provider.SigningPolicyStoreException;
import org.globus.gsi.provider.SigningPolicyStoreParameters;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;
import java.io.IOException;
import java.net.URI;
import java.security.InvalidAlgorithmParameterException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.security.auth.x500.X500Principal;
import org.globus.gsi.SigningPolicy;
import org.globus.gsi.util.CertificateIOUtil;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
/**
* FILL ME
*
* @author [email protected]
*/
public class ResourceSigningPolicyStore implements SigningPolicyStore {
private PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
private Map<URI, ResourceSigningPolicy> signingPolicyFileMap = new HashMap<URI, ResourceSigningPolicy>();
private Map<String, SigningPolicy> policyMap = new HashMap<String, SigningPolicy>();
private ResourceSigningPolicyStoreParameters parameters;
private Log logger = LogFactory.getLog(ResourceSigningPolicyStore.class.getCanonicalName());
private final Map<String, Long> invalidPoliciesCache = new HashMap<String, Long>();
private final Map<String, Long> validPoliciesCache = new HashMap<String, Long>();
private final static long CACHE_TIME_MILLIS = 3600*1000;
private long lastUpdate = 0;
public ResourceSigningPolicyStore(SigningPolicyStoreParameters param) throws InvalidAlgorithmParameterException {
if (param == null) {
throw new IllegalArgumentException();
}
if (!(param instanceof ResourceSigningPolicyStoreParameters)) {
throw new InvalidAlgorithmParameterException();
}
this.parameters = (ResourceSigningPolicyStoreParameters) param;
}
public synchronized SigningPolicy getSigningPolicy(X500Principal caPrincipal) throws SigningPolicyStoreException {
if (caPrincipal == null) {
return null;
}
String name = caPrincipal.getName();
long now = System.currentTimeMillis();
String hash = CertificateIOUtil.nameHash(caPrincipal);
Long validCacheTime = validPoliciesCache.get(hash);
Long invalidCacheTime = invalidPoliciesCache.get(hash);
if ((invalidCacheTime != null) && (invalidCacheTime - now < 10*CACHE_TIME_MILLIS)) {
return null;
}
if ((validCacheTime == null) || (validCacheTime-now > CACHE_TIME_MILLIS) || !this.policyMap.containsKey(name)) {
loadPolicy(hash);
}
return this.policyMap.get(name);
}
private synchronized void loadPolicy(String hash) throws SigningPolicyStoreException {
String locations = this.parameters.getTrustRootLocations();
Resource[] resources;
long curTime = System.currentTimeMillis();
try {
resources = resolver.getResources(locations);
} catch (IOException e) {
throw new SigningPolicyStoreException(e);
}
long now = System.currentTimeMillis();
for (Resource resource : resources) {
String filename = resource.getFilename();
if (!filename.startsWith(hash)) {
continue;
}
if (!resource.isReadable()) {
logger.debug("Cannot read: " + resource.getFilename());
continue;
}
try {
loadSigningPolicy(resource, policyMap, signingPolicyFileMap);
} catch (Exception e) {
if (!invalidPoliciesCache.containsKey(filename)) {
logger.warn("Failed to load signing policy: " + filename);
logger.debug("Failed to load signing policy: " + filename, e);
invalidPoliciesCache.put(filename, now);
}
}
validPoliciesCache.put(hash, now);
}
}
private void loadSigningPolicy(
Resource policyResource, Map<String, SigningPolicy> policyMapToLoad,
Map<URI, ResourceSigningPolicy> currentPolicyFileMap) throws SigningPolicyStoreException {
URI uri;
if (!policyResource.isReadable()) {
throw new SigningPolicyStoreException("Cannot read file");
}
try {
uri = policyResource.getURI();
} catch (IOException e) {
throw new SigningPolicyStoreException(e);
}
ResourceSigningPolicy filePolicy = this.signingPolicyFileMap.get(uri);
if (filePolicy == null) {
try {
filePolicy = new ResourceSigningPolicy(policyResource);
} catch (ResourceStoreException e) {
throw new SigningPolicyStoreException(e);
}
}
Collection<SigningPolicy> policies = filePolicy.getSigningPolicies();
currentPolicyFileMap.put(uri, filePolicy);
if (policies != null) {
for (SigningPolicy policy : policies) {
policyMapToLoad.put(policy.getCASubjectDN().getName(), policy);
}
}
}
}
| Partial revert of dfdacf299a740d35c987f788bdd2399c8a837e07; load all policies in one shot, as they are all requested by the higher level regardless.
| ssl-proxies/src/main/java/org/globus/gsi/stores/ResourceSigningPolicyStore.java | Partial revert of dfdacf299a740d35c987f788bdd2399c8a837e07; load all policies in one shot, as they are all requested by the higher level regardless. |
|
Java | apache-2.0 | dc97edcccd72ca6aa984ab5ed37358eef6311e9e | 0 | cn-cerc/summer-mis,cn-cerc/summer-mis | package cn.cerc.mis.queue;
import cn.cerc.core.DataSet;
import cn.cerc.core.Record;
import cn.cerc.core.TDateTime;
import cn.cerc.mis.client.AutoService;
import cn.cerc.mis.core.LocalService;
import cn.cerc.mis.message.MessageProcess;
import cn.cerc.mis.rds.StubHandle;
import cn.cerc.mis.task.AbstractTask;
import lombok.extern.slf4j.Slf4j;
/**
* 处理后台异步任务
*
* @author ZhangGong
*/
@Slf4j
public class ProcessService extends AbstractTask {
// 手动执行所有的预约服务
public static void main(String[] args) {
StubHandle handle = new StubHandle();
ProcessService ps = new ProcessService();
ps.setHandle(handle);
ps.run();
}
@Override
public void execute() {
LocalService svr = new LocalService(this, "SvrUserMessages.getWaitList");
if (!svr.exec()) {
throw new RuntimeException(svr.getMessage());
}
DataSet ds = svr.getDataOut();
while (ds.fetch()) {
log.info("开始处理异步任务,UID=" + ds.getString("UID_"));
processService(ds.getString("UID_"));
}
}
/**
* 处理一个服务
*/
private void processService(String msgId) {
// 此任务可能被其它主机抢占
LocalService svrMsg = new LocalService(this, "SvrUserMessages.readAsyncService");
if (!svrMsg.exec("msgId", msgId)) {
return;
}
Record ds = svrMsg.getDataOut().getHead();
String corpNo = ds.getString("corpNo");
String userCode = ds.getString("userCode");
String content = ds.getString("content");
String subject = ds.getString("subject");
// 读取并标识为工作中,以防被其它用户抢占
AsyncService svrSync = new AsyncService(null);
svrSync.read(content);
svrSync.setProcess(MessageProcess.working.ordinal());
updateMessage(svrSync, msgId, subject);
try {
AutoService svrAuto = new AutoService(corpNo, userCode, svrSync.getService());
svrAuto.getDataIn().appendDataSet(svrSync.getDataIn(), true);
if (svrAuto.exec()) {
svrSync.getDataOut().appendDataSet(svrAuto.getDataOut(), true);
svrSync.setProcess(MessageProcess.ok.ordinal());
} else {
svrSync.getDataOut().appendDataSet(svrAuto.getDataOut(), true);
svrSync.setProcess(MessageProcess.error.ordinal());
}
svrSync.getDataOut().getHead().setField("_message_", svrAuto.getMessage());
updateMessage(svrSync, msgId, subject);
} catch (Throwable e) {
e.printStackTrace();
svrSync.setProcess(MessageProcess.error.ordinal());
svrSync.getDataOut().getHead().setField("_message_", e.getMessage());
updateMessage(svrSync, msgId, subject);
}
}
/**
* 保存到数据库
*/
private void updateMessage(AsyncService task, String msgId, String subject) {
task.setProcessTime(TDateTime.Now().toString());
LocalService svr = new LocalService(this, "SvrUserMessages.updateAsyncService");
if (!svr.exec("msgId", msgId, "content", task.toString(), "process", task.getProcess())) {
throw new RuntimeException("更新任务队列进度异常:" + svr.getMessage());
}
log.debug(task.getService() + ":" + subject + ":" + AsyncService.getProcessTitle(task.getProcess()));
}
}
| summer-mis/src/main/java/cn/cerc/mis/queue/ProcessService.java | package cn.cerc.mis.queue;
import cn.cerc.core.DataSet;
import cn.cerc.core.Record;
import cn.cerc.core.TDateTime;
import cn.cerc.mis.client.AutoService;
import cn.cerc.mis.core.LocalService;
import cn.cerc.mis.message.MessageProcess;
import cn.cerc.mis.rds.StubHandle;
import cn.cerc.mis.task.AbstractTask;
import lombok.extern.slf4j.Slf4j;
/**
* 处理后台异步任务
*
* @author ZhangGong
*/
@Slf4j
public class ProcessService extends AbstractTask {
// 手动执行所有的预约服务
public static void main(String[] args) {
StubHandle handle = new StubHandle();
ProcessService ps = new ProcessService();
ps.setHandle(handle);
ps.run();
}
@Override
public void execute() {
LocalService svr = new LocalService(this, "SvrUserMessages.getWaitList");
if (!svr.exec()) {
throw new RuntimeException(svr.getMessage());
}
DataSet ds = svr.getDataOut();
while (ds.fetch()) {
log.info("开始处理异步任务,UID=" + ds.getString("UID_"));
processService(ds.getString("UID_"));
}
}
/**
* 处理一个服务
*/
private void processService(String msgId) {
LocalService svrMsg = new LocalService(this, "SvrUserMessages.readAsyncService");
if (!svrMsg.exec("msgId", msgId)) // 此任务可能被其它主机抢占
{
return;
}
Record ds = svrMsg.getDataOut().getHead();
String corpNo = ds.getString("corpNo");
String userCode = ds.getString("userCode");
String content = ds.getString("content");
String subject = ds.getString("subject");
// 读取并标识为工作中,以防被其它用户抢占
AsyncService svrSync = new AsyncService(null);
svrSync.read(content);
svrSync.setProcess(MessageProcess.working.ordinal());
updateMessage(svrSync, msgId, subject);
try {
AutoService svrAuto = new AutoService(corpNo, userCode, svrSync.getService());
svrAuto.getDataIn().appendDataSet(svrSync.getDataIn(), true);
if (svrAuto.exec()) {
svrSync.getDataOut().appendDataSet(svrAuto.getDataOut(), true);
svrSync.setProcess(MessageProcess.ok.ordinal());
} else {
svrSync.getDataOut().appendDataSet(svrAuto.getDataOut(), true);
svrSync.setProcess(MessageProcess.error.ordinal());
}
svrSync.getDataOut().getHead().setField("_message_", svrAuto.getMessage());
updateMessage(svrSync, msgId, subject);
} catch (Throwable e) {
e.printStackTrace();
svrSync.setProcess(MessageProcess.error.ordinal());
svrSync.getDataOut().getHead().setField("_message_", e.getMessage());
updateMessage(svrSync, msgId, subject);
}
}
/**
* 保存到数据库
*/
private void updateMessage(AsyncService task, String msgId, String subject) {
task.setProcessTime(TDateTime.Now().toString());
LocalService svr = new LocalService(this, "SvrUserMessages.updateAsyncService");
if (!svr.exec("msgId", msgId, "content", task.toString(), "process", task.getProcess())) {
throw new RuntimeException("更新任务队列进度异常:" + svr.getMessage());
}
log.debug(task.getService() + ":" + subject + ":" + AsyncService.getProcessTitle(task.getProcess()));
}
}
| Update ProcessService.java
| summer-mis/src/main/java/cn/cerc/mis/queue/ProcessService.java | Update ProcessService.java |
|
Java | apache-2.0 | f28fa2078e46c7027e2a9e8abedf3a66b15b6884 | 0 | brianchen2012/syncope,brianchen2012/syncope,brianchen2012/syncope | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.syncope.core.persistence.beans;
import static javax.persistence.EnumType.STRING;
import java.lang.reflect.Constructor;
import java.text.DecimalFormat;
import java.text.Format;
import java.text.SimpleDateFormat;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Enumerated;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.MappedSuperclass;
import javax.persistence.Transient;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import org.apache.syncope.core.persistence.validation.attrvalue.BasicValidator;
import org.apache.syncope.core.persistence.validation.attrvalue.AbstractValidator;
import org.apache.syncope.core.persistence.validation.entity.SchemaCheck;
import org.apache.syncope.types.SchemaType;
@MappedSuperclass
@SchemaCheck
public abstract class AbstractSchema extends AbstractBaseBean {
public static String enumValuesSeparator = ";";
private static final long serialVersionUID = -8621028596062054739L;
@Id
private String name;
@Column(nullable = false)
@Enumerated(STRING)
private SchemaType type;
@Column(nullable = false)
private String mandatoryCondition;
@Basic
@Min(0)
@Max(1)
private Integer multivalue;
@Basic
@Min(0)
@Max(1)
private Integer uniqueConstraint;
@Basic
@Min(0)
@Max(1)
private Integer readonly;
@Column(nullable = true)
private String conversionPattern;
@Column(nullable = true)
private String validatorClass;
@Column(nullable = true)
@Lob
private String enumerationValues;
@Column(nullable = true)
@Lob
private String enumerationKeys;
@Transient
private AbstractValidator validator;
public AbstractSchema() {
super();
type = SchemaType.String;
mandatoryCondition = Boolean.FALSE.toString();
multivalue = getBooleanAsInteger(false);
uniqueConstraint = getBooleanAsInteger(false);
readonly = getBooleanAsInteger(false);
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public SchemaType getType() {
return type;
}
public void setType(SchemaType type) {
this.type = type;
}
public String getMandatoryCondition() {
return mandatoryCondition;
}
public void setMandatoryCondition(final String mandatoryCondition) {
this.mandatoryCondition = mandatoryCondition;
}
public boolean isMultivalue() {
return isBooleanAsInteger(multivalue);
}
public void setMultivalue(boolean multivalue) {
this.multivalue = getBooleanAsInteger(multivalue);
}
public boolean isUniqueConstraint() {
return isBooleanAsInteger(uniqueConstraint);
}
public void setUniqueConstraint(final boolean uniquevalue) {
this.uniqueConstraint = getBooleanAsInteger(uniquevalue);
}
public boolean isReadonly() {
return isBooleanAsInteger(readonly);
}
public void setReadonly(final boolean readonly) {
this.readonly = getBooleanAsInteger(readonly);
}
public AbstractValidator getValidator() {
if (validator != null) {
return validator;
}
if (getValidatorClass() != null && getValidatorClass().length() > 0) {
try {
Constructor validatorConstructor = Class.forName(getValidatorClass()).getConstructor(
new Class[]{getClass().getSuperclass()});
validator = (AbstractValidator) validatorConstructor.newInstance(this);
} catch (Exception e) {
LOG.error("Could not instantiate validator of type " + getValidatorClass()
+ ", reverting to AttributeBasicValidator", e);
}
}
if (validator == null) {
validator = new BasicValidator(this);
}
return validator;
}
public String getValidatorClass() {
return validatorClass;
}
public void setValidatorClass(final String validatorClass) {
this.validatorClass = validatorClass;
}
public String getEnumerationValues() {
return enumerationValues;
}
public void setEnumerationValues(final String enumerationValues) {
this.enumerationValues = enumerationValues;
}
public String getEnumerationKeys() {
return enumerationKeys;
}
public void setEnumerationKeys(String enumerationKeys) {
this.enumerationKeys = enumerationKeys;
}
public String getConversionPattern() {
if (!getType().isConversionPatternNeeded()) {
LOG.debug("Conversion pattern is not needed: {}'s type is {}", this, getType());
}
return conversionPattern;
}
public void setConversionPattern(final String conversionPattern) {
if (!getType().isConversionPatternNeeded()) {
LOG.warn("Conversion pattern will be ignored: " + "this attribute type is " + getType());
}
this.conversionPattern = conversionPattern;
}
public <T extends Format> T getFormatter() {
T result = null;
if (getConversionPattern() != null) {
switch (getType()) {
case Long:
DecimalFormat longFormatter = DECIMAL_FORMAT.get();
longFormatter.applyPattern(getConversionPattern());
result = (T) longFormatter;
break;
case Double:
DecimalFormat doubleFormatter = DECIMAL_FORMAT.get();
doubleFormatter.applyPattern(getConversionPattern());
result = (T) doubleFormatter;
break;
case Date:
SimpleDateFormat dateFormatter = DATE_FORMAT.get();
dateFormatter.applyPattern(getConversionPattern());
dateFormatter.setLenient(false);
result = (T) dateFormatter;
break;
default:
}
}
return result;
}
}
| core/src/main/java/org/apache/syncope/core/persistence/beans/AbstractSchema.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.syncope.core.persistence.beans;
import static javax.persistence.EnumType.STRING;
import java.lang.reflect.Constructor;
import java.text.DecimalFormat;
import java.text.Format;
import java.text.SimpleDateFormat;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Enumerated;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Transient;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import org.apache.syncope.core.persistence.validation.attrvalue.BasicValidator;
import org.apache.syncope.core.persistence.validation.attrvalue.AbstractValidator;
import org.apache.syncope.core.persistence.validation.entity.SchemaCheck;
import org.apache.syncope.types.SchemaType;
@MappedSuperclass
@SchemaCheck
public abstract class AbstractSchema extends AbstractBaseBean {
public static String enumValuesSeparator = ";";
private static final long serialVersionUID = -8621028596062054739L;
@Id
private String name;
@Column(nullable = false)
@Enumerated(STRING)
private SchemaType type;
@Column(nullable = false)
private String mandatoryCondition;
@Basic
@Min(0)
@Max(1)
private Integer multivalue;
@Basic
@Min(0)
@Max(1)
private Integer uniqueConstraint;
@Basic
@Min(0)
@Max(1)
private Integer readonly;
@Column(nullable = true)
private String conversionPattern;
@Column(nullable = true)
private String validatorClass;
@Column(nullable = true)
private String enumerationValues;
@Column(nullable = true)
private String enumerationKeys;
@Transient
private AbstractValidator validator;
public AbstractSchema() {
super();
type = SchemaType.String;
mandatoryCondition = Boolean.FALSE.toString();
multivalue = getBooleanAsInteger(false);
uniqueConstraint = getBooleanAsInteger(false);
readonly = getBooleanAsInteger(false);
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public SchemaType getType() {
return type;
}
public void setType(SchemaType type) {
this.type = type;
}
public String getMandatoryCondition() {
return mandatoryCondition;
}
public void setMandatoryCondition(final String mandatoryCondition) {
this.mandatoryCondition = mandatoryCondition;
}
public boolean isMultivalue() {
return isBooleanAsInteger(multivalue);
}
public void setMultivalue(boolean multivalue) {
this.multivalue = getBooleanAsInteger(multivalue);
}
public boolean isUniqueConstraint() {
return isBooleanAsInteger(uniqueConstraint);
}
public void setUniqueConstraint(final boolean uniquevalue) {
this.uniqueConstraint = getBooleanAsInteger(uniquevalue);
}
public boolean isReadonly() {
return isBooleanAsInteger(readonly);
}
public void setReadonly(final boolean readonly) {
this.readonly = getBooleanAsInteger(readonly);
}
public AbstractValidator getValidator() {
if (validator != null) {
return validator;
}
if (getValidatorClass() != null && getValidatorClass().length() > 0) {
try {
Constructor validatorConstructor = Class.forName(getValidatorClass()).getConstructor(
new Class[]{getClass().getSuperclass()});
validator = (AbstractValidator) validatorConstructor.newInstance(this);
} catch (Exception e) {
LOG.error("Could not instantiate validator of type " + getValidatorClass()
+ ", reverting to AttributeBasicValidator", e);
}
}
if (validator == null) {
validator = new BasicValidator(this);
}
return validator;
}
public String getValidatorClass() {
return validatorClass;
}
public void setValidatorClass(final String validatorClass) {
this.validatorClass = validatorClass;
}
public String getEnumerationValues() {
return enumerationValues;
}
public void setEnumerationValues(final String enumerationValues) {
this.enumerationValues = enumerationValues;
}
public String getEnumerationKeys() {
return enumerationKeys;
}
public void setEnumerationKeys(String enumerationKeys) {
this.enumerationKeys = enumerationKeys;
}
public String getConversionPattern() {
if (!getType().isConversionPatternNeeded()) {
LOG.debug("Conversion pattern is not needed: {}'s type is {}", this, getType());
}
return conversionPattern;
}
public void setConversionPattern(final String conversionPattern) {
if (!getType().isConversionPatternNeeded()) {
LOG.warn("Conversion pattern will be ignored: " + "this attribute type is " + getType());
}
this.conversionPattern = conversionPattern;
}
public <T extends Format> T getFormatter() {
T result = null;
if (getConversionPattern() != null) {
switch (getType()) {
case Long:
DecimalFormat longFormatter = DECIMAL_FORMAT.get();
longFormatter.applyPattern(getConversionPattern());
result = (T) longFormatter;
break;
case Double:
DecimalFormat doubleFormatter = DECIMAL_FORMAT.get();
doubleFormatter.applyPattern(getConversionPattern());
result = (T) doubleFormatter;
break;
case Date:
SimpleDateFormat dateFormatter = DATE_FORMAT.get();
dateFormatter.applyPattern(getConversionPattern());
dateFormatter.setLenient(false);
result = (T) dateFormatter;
break;
default:
}
}
return result;
}
}
| Fixes SYNCOPE-201
git-svn-id: 51e9c0635e05060c2a7639df764e0b3ebb09013f@1381133 13f79535-47bb-0310-9956-ffa450edef68
| core/src/main/java/org/apache/syncope/core/persistence/beans/AbstractSchema.java | Fixes SYNCOPE-201 |
|
Java | apache-2.0 | e916006e27f73e8469a3f20d5f7dfe7c9dbad372 | 0 | apache/olingo-odata4,apache/olingo-odata4 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.olingo.server.core;
import java.util.Locale;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.ODataLibraryException;
import org.apache.olingo.server.api.ODataLibraryException.ODataErrorMessage;
import org.apache.olingo.server.api.ODataServerError;
import org.apache.olingo.server.api.deserializer.DeserializerException;
import org.apache.olingo.server.api.etag.PreconditionException;
import org.apache.olingo.server.api.serializer.SerializerException;
import org.apache.olingo.server.core.uri.parser.UriParserException;
import org.apache.olingo.server.core.uri.parser.UriParserSemanticException;
import org.apache.olingo.server.core.uri.parser.UriParserSyntaxException;
import org.apache.olingo.server.core.uri.validator.UriValidationException;
public class ODataExceptionHelper {
private ODataExceptionHelper() {
// Private Constructor
}
public static ODataServerError createServerErrorObject(final UriValidationException e,
final Locale requestedLocale) {
ODataServerError serverError = basicTranslatedError(e, requestedLocale);
serverError.setStatusCode(HttpStatusCode.BAD_REQUEST.getStatusCode());
return serverError;
}
public static ODataServerError createServerErrorObject(final UriParserSemanticException e,
final Locale requestedLocale) {
ODataServerError serverError = basicTranslatedError(e, requestedLocale);
if (UriParserSemanticException.MessageKeys.RESOURCE_NOT_FOUND.equals(e.getMessageKey())
|| UriParserSemanticException.MessageKeys.PROPERTY_NOT_IN_TYPE.equals(e.getMessageKey())) {
serverError.setStatusCode(HttpStatusCode.NOT_FOUND.getStatusCode());
} else if (UriParserSemanticException.MessageKeys.NOT_IMPLEMENTED.equals(e.getMessageKey())) {
serverError.setStatusCode(HttpStatusCode.NOT_IMPLEMENTED.getStatusCode());
} else {
serverError.setStatusCode(HttpStatusCode.BAD_REQUEST.getStatusCode());
}
return serverError;
}
public static ODataServerError createServerErrorObject(final UriParserSyntaxException e,
final Locale requestedLocale) {
ODataServerError serverError = basicTranslatedError(e, requestedLocale);
serverError.setStatusCode(
UriParserSyntaxException.MessageKeys.WRONG_VALUE_FOR_SYSTEM_QUERY_OPTION_FORMAT.equals(e.getMessageKey()) ?
HttpStatusCode.NOT_ACCEPTABLE.getStatusCode() :
HttpStatusCode.BAD_REQUEST.getStatusCode());
return serverError;
}
public static ODataServerError createServerErrorObject(final UriParserException e, final Locale requestedLocale) {
ODataServerError serverError = basicTranslatedError(e, requestedLocale);
serverError.setStatusCode(HttpStatusCode.BAD_REQUEST.getStatusCode());
return serverError;
}
public static ODataServerError createServerErrorObject(final ContentNegotiatorException e,
final Locale requestedLocale) {
ODataServerError serverError = basicTranslatedError(e, requestedLocale);
serverError.setStatusCode(HttpStatusCode.NOT_ACCEPTABLE.getStatusCode());
return serverError;
}
public static ODataServerError createServerErrorObject(final ODataHandlerException e, final Locale requestedLocale) {
ODataServerError serverError = basicTranslatedError(e, requestedLocale);
if (ODataHandlerException.MessageKeys.FUNCTIONALITY_NOT_IMPLEMENTED.equals(e.getMessageKey())
|| ODataHandlerException.MessageKeys.PROCESSOR_NOT_IMPLEMENTED.equals(e.getMessageKey())) {
serverError.setStatusCode(HttpStatusCode.NOT_IMPLEMENTED.getStatusCode());
} else if (ODataHandlerException.MessageKeys.ODATA_VERSION_NOT_SUPPORTED.equals(e.getMessageKey())
|| ODataHandlerException.MessageKeys.INVALID_HTTP_METHOD.equals(e.getMessageKey())
|| ODataHandlerException.MessageKeys.AMBIGUOUS_XHTTP_METHOD.equals(e.getMessageKey())
|| ODataHandlerException.MessageKeys.MISSING_CONTENT_TYPE.equals(e.getMessageKey())
|| ODataHandlerException.MessageKeys.INVALID_CONTENT_TYPE.equals(e.getMessageKey())) {
serverError.setStatusCode(HttpStatusCode.BAD_REQUEST.getStatusCode());
} else if (ODataHandlerException.MessageKeys.HTTP_METHOD_NOT_ALLOWED.equals(e.getMessageKey())) {
serverError.setStatusCode(HttpStatusCode.METHOD_NOT_ALLOWED.getStatusCode());
}
return serverError;
}
public static ODataServerError createServerErrorObject(final SerializerException e, final Locale requestedLocale) {
ODataServerError serverError = basicTranslatedError(e, requestedLocale);
serverError.setStatusCode(HttpStatusCode.BAD_REQUEST.getStatusCode());
return serverError;
}
public static ODataServerError createServerErrorObject(final DeserializerException e, final Locale requestedLocale) {
return basicTranslatedError(e, requestedLocale)
.setStatusCode(HttpStatusCode.BAD_REQUEST.getStatusCode());
}
public static ODataServerError createServerErrorObject(final PreconditionException e,
final Locale requestedLocale) {
ODataServerError serverError = basicTranslatedError(e, requestedLocale);
if (PreconditionException.MessageKeys.MISSING_HEADER == e.getMessageKey()) {
serverError.setStatusCode(HttpStatusCode.PRECONDITION_REQUIRED.getStatusCode());
} else if (PreconditionException.MessageKeys.FAILED == e.getMessageKey()) {
serverError.setStatusCode(HttpStatusCode.PRECONDITION_FAILED.getStatusCode());
}
return serverError;
}
public static ODataServerError createServerErrorObject(final ODataLibraryException e, final Locale requestedLocale) {
return basicTranslatedError(e, requestedLocale);
}
public static ODataServerError createServerErrorObject(final ODataApplicationException e) {
ODataServerError serverError = basicServerError(e);
serverError.setStatusCode(e.getStatusCode());
serverError.setLocale(e.getLocale());
serverError.setCode(e.getODataErrorCode());
serverError.setMessage(e.getLocalizedMessage());
return serverError;
}
public static ODataServerError createServerErrorObject(final Exception e) {
ODataServerError serverError = basicServerError(e);
serverError.setStatusCode(HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode());
serverError.setLocale(Locale.ENGLISH);
return serverError;
}
private static ODataServerError basicServerError(final Exception e) {
ODataServerError serverError = new ODataServerError().setException(e).setMessage(e.getMessage());
if (serverError.getMessage() == null) {
serverError.setMessage("OData Library: An exception without message text was thrown.");
}
return serverError;
}
private static ODataServerError basicTranslatedError(final ODataLibraryException e,
final Locale requestedLocale) {
ODataServerError serverError = basicServerError(e);
ODataErrorMessage translatedMessage = e.getTranslatedMessage(requestedLocale);
serverError.setMessage(translatedMessage.getMessage());
serverError.setLocale(translatedMessage.getLocale());
serverError.setStatusCode(HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode());
return serverError;
}
}
| lib/server-core/src/main/java/org/apache/olingo/server/core/ODataExceptionHelper.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.olingo.server.core;
import java.util.Locale;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.ODataLibraryException;
import org.apache.olingo.server.api.ODataLibraryException.ODataErrorMessage;
import org.apache.olingo.server.api.ODataServerError;
import org.apache.olingo.server.api.deserializer.DeserializerException;
import org.apache.olingo.server.api.etag.PreconditionException;
import org.apache.olingo.server.api.serializer.SerializerException;
import org.apache.olingo.server.core.uri.parser.UriParserException;
import org.apache.olingo.server.core.uri.parser.UriParserSemanticException;
import org.apache.olingo.server.core.uri.parser.UriParserSyntaxException;
import org.apache.olingo.server.core.uri.validator.UriValidationException;
public class ODataExceptionHelper {
private ODataExceptionHelper() {
// Private Constructor
}
public static ODataServerError createServerErrorObject(final UriValidationException e,
final Locale requestedLocale) {
ODataServerError serverError = basicTranslatedError(e, requestedLocale);
serverError.setStatusCode(HttpStatusCode.BAD_REQUEST.getStatusCode());
return serverError;
}
public static ODataServerError createServerErrorObject(final UriParserSemanticException e,
final Locale requestedLocale) {
ODataServerError serverError = basicTranslatedError(e, requestedLocale);
if (UriParserSemanticException.MessageKeys.RESOURCE_NOT_FOUND.equals(e.getMessageKey())
|| UriParserSemanticException.MessageKeys.PROPERTY_NOT_IN_TYPE.equals(e.getMessageKey())) {
serverError.setStatusCode(HttpStatusCode.NOT_FOUND.getStatusCode());
} else if (UriParserSemanticException.MessageKeys.NOT_IMPLEMENTED.equals(e.getMessageKey())) {
serverError.setStatusCode(HttpStatusCode.NOT_IMPLEMENTED.getStatusCode());
} else {
serverError.setStatusCode(HttpStatusCode.BAD_REQUEST.getStatusCode());
}
return serverError;
}
public static ODataServerError createServerErrorObject(final UriParserSyntaxException e,
final Locale requestedLocale) {
ODataServerError serverError = basicTranslatedError(e, requestedLocale);
serverError.setStatusCode(
UriParserSyntaxException.MessageKeys.WRONG_VALUE_FOR_SYSTEM_QUERY_OPTION_FORMAT.equals(e.getMessageKey()) ?
HttpStatusCode.NOT_ACCEPTABLE.getStatusCode() :
HttpStatusCode.BAD_REQUEST.getStatusCode());
return serverError;
}
public static ODataServerError createServerErrorObject(final UriParserException e, final Locale requestedLocale) {
ODataServerError serverError = basicTranslatedError(e, requestedLocale);
serverError.setStatusCode(HttpStatusCode.BAD_REQUEST.getStatusCode());
return serverError;
}
public static ODataServerError createServerErrorObject(final ContentNegotiatorException e,
final Locale requestedLocale) {
ODataServerError serverError = basicTranslatedError(e, requestedLocale);
serverError.setStatusCode(HttpStatusCode.NOT_ACCEPTABLE.getStatusCode());
return serverError;
}
public static ODataServerError createServerErrorObject(final ODataHandlerException e, final Locale requestedLocale) {
ODataServerError serverError = basicTranslatedError(e, requestedLocale);
if (ODataHandlerException.MessageKeys.FUNCTIONALITY_NOT_IMPLEMENTED.equals(e.getMessageKey())
|| ODataHandlerException.MessageKeys.PROCESSOR_NOT_IMPLEMENTED.equals(e.getMessageKey())) {
serverError.setStatusCode(HttpStatusCode.NOT_IMPLEMENTED.getStatusCode());
} else if (ODataHandlerException.MessageKeys.ODATA_VERSION_NOT_SUPPORTED.equals(e.getMessageKey())
|| ODataHandlerException.MessageKeys.INVALID_HTTP_METHOD.equals(e.getMessageKey())
|| ODataHandlerException.MessageKeys.AMBIGUOUS_XHTTP_METHOD.equals(e.getMessageKey())
|| ODataHandlerException.MessageKeys.MISSING_CONTENT_TYPE.equals(e.getMessageKey())
|| ODataHandlerException.MessageKeys.INVALID_CONTENT_TYPE.equals(e.getMessageKey())) {
serverError.setStatusCode(HttpStatusCode.BAD_REQUEST.getStatusCode());
} else if (ODataHandlerException.MessageKeys.HTTP_METHOD_NOT_ALLOWED.equals(e.getMessageKey())) {
serverError.setStatusCode(HttpStatusCode.METHOD_NOT_ALLOWED.getStatusCode());
}
return serverError;
}
public static ODataServerError createServerErrorObject(final SerializerException e, final Locale requestedLocale) {
ODataServerError serverError = basicTranslatedError(e, requestedLocale);
serverError.setStatusCode(HttpStatusCode.BAD_REQUEST.getStatusCode());
return serverError;
}
public static ODataServerError createServerErrorObject(final DeserializerException e, final Locale requestedLocale) {
return basicTranslatedError(e, requestedLocale)
.setStatusCode(HttpStatusCode.BAD_REQUEST.getStatusCode());
}
public static ODataServerError createServerErrorObject(final PreconditionException e,
final Locale requestedLocale) {
ODataServerError serverError = basicTranslatedError(e, requestedLocale);
if (PreconditionException.MessageKeys.MISSING_HEADER == e.getMessageKey()) {
serverError.setStatusCode(HttpStatusCode.PRECONDITION_REQUIRED.getStatusCode());
} else if (PreconditionException.MessageKeys.FAILED == e.getMessageKey()) {
serverError.setStatusCode(HttpStatusCode.PRECONDITION_FAILED.getStatusCode());
}
return serverError;
}
public static ODataServerError createServerErrorObject(final ODataLibraryException e, final Locale requestedLocale) {
return basicTranslatedError(e, requestedLocale);
}
public static ODataServerError createServerErrorObject(final ODataApplicationException e) {
ODataServerError serverError = basicServerError(e);
serverError.setStatusCode(e.getStatusCode());
serverError.setLocale(e.getLocale());
serverError.setCode(e.getODataErrorCode());
return serverError;
}
public static ODataServerError createServerErrorObject(final Exception e) {
ODataServerError serverError = basicServerError(e);
serverError.setStatusCode(HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode());
serverError.setLocale(Locale.ENGLISH);
return serverError;
}
private static ODataServerError basicServerError(final Exception e) {
ODataServerError serverError = new ODataServerError().setException(e).setMessage(e.getLocalizedMessage());
if (serverError.getMessage() == null) {
serverError.setMessage("OData Library: An exception without message text was thrown.");
}
return serverError;
}
private static ODataServerError basicTranslatedError(final ODataLibraryException e,
final Locale requestedLocale) {
ODataServerError serverError = basicServerError(e);
ODataErrorMessage translatedMessage = e.getTranslatedMessage(requestedLocale);
serverError.setMessage(translatedMessage.getMessage());
serverError.setLocale(translatedMessage.getLocale());
serverError.setStatusCode(HttpStatusCode.INTERNAL_SERVER_ERROR.getStatusCode());
return serverError;
}
}
| [OLINGO-979] corrected localized error message
Signed-off-by: Christian Amend <[email protected]>
| lib/server-core/src/main/java/org/apache/olingo/server/core/ODataExceptionHelper.java | [OLINGO-979] corrected localized error message |
|
Java | apache-2.0 | 03ae3bcefa531ded62a51f6753d797ac8484c2b6 | 0 | skylot/jadx,NeoSpb/jadx,jpstotz/jadx | package jadx.core.dex.visitors;
import java.util.Set;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.info.ClassInfo;
import jadx.core.dex.info.FieldInfo;
import jadx.core.dex.instructions.IndexInsnNode;
import jadx.core.dex.instructions.InvokeNode;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.InsnWrapArg;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.instructions.mods.ConstructorInsn;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.DexNode;
import jadx.core.dex.nodes.FieldNode;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.dex.nodes.parser.FieldInitAttr;
import jadx.core.utils.exceptions.JadxException;
public class DependencyCollector extends AbstractVisitor {
@Override
public boolean visit(ClassNode cls) throws JadxException {
DexNode dex = cls.dex();
Set<ClassNode> depList = cls.getDependencies();
processClass(cls, dex, depList);
for (ClassNode inner : cls.getInnerClasses()) {
processClass(inner, dex, depList);
}
depList.remove(cls);
return false;
}
private static void processClass(ClassNode cls, DexNode dex, Set<ClassNode> depList) {
addDep(dex, depList, cls.getSuperClass());
for (ArgType iType : cls.getInterfaces()) {
addDep(dex, depList, iType);
}
for (FieldNode fieldNode : cls.getFields()) {
addDep(dex, depList, fieldNode.getType());
// process instructions from field init
FieldInitAttr fieldInitAttr = fieldNode.get(AType.FIELD_INIT);
if (fieldInitAttr != null && fieldInitAttr.getValueType() == FieldInitAttr.InitType.INSN) {
processInsn(dex, depList, fieldInitAttr.getInsn());
}
}
// TODO: process annotations and generics
for (MethodNode methodNode : cls.getMethods()) {
if (methodNode.isNoCode() || methodNode.contains(AType.JADX_ERROR)) {
continue;
}
processMethod(dex, depList, methodNode);
}
}
private static void processMethod(DexNode dex, Set<ClassNode> depList, MethodNode methodNode) {
addDep(dex, depList, methodNode.getParentClass());
addDep(dex, depList, methodNode.getReturnType());
for (ArgType arg : methodNode.getMethodInfo().getArgumentsTypes()) {
addDep(dex, depList, arg);
}
for (BlockNode block : methodNode.getBasicBlocks()) {
for (InsnNode insnNode : block.getInstructions()) {
processInsn(dex, depList, insnNode);
}
}
}
// TODO: add custom instructions processing
private static void processInsn(DexNode dex, Set<ClassNode> depList, InsnNode insnNode) {
RegisterArg result = insnNode.getResult();
if (result != null) {
addDep(dex, depList, result.getType());
}
for (InsnArg arg : insnNode.getArguments()) {
if (arg.isInsnWrap()) {
processInsn(dex, depList, ((InsnWrapArg) arg).getWrapInsn());
} else {
addDep(dex, depList, arg.getType());
}
}
processCustomInsn(dex, depList, insnNode);
}
private static void processCustomInsn(DexNode dex, Set<ClassNode> depList, InsnNode insn) {
if (insn instanceof IndexInsnNode) {
Object index = ((IndexInsnNode) insn).getIndex();
if (index instanceof FieldInfo) {
addDep(dex, depList, ((FieldInfo) index).getDeclClass());
} else if (index instanceof ArgType) {
addDep(dex, depList, (ArgType) index);
}
} else if (insn instanceof InvokeNode) {
ClassInfo declClass = ((InvokeNode) insn).getCallMth().getDeclClass();
addDep(dex, depList, declClass);
} else if (insn instanceof ConstructorInsn) {
ClassInfo declClass = ((ConstructorInsn) insn).getCallMth().getDeclClass();
addDep(dex, depList, declClass);
}
}
private static void addDep(DexNode dex, Set<ClassNode> depList, ArgType type) {
if (type != null) {
if (type.isObject()) {
addDep(dex, depList, ClassInfo.fromName(dex.root(), type.getObject()));
ArgType[] genericTypes = type.getGenericTypes();
if (type.isGeneric() && genericTypes != null) {
for (ArgType argType : genericTypes) {
addDep(dex, depList, argType);
}
}
} else if (type.isArray()) {
addDep(dex, depList, type.getArrayRootElement());
}
}
}
private static void addDep(DexNode dex, Set<ClassNode> depList, ClassInfo clsInfo) {
if (clsInfo != null) {
ClassNode node = dex.resolveClass(clsInfo);
addDep(dex, depList, node);
}
}
private static void addDep(DexNode dex, Set<ClassNode> depList, ClassNode clsNode) {
if (clsNode != null) {
// add only top classes
depList.add(clsNode.getTopParentClass());
}
}
}
| jadx-core/src/main/java/jadx/core/dex/visitors/DependencyCollector.java | package jadx.core.dex.visitors;
import java.util.Set;
import jadx.core.dex.attributes.AType;
import jadx.core.dex.info.ClassInfo;
import jadx.core.dex.info.FieldInfo;
import jadx.core.dex.instructions.IndexInsnNode;
import jadx.core.dex.instructions.InvokeNode;
import jadx.core.dex.instructions.args.ArgType;
import jadx.core.dex.instructions.args.InsnArg;
import jadx.core.dex.instructions.args.InsnWrapArg;
import jadx.core.dex.instructions.args.RegisterArg;
import jadx.core.dex.instructions.mods.ConstructorInsn;
import jadx.core.dex.nodes.BlockNode;
import jadx.core.dex.nodes.ClassNode;
import jadx.core.dex.nodes.DexNode;
import jadx.core.dex.nodes.FieldNode;
import jadx.core.dex.nodes.InsnNode;
import jadx.core.dex.nodes.MethodNode;
import jadx.core.utils.exceptions.JadxException;
public class DependencyCollector extends AbstractVisitor {
@Override
public boolean visit(ClassNode cls) throws JadxException {
DexNode dex = cls.dex();
Set<ClassNode> depList = cls.getDependencies();
processClass(cls, dex, depList);
for (ClassNode inner : cls.getInnerClasses()) {
processClass(inner, dex, depList);
}
depList.remove(cls);
return false;
}
private static void processClass(ClassNode cls, DexNode dex, Set<ClassNode> depList) {
addDep(dex, depList, cls.getSuperClass());
for (ArgType iType : cls.getInterfaces()) {
addDep(dex, depList, iType);
}
for (FieldNode fieldNode : cls.getFields()) {
addDep(dex, depList, fieldNode.getType());
}
// TODO: process annotations and generics
for (MethodNode methodNode : cls.getMethods()) {
if (methodNode.isNoCode() || methodNode.contains(AType.JADX_ERROR)) {
continue;
}
processMethod(dex, depList, methodNode);
}
}
private static void processMethod(DexNode dex, Set<ClassNode> depList, MethodNode methodNode) {
addDep(dex, depList, methodNode.getParentClass());
addDep(dex, depList, methodNode.getReturnType());
for (ArgType arg : methodNode.getMethodInfo().getArgumentsTypes()) {
addDep(dex, depList, arg);
}
for (BlockNode block : methodNode.getBasicBlocks()) {
for (InsnNode insnNode : block.getInstructions()) {
processInsn(dex, depList, insnNode);
}
}
}
// TODO: add custom instructions processing
private static void processInsn(DexNode dex, Set<ClassNode> depList, InsnNode insnNode) {
RegisterArg result = insnNode.getResult();
if (result != null) {
addDep(dex, depList, result.getType());
}
for (InsnArg arg : insnNode.getArguments()) {
if (arg.isInsnWrap()) {
processInsn(dex, depList, ((InsnWrapArg) arg).getWrapInsn());
} else {
addDep(dex, depList, arg.getType());
}
}
processCustomInsn(dex, depList, insnNode);
}
private static void processCustomInsn(DexNode dex, Set<ClassNode> depList, InsnNode insn) {
if (insn instanceof IndexInsnNode) {
Object index = ((IndexInsnNode) insn).getIndex();
if (index instanceof FieldInfo) {
addDep(dex, depList, ((FieldInfo) index).getDeclClass());
} else if (index instanceof ArgType) {
addDep(dex, depList, (ArgType) index);
}
} else if (insn instanceof InvokeNode) {
ClassInfo declClass = ((InvokeNode) insn).getCallMth().getDeclClass();
addDep(dex, depList, declClass);
} else if (insn instanceof ConstructorInsn) {
ClassInfo declClass = ((ConstructorInsn) insn).getCallMth().getDeclClass();
addDep(dex, depList, declClass);
}
}
private static void addDep(DexNode dex, Set<ClassNode> depList, ArgType type) {
if (type != null) {
if (type.isObject()) {
addDep(dex, depList, ClassInfo.fromName(dex.root(), type.getObject()));
ArgType[] genericTypes = type.getGenericTypes();
if (type.isGeneric() && genericTypes != null) {
for (ArgType argType : genericTypes) {
addDep(dex, depList, argType);
}
}
} else if (type.isArray()) {
addDep(dex, depList, type.getArrayRootElement());
}
}
}
private static void addDep(DexNode dex, Set<ClassNode> depList, ClassInfo clsInfo) {
if (clsInfo != null) {
ClassNode node = dex.resolveClass(clsInfo);
addDep(dex, depList, node);
}
}
private static void addDep(DexNode dex, Set<ClassNode> depList, ClassNode clsNode) {
if (clsNode != null) {
// add only top classes
depList.add(clsNode.getTopParentClass());
}
}
}
| fix: process field init code in dependency collector (#467)
| jadx-core/src/main/java/jadx/core/dex/visitors/DependencyCollector.java | fix: process field init code in dependency collector (#467) |
|
Java | apache-2.0 | e3e9d68251e1a627be63750073d0f5e1f47fff81 | 0 | glowroot/glowroot,trask/glowroot,trask/glowroot,trask/glowroot,glowroot/glowroot,trask/glowroot,glowroot/glowroot,glowroot/glowroot | /*
* Copyright 2012-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.glowroot.agent.ui.sandbox;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.ning.http.client.AsyncHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ExpensiveCall {
private static final Logger logger = LoggerFactory.getLogger(ExpensiveCall.class);
private static final AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
private static final Random random = new Random();
private final int maxTimeMillis;
private final int maxTraceEntryMessageLength;
ExpensiveCall(int maxTimeMillis, int maxTraceEntryMessageLength) {
this.maxTimeMillis = maxTimeMillis;
this.maxTraceEntryMessageLength = maxTraceEntryMessageLength;
}
void execute() throws Exception {
int route = random.nextInt(11);
switch (route) {
case 0:
execute0();
return;
case 1:
execute1();
return;
case 2:
execute2();
return;
case 3:
execute3();
return;
case 4:
execute4();
return;
case 5:
execute5();
return;
case 6:
execute6();
return;
case 7:
execute7();
return;
case 8:
execute8();
return;
case 9:
execute9();
return;
default:
new AsyncWrapperCall(maxTimeMillis, maxTraceEntryMessageLength).execute();
}
}
private void execute0() throws InterruptedException {
expensive();
execute1();
}
private void execute1() throws InterruptedException {
expensive();
}
private void execute2() throws InterruptedException {
expensive();
execute3();
}
private void execute3() throws InterruptedException {
expensive();
}
private void execute4() throws InterruptedException {
expensive();
execute5();
try {
asyncHttpClient.prepareGet("http://example.org").execute().get();
} catch (ExecutionException e) {
logger.error(e.getMessage(), e);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
private void execute5() throws InterruptedException {
expensive();
}
private void execute6() throws InterruptedException {
expensive();
execute7();
}
private void execute7() throws InterruptedException {
expensive();
}
private void execute8() throws InterruptedException {
expensive();
execute9();
}
private void execute9() throws InterruptedException {
expensive();
}
public String getTraceEntryMessage() {
return getTraceEntryMessage(random.nextInt(5) > 0);
}
// this is just to prevent jvm from optimizing away for the loop below
public static final AtomicLong dummy = new AtomicLong();
// need
private static final Object lock = new Object();
static {
ThreadFactory threadFactory = new ThreadFactoryBuilder().setDaemon(true).build();
Executors.newSingleThreadExecutor(threadFactory).submit(new Callable<Void>() {
@Override
public Void call() throws InterruptedException {
// this loop is used to block threads executing expensive() below
while (true) {
synchronized (lock) {
Thread.sleep(random.nextInt(10));
}
Thread.sleep(1);
}
}
});
}
private void expensive() throws InterruptedException {
int millis = random.nextInt(maxTimeMillis) / 4;
// spend a quarter of the time taxing the cpu and doing memory allocation
long start = System.currentTimeMillis();
while (System.currentTimeMillis() - start < millis) {
for (int i = 0; i < 100000; i++) {
dummy.addAndGet(random.nextInt(1024));
if (i % 100 == 0) {
dummy.addAndGet(new byte[random.nextInt(1024)].length);
}
}
}
// spend the rest of the time in both blocking and waiting states
start = System.currentTimeMillis();
while (System.currentTimeMillis() - start < 3 * millis) {
synchronized (lock) {
Thread.sleep(random.nextInt(10));
dummy.incrementAndGet();
}
Thread.sleep(1);
}
}
private String getTraceEntryMessage(boolean spaces) {
int traceEntryMessageLength = random.nextInt(maxTraceEntryMessageLength);
StringBuilder sb = new StringBuilder(traceEntryMessageLength);
for (int i = 0; i < traceEntryMessageLength; i++) {
// random lowercase character
sb.append((char) ('a' + random.nextInt(26)));
if (spaces && random.nextInt(6) == 0 && i != 0 && i != traceEntryMessageLength - 1) {
// on average, one of six characters will be a space (but not first or last char)
sb.append(' ');
}
}
return sb.toString();
}
}
| agent-parent/ui-sandbox/src/test/java/org/glowroot/agent/ui/sandbox/ExpensiveCall.java | /*
* Copyright 2012-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.glowroot.agent.ui.sandbox;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.ning.http.client.AsyncHttpClient;
public class ExpensiveCall {
private static final AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
private static final Random random = new Random();
private final int maxTimeMillis;
private final int maxTraceEntryMessageLength;
ExpensiveCall(int maxTimeMillis, int maxTraceEntryMessageLength) {
this.maxTimeMillis = maxTimeMillis;
this.maxTraceEntryMessageLength = maxTraceEntryMessageLength;
}
void execute() throws Exception {
int route = random.nextInt(11);
switch (route) {
case 0:
execute0();
return;
case 1:
execute1();
return;
case 2:
execute2();
return;
case 3:
execute3();
return;
case 4:
execute4();
return;
case 5:
execute5();
return;
case 6:
execute6();
return;
case 7:
execute7();
return;
case 8:
execute8();
return;
case 9:
execute9();
return;
default:
new AsyncWrapperCall(maxTimeMillis, maxTraceEntryMessageLength).execute();
}
}
private void execute0() throws InterruptedException {
expensive();
execute1();
}
private void execute1() throws InterruptedException {
expensive();
}
private void execute2() throws InterruptedException {
expensive();
execute3();
}
private void execute3() throws InterruptedException {
expensive();
}
private void execute4() throws InterruptedException {
expensive();
execute5();
try {
asyncHttpClient.prepareGet("http://example.org/hello").execute().get();
} catch (ExecutionException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void execute5() throws InterruptedException {
expensive();
}
private void execute6() throws InterruptedException {
expensive();
execute7();
}
private void execute7() throws InterruptedException {
expensive();
}
private void execute8() throws InterruptedException {
expensive();
execute9();
}
private void execute9() throws InterruptedException {
expensive();
}
public String getTraceEntryMessage() {
return getTraceEntryMessage(random.nextInt(5) > 0);
}
// this is just to prevent jvm from optimizing away for the loop below
public static final AtomicLong dummy = new AtomicLong();
// need
private static final Object lock = new Object();
static {
ThreadFactory threadFactory = new ThreadFactoryBuilder().setDaemon(true).build();
Executors.newSingleThreadExecutor(threadFactory).submit(new Callable<Void>() {
@Override
public Void call() throws InterruptedException {
// this loop is used to block threads executing expensive() below
while (true) {
synchronized (lock) {
Thread.sleep(random.nextInt(10));
}
Thread.sleep(1);
}
}
});
}
private void expensive() throws InterruptedException {
int millis = random.nextInt(maxTimeMillis) / 4;
// spend a quarter of the time taxing the cpu and doing memory allocation
long start = System.currentTimeMillis();
while (System.currentTimeMillis() - start < millis) {
for (int i = 0; i < 100000; i++) {
dummy.addAndGet(random.nextInt(1024));
if (i % 100 == 0) {
dummy.addAndGet(new byte[random.nextInt(1024)].length);
}
}
}
// spend the rest of the time in both blocking and waiting states
start = System.currentTimeMillis();
while (System.currentTimeMillis() - start < 3 * millis) {
synchronized (lock) {
Thread.sleep(random.nextInt(10));
dummy.incrementAndGet();
}
Thread.sleep(1);
}
}
private String getTraceEntryMessage(boolean spaces) {
int traceEntryMessageLength = random.nextInt(maxTraceEntryMessageLength);
StringBuilder sb = new StringBuilder(traceEntryMessageLength);
for (int i = 0; i < traceEntryMessageLength; i++) {
// random lowercase character
sb.append((char) ('a' + random.nextInt(26)));
if (spaces && random.nextInt(6) == 0 && i != 0 && i != traceEntryMessageLength - 1) {
// on average, one of six characters will be a space (but not first or last char)
sb.append(' ');
}
}
return sb.toString();
}
}
| Fix UI sandbox service call sample
| agent-parent/ui-sandbox/src/test/java/org/glowroot/agent/ui/sandbox/ExpensiveCall.java | Fix UI sandbox service call sample |
|
Java | apache-2.0 | 09b1ff1cf5a51b7319e1c8b8c88fac0cfe96281d | 0 | YoungDigitalPlanet/empiria.player,YoungDigitalPlanet/empiria.player,YoungDigitalPlanet/empiria.player | package eu.ydp.empiria.player.client.controller.body;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.xml.client.Element;
import eu.ydp.empiria.player.client.components.ModulePlaceholder;
import eu.ydp.empiria.player.client.module.IInlineModule;
import eu.ydp.empiria.player.client.module.IModule;
import eu.ydp.empiria.player.client.module.IMultiViewModule;
import eu.ydp.empiria.player.client.module.ISingleViewModule;
import eu.ydp.empiria.player.client.module.ISingleViewWithBodyModule;
import eu.ydp.empiria.player.client.module.ISingleViewSimpleModule;
import eu.ydp.empiria.player.client.module.ModuleSocket;
import eu.ydp.empiria.player.client.module.listener.ModuleInteractionListener;
import eu.ydp.empiria.player.client.module.registry.ModulesRegistrySocket;
import eu.ydp.empiria.player.client.util.StackMap;
public class ModulesInstalator implements ModulesInstalatorSocket {
protected ModulesRegistrySocket registry;
protected ModuleSocket moduleSocket;
protected ModuleInteractionListener moduleInteractionListener;
protected ParenthoodGeneratorSocket parenthood;
protected List<IModule> singleViewModules;
protected StackMap<String, StackMap<Element, HasWidgets>> uniqueModulesMap = new StackMap<String, StackMap<Element,HasWidgets>>();
protected StackMap<Element, HasWidgets> nonuniqueModulesMap = new StackMap<Element, HasWidgets>();
protected StackMap<String, IModule> multiViewModulesMap = new StackMap<String, IModule>();
public ModulesInstalator(ParenthoodGeneratorSocket pts, ModulesRegistrySocket reg, ModuleSocket ms, ModuleInteractionListener mil){
this.registry = reg;
this.moduleSocket = ms;
this.moduleInteractionListener = mil;
this.parenthood = pts;
singleViewModules = new ArrayList<IModule>();
}
@Override
public boolean isModuleSupported(String nodeName){
return registry.isModuleSupported(nodeName);
}
@Override
public boolean isMultiViewModule(String nodeName) {
return registry.isMultiViewModule(nodeName);
}
public void registerModuleView(Element element, HasWidgets parent){
String responseIdentifier = element.getAttribute("responseIdentifier");
ModulePlaceholder placeholder = new ModulePlaceholder();
parent.add(placeholder);
if (responseIdentifier != null){
if (!uniqueModulesMap.containsKey(responseIdentifier)){
uniqueModulesMap.put(responseIdentifier, new StackMap<Element, HasWidgets>());
}
if (!multiViewModulesMap.containsKey(responseIdentifier)){
IModule currModule = registry.createModule(element.getNodeName());
multiViewModulesMap.put(responseIdentifier, currModule);
parenthood.addChild(currModule);
}
uniqueModulesMap.get(responseIdentifier).put(element, placeholder);
} else {
nonuniqueModulesMap.put(element, placeholder);
}
}
@Override
public void createSingleViewModule(Element element, HasWidgets parent,BodyGeneratorSocket bodyGeneratorSocket) {
IModule module = registry.createModule(element.getNodeName());
parenthood.addChild(module);
if (module instanceof ISingleViewWithBodyModule){
parenthood.pushParent((ISingleViewWithBodyModule) module);
((ISingleViewWithBodyModule) module).initModule(element, moduleSocket, moduleInteractionListener, bodyGeneratorSocket);
parenthood.popParent();
} else if (module instanceof ISingleViewSimpleModule){
((ISingleViewSimpleModule)module).initModule(element, moduleSocket, moduleInteractionListener);
}else if(module instanceof IInlineModule){
((IInlineModule) module).initModule(element, moduleSocket);
}
if (((ISingleViewModule)module).getView() instanceof Widget ){
parent.add( ((ISingleViewModule)module).getView() );
}
singleViewModules.add(module);
}
public void installMultiViewNonuniuqeModules(){
for (Element currElement : nonuniqueModulesMap.getKeys()){
// TODO
}
}
public List<IModule> installMultiViewUniqueModules(){
List<IModule> modules = new ArrayList<IModule>();
for (String responseIdentifier : uniqueModulesMap.getKeys()){
StackMap<Element, HasWidgets> currModuleMap = uniqueModulesMap.get(responseIdentifier);
IModule currModule = null;
for (Element currElement : currModuleMap.getKeys()){
if (currModule == null){
currModule = multiViewModulesMap.get(responseIdentifier);
if (currModule instanceof IMultiViewModule){
((IMultiViewModule)currModule).initModule(moduleSocket, moduleInteractionListener);
}
}
if (currModule instanceof IMultiViewModule){
((IMultiViewModule)currModule).addElement(currElement);
}
}
if (currModule instanceof IMultiViewModule){
((IMultiViewModule)currModule).installViews(currModuleMap.getValues());
}
if (currModule != null){
modules.add(currModule);
}
}
return modules;
}
public List<IModule> getInstalledSingleViewModules(){
return singleViewModules;
}
public void setInitialParent(ISingleViewWithBodyModule parent){
parenthood.pushParent(parent);
}
}
| empiria.player/src/eu/ydp/empiria/player/client/controller/body/ModulesInstalator.java | package eu.ydp.empiria.player.client.controller.body;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.xml.client.Element;
import eu.ydp.empiria.player.client.components.ModulePlaceholder;
import eu.ydp.empiria.player.client.module.IModule;
import eu.ydp.empiria.player.client.module.IMultiViewModule;
import eu.ydp.empiria.player.client.module.ISingleViewModule;
import eu.ydp.empiria.player.client.module.ISingleViewWithBodyModule;
import eu.ydp.empiria.player.client.module.ISingleViewSimpleModule;
import eu.ydp.empiria.player.client.module.ModuleSocket;
import eu.ydp.empiria.player.client.module.listener.ModuleInteractionListener;
import eu.ydp.empiria.player.client.module.registry.ModulesRegistrySocket;
import eu.ydp.empiria.player.client.util.StackMap;
public class ModulesInstalator implements ModulesInstalatorSocket {
protected ModulesRegistrySocket registry;
protected ModuleSocket moduleSocket;
protected ModuleInteractionListener moduleInteractionListener;
protected ParenthoodGeneratorSocket parenthood;
protected List<IModule> singleViewModules;
protected StackMap<String, StackMap<Element, HasWidgets>> uniqueModulesMap = new StackMap<String, StackMap<Element,HasWidgets>>();
protected StackMap<Element, HasWidgets> nonuniqueModulesMap = new StackMap<Element, HasWidgets>();
protected StackMap<String, IModule> multiViewModulesMap = new StackMap<String, IModule>();
public ModulesInstalator(ParenthoodGeneratorSocket pts, ModulesRegistrySocket reg, ModuleSocket ms, ModuleInteractionListener mil){
this.registry = reg;
this.moduleSocket = ms;
this.moduleInteractionListener = mil;
this.parenthood = pts;
singleViewModules = new ArrayList<IModule>();
}
@Override
public boolean isModuleSupported(String nodeName){
return registry.isModuleSupported(nodeName);
}
@Override
public boolean isMultiViewModule(String nodeName) {
return registry.isMultiViewModule(nodeName);
}
public void registerModuleView(Element element, HasWidgets parent){
String responseIdentifier = element.getAttribute("responseIdentifier");
ModulePlaceholder placeholder = new ModulePlaceholder();
parent.add(placeholder);
if (responseIdentifier != null){
if (!uniqueModulesMap.containsKey(responseIdentifier)){
uniqueModulesMap.put(responseIdentifier, new StackMap<Element, HasWidgets>());
}
if (!multiViewModulesMap.containsKey(responseIdentifier)){
IModule currModule = registry.createModule(element.getNodeName());
multiViewModulesMap.put(responseIdentifier, currModule);
parenthood.addChild(currModule);
}
uniqueModulesMap.get(responseIdentifier).put(element, placeholder);
} else {
nonuniqueModulesMap.put(element, placeholder);
}
}
@Override
public void createSingleViewModule(Element element, HasWidgets parent,BodyGeneratorSocket bodyGeneratorSocket) {
IModule module = registry.createModule(element.getNodeName());
parenthood.addChild(module);
if (module instanceof ISingleViewWithBodyModule){
parenthood.pushParent((ISingleViewWithBodyModule) module);
((ISingleViewWithBodyModule) module).initModule(element, moduleSocket, moduleInteractionListener, bodyGeneratorSocket);
parenthood.popParent();
} else if (module instanceof ISingleViewSimpleModule){
((ISingleViewSimpleModule)module).initModule(element, moduleSocket, moduleInteractionListener);
}
if (((ISingleViewModule)module).getView() instanceof Widget ){
parent.add( ((ISingleViewModule)module).getView() );
}
singleViewModules.add(module);
}
public void installMultiViewNonuniuqeModules(){
for (Element currElement : nonuniqueModulesMap.getKeys()){
// TODO
}
}
public List<IModule> installMultiViewUniqueModules(){
List<IModule> modules = new ArrayList<IModule>();
for (String responseIdentifier : uniqueModulesMap.getKeys()){
StackMap<Element, HasWidgets> currModuleMap = uniqueModulesMap.get(responseIdentifier);
IModule currModule = null;
for (Element currElement : currModuleMap.getKeys()){
if (currModule == null){
currModule = multiViewModulesMap.get(responseIdentifier);
if (currModule instanceof IMultiViewModule){
((IMultiViewModule)currModule).initModule(moduleSocket, moduleInteractionListener);
}
}
if (currModule instanceof IMultiViewModule){
((IMultiViewModule)currModule).addElement(currElement);
}
}
if (currModule instanceof IMultiViewModule){
((IMultiViewModule)currModule).installViews(currModuleMap.getValues());
}
if (currModule != null){
modules.add(currModule);
}
}
return modules;
}
public List<IModule> getInstalledSingleViewModules(){
return singleViewModules;
}
public void setInitialParent(ISingleViewWithBodyModule parent){
parenthood.pushParent(parent);
}
}
| added initializing inline module
bug 60753
git-svn-id: fd5e0bdc55a948b8bf0a1d738c6140e6e4400378@100959 3e83ccf1-c6ce-0310-9054-8fdb33cf0640
| empiria.player/src/eu/ydp/empiria/player/client/controller/body/ModulesInstalator.java | added initializing inline module bug 60753 |
|
Java | apache-2.0 | 2bb3b45d64ccfed6470a58dce4e9bfb5639ef51c | 0 | scify/Memor-i,scify/Memor-i | package org.scify.memori.network;
import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.scify.memori.PlayerManager;
import org.scify.memori.interfaces.UserAction;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;
public class GameMovementManager {
public static final int MAX_REQUEST_TRIES_FOR_MOVEMENT = 100;
private RequestManager requestManager;
private static long timestampOfLastOpponentMovement;
protected Semaphore sMoveRequest = new Semaphore(1);
public static void setTimestampOfLastOpponentMovement(long timestampOfLastOpponentMovement) {
GameMovementManager.timestampOfLastOpponentMovement = timestampOfLastOpponentMovement;
}
public GameMovementManager() {
requestManager = new RequestManager();
}
public String sendMovementToServer(String movementJson, long userActionTimestamp) {
System.err.println("sending movement to server: " + movementJson);
String url = "gameMovement/create";
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("game_request_id", String.valueOf(GameRequestManager.getGameRequestId())));
urlParameters.add(new BasicNameValuePair("player_id", String.valueOf(PlayerManager.getPlayerId())));
urlParameters.add(new BasicNameValuePair("timestamp", String.valueOf(userActionTimestamp)));
urlParameters.add(new BasicNameValuePair("movement_json", movementJson));
return this.requestManager.doPost(url, urlParameters);
}
public boolean callOngoing() {
return sMoveRequest.availablePermits() == 0;
}
public UserAction getNextMovementFromServer() throws Exception {
// Use semaphore to ascertain that the call is served before another
sMoveRequest.acquire();
String url = "gameMovement/latest";
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("game_request_id", String.valueOf(GameRequestManager.getGameRequestId())));
urlParameters.add(new BasicNameValuePair("opponent_id", String.valueOf(PlayerManager.getOpponentPlayer().getId())));
urlParameters.add(new BasicNameValuePair("last_timestamp", String.valueOf(timestampOfLastOpponentMovement)));
System.out.println(url);
System.out.println(urlParameters.get(0).getValue());
System.out.println(urlParameters.get(1).getValue());
System.out.println(urlParameters.get(2).getValue());
String serverResponse = this.requestManager.doPost(url, urlParameters);
// Call served. Release semaphore.
sMoveRequest.release();
// TODO if post fails retry
return parseGameRequestResponse(serverResponse);
}
private UserAction parseGameRequestResponse(String serverResponse) throws Exception {
if(serverResponse == null)
return null;
Gson g = new Gson();
ServerOperationResponse response = g.fromJson(serverResponse, ServerOperationResponse.class);
int code = response.getCode();
switch (code) {
case ServerResponse.RESPONSE_SUCCESSFUL:
// game request was either accepted or rejected
LinkedTreeMap parameters = (LinkedTreeMap) response.getParameters();
LinkedTreeMap movement = (LinkedTreeMap) parameters.get("game_movement_json");
Object timestampObj = movement.get("timestamp");
String timestampStr = timestampObj.toString();
Long timestamp = Double.valueOf(Double.parseDouble(timestampStr)).longValue();
UserAction action = new UserAction(movement.get("actionType").toString(), movement.get("direction").toString(), timestamp);
return action;
case ServerResponse.RESPONSE_ERROR:
// error
return null;
case ServerResponse.VALIDATION_ERROR:
// server validation not passed
return null;
case ServerResponse.OPPONENT_OFFLINE:
// opponent went offline.
// throw an Exception to let rules know that the game Ended.
throw new Exception("Opponent offline!");
}
return null;
}
}
| src/main/java/org/scify/memori/network/GameMovementManager.java | package org.scify.memori.network;
import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.scify.memori.PlayerManager;
import org.scify.memori.interfaces.UserAction;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;
public class GameMovementManager {
public static final int MAX_REQUEST_TRIES_FOR_MOVEMENT = 200;
private RequestManager requestManager;
private static long timestampOfLastOpponentMovement;
protected Semaphore sMoveRequest = new Semaphore(1);
public static void setTimestampOfLastOpponentMovement(long timestampOfLastOpponentMovement) {
GameMovementManager.timestampOfLastOpponentMovement = timestampOfLastOpponentMovement;
}
public GameMovementManager() {
requestManager = new RequestManager();
}
public String sendMovementToServer(String movementJson, long userActionTimestamp) {
System.err.println("sending movement to server: " + movementJson);
String url = "gameMovement/create";
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("game_request_id", String.valueOf(GameRequestManager.getGameRequestId())));
urlParameters.add(new BasicNameValuePair("player_id", String.valueOf(PlayerManager.getPlayerId())));
urlParameters.add(new BasicNameValuePair("timestamp", String.valueOf(userActionTimestamp)));
urlParameters.add(new BasicNameValuePair("movement_json", movementJson));
return this.requestManager.doPost(url, urlParameters);
}
public boolean callOngoing() {
return sMoveRequest.availablePermits() == 0;
}
public UserAction getNextMovementFromServer() throws Exception {
// Use semaphore to ascertain that the call is served before another
sMoveRequest.acquire();
String url = "gameMovement/latest";
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("game_request_id", String.valueOf(GameRequestManager.getGameRequestId())));
urlParameters.add(new BasicNameValuePair("opponent_id", String.valueOf(PlayerManager.getOpponentPlayer().getId())));
urlParameters.add(new BasicNameValuePair("last_timestamp", String.valueOf(timestampOfLastOpponentMovement)));
System.out.println(url);
System.out.println(urlParameters.get(0).getValue());
System.out.println(urlParameters.get(1).getValue());
System.out.println(urlParameters.get(2).getValue());
String serverResponse = this.requestManager.doPost(url, urlParameters);
// Call served. Release semaphore.
sMoveRequest.release();
// TODO if post fails retry
return parseGameRequestResponse(serverResponse);
}
private UserAction parseGameRequestResponse(String serverResponse) throws Exception {
if(serverResponse == null)
return null;
Gson g = new Gson();
ServerOperationResponse response = g.fromJson(serverResponse, ServerOperationResponse.class);
int code = response.getCode();
switch (code) {
case ServerResponse.RESPONSE_SUCCESSFUL:
// game request was either accepted or rejected
LinkedTreeMap parameters = (LinkedTreeMap) response.getParameters();
LinkedTreeMap movement = (LinkedTreeMap) parameters.get("game_movement_json");
Object timestampObj = movement.get("timestamp");
String timestampStr = timestampObj.toString();
Long timestamp = Double.valueOf(Double.parseDouble(timestampStr)).longValue();
UserAction action = new UserAction(movement.get("actionType").toString(), movement.get("direction").toString(), timestamp);
return action;
case ServerResponse.RESPONSE_ERROR:
// error
return null;
case ServerResponse.VALIDATION_ERROR:
// server validation not passed
return null;
case ServerResponse.OPPONENT_OFFLINE:
// opponent went offline.
// throw an Exception to let rules know that the game Ended.
throw new Exception("Opponent offline!");
}
return null;
}
}
| Reduced time that a player has to do a movement
| src/main/java/org/scify/memori/network/GameMovementManager.java | Reduced time that a player has to do a movement |
|
Java | apache-2.0 | 5110c0a43007b30b7111f6cfd5dc3c1eaadf2c36 | 0 | trejkaz/derby,trejkaz/derby,apache/derby,apache/derby,apache/derby,trejkaz/derby,apache/derby | /*
Derby - Class org.apache.derbyTesting.functionTests.tests.upgradeTests.UpgradeTester
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.apache.derbyTesting.functionTests.tests.upgradeTests;
import java.net.URLClassLoader;
import java.net.URL;
import java.net.MalformedURLException;
import java.util.Properties;
import java.io.File;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.apache.derbyTesting.functionTests.harness.jvm;
/**
* Tests upgrades including soft upgrade. Test consists of following phases:
<OL>
<LI> Create database with the <B>old</B> release.
<LI> Boot the database with the <B>new</B> release in soft upgrade mode.
Try to execute functionality that is not allowed in soft upgrade.
<LI> Boot the database with the <B>old</B> release to ensure the
database can be booted by the old release after soft upgrade.
<LI> Boot the database with the <B>new</B> release in hard upgrade mode,
specifying the upgrade=true attribute.
<LI> Boot the database with the <B>old</B> release to ensure the
database can not be booted by the old release after hard upgrade.
</OL>
<P>
That's the general idea for GA releases. Alpha/beta releases do not
support upgrade unless the derby.database.allowPreReleaseUpgrade
property is set to true, in which case this program modifies the expected
behaviour.
<P>
<P>
This tests the following specifically.
<BR>
10.1 Upgrade issues
<UL>
<LI> Routines with explicit Java signatures.
</UL>
Metadata tests
<BR>
10.2 Upgrade tests
<UL>
<LI> caseReusableRecordIdSequenceNumber
<LI> Trigger action re-writing and implementation changes (DERBY-438)
<LI> Grant/Revoke tests
</UL>
*/
public class UpgradeTester {
/**
* Phases in upgrade test
*/
private static final String[] PHASES =
{"CREATE", "SOFT UPGRADE", "POST SOFT UPGRADE", "UPGRADE", "POST UPGRADE"};
/**
* Create a database with old version
*/
static final int PH_CREATE = 0;
/**
* Perform soft upgrade with new version
*/
static final int PH_SOFT_UPGRADE = 1;
/**
* Boot the database with old release after soft upgrade
*/
static final int PH_POST_SOFT_UPGRADE = 2;
/**
* Perform hard upgrade with new version
*/
static final int PH_HARD_UPGRADE = 3;
/**
* Boot the database with old release after hard upgrade
*/
static final int PH_POST_HARD_UPGRADE = 4;
/**
* Use old release for this phase
*/
private static final int OLD_RELEASE = 0;
/**
* Use new release for this phase
*/
private static final int NEW_RELEASE = 1;
// Location of jar file of old and new release
private String oldJarLoc;
private String newJarLoc;
// Class loader for old and new release jars
private URLClassLoader oldClassLoader;
private URLClassLoader newClassLoader;
// Major and Minor version number of old release
private int oldMajorVersion;
private int oldMinorVersion;
// Major and Minor version number of new release
private int newMajorVersion;
private int newMinorVersion;
// Indicate if alpha/beta releases should support upgrade
private boolean allowPreReleaseUpgrade;
private final String dbName = "wombat";
// We can specify more jars, as required.
private String[] jarFiles = new String [] { "derby.jar",
"derbynet.jar",
"derbyclient.jar",
"derbytools.jar"};
// Test jar
private String testJar = "derbyTesting.jar";
// Boolean to indicate if the test is run using jars or classes folder
// in classpath
private boolean[] isJar = new boolean[1];
/**
* Constructor
*
* @param oldMajorVersion Major version number of old release
* @param oldMinorVersion Minor version number of old release
* @param newMajorVersion Major version number of new release
* @param newMinorVersion Minor version number of new release
* @param allowPreReleaseUpgrade If true, set the system property
* 'derby.database.allowPreReleaseUpgrade' to indicate alpha/beta releases
* to support upgrade.
*/
public UpgradeTester(int oldMajorVersion, int oldMinorVersion,
int newMajorVersion, int newMinorVersion,
boolean allowPreReleaseUpgrade) {
this.oldMajorVersion = oldMajorVersion;
this.oldMinorVersion = oldMinorVersion;
this.newMajorVersion = newMajorVersion;
this.newMinorVersion = newMinorVersion;
this.allowPreReleaseUpgrade = allowPreReleaseUpgrade;
}
/**
* Set the location of jar files for old and new release
*/
private void setJarLocations() {
this.oldJarLoc = getOldJarLocation();
this.newJarLoc = getNewJarLocation();
}
/**
* Get the location of jars of old release. The location is specified
* in the property "derbyTesting.jar.path".
*
* @return location of jars of old release
*/
private String getOldJarLocation() {
String jarLocation = null;
String jarPath = System.getProperty("derbyTesting.jar.path");
if((jarPath != null) && (jarPath.compareTo("JAR_PATH_NOT_SET") == 0)) {
System.out.println("FAIL: Path to previous release jars not set");
System.out.println("Check if derbyTesting.jar.path property has been set in ant.properties file");
System.exit(-1);
}
String version = oldMajorVersion + "." + oldMinorVersion;
jarLocation = jarPath + File.separator + version;
return jarLocation;
}
/**
* Get the location of jar of new release. This is obtained from the
* classpath using findCodeBase method in jvm class.
*
* @return location of jars of new release
*/
private String getNewJarLocation() {
return jvm.findCodeBase(isJar);
}
/**
* This method creates two class loaders - one for old release and
* other for new release. It calls the appropriate create methods
* depending on what is used in the user's classpath - jars or
* classes folder
*
* @throws MalformedURLException
*/
private void createClassLoaders() throws MalformedURLException{
if(isJar[0]){
oldClassLoader = createClassLoader(oldJarLoc);
newClassLoader = createClassLoader(newJarLoc);
} else {
// classes folder in classpath
createLoadersUsingClasses();
}
}
/**
* Create a class loader using jars in the specified location. Add all jars
* specified in jarFiles and the testing jar.
*
* @param jarLoc Location of jar files
* @return class loader
* @throws MalformedURLException
*/
private URLClassLoader createClassLoader(String jarLoc)
throws MalformedURLException {
URL[] url = new URL[jarFiles.length + 1];
for(int i=0; i < jarFiles.length; i++) {
url[i] = new File(jarLoc + File.separator + jarFiles[i]).toURL();
}
// Add derbyTesting.jar. Added from newer release
url[jarFiles.length] = new File(newJarLoc + File.separator + testJar).toURL();
// Specify null for parent class loader to avoid mixing up
// jars specified in the system classpath
return new URLClassLoader(url, null);
}
/**
* Create old and new class loader. This method is used when classes folder
* is specified in the user's classpath.
*
* @throws MalformedURLException
*/
private void createLoadersUsingClasses()
throws MalformedURLException {
URL[] oldUrl = new URL[jarFiles.length + 1];
for(int i=0; i < jarFiles.length; i++) {
oldUrl[i] = new File(oldJarLoc + File.separator + jarFiles[i]).toURL();
}
// Use derby testing classes from newer release. To get the
// testing classes from newer release, we need to add the whole
// classes folder. So the oldClassLoader may contain extra classes
// from the newer version
oldUrl[jarFiles.length] = new File(newJarLoc).toURL();
oldClassLoader = new URLClassLoader(oldUrl, null);
URL[] newUrl = new URL[] {new File(newJarLoc).toURL()};
newClassLoader = new URLClassLoader(newUrl, null);
}
/**
* Set the context class loader
* @param classLoader class loader
*/
private static void setClassLoader(URLClassLoader classLoader) {
Thread.currentThread().setContextClassLoader(classLoader);
}
/**
* Set the context class loader to null
*/
private static void setNullClassLoader() {
Thread.currentThread().setContextClassLoader(null);
}
/**
* Runs the upgrade tests by calling runPhase for each phase.
* @throws Exception
*/
public void runUpgradeTests() throws Exception{
// Set the system property to allow alpha/beta release
// upgrade as specified
if(allowPreReleaseUpgrade)
System.setProperty("derby.database.allowPreReleaseUpgrade",
"true");
else
System.setProperty("derby.database.allowPreReleaseUpgrade",
"false");
setJarLocations();
createClassLoaders();
runPhase(OLD_RELEASE, PH_CREATE);
runPhase(NEW_RELEASE, PH_SOFT_UPGRADE);
runPhase(OLD_RELEASE, PH_POST_SOFT_UPGRADE);
runPhase(NEW_RELEASE, PH_HARD_UPGRADE);
runPhase(OLD_RELEASE, PH_POST_HARD_UPGRADE);
}
/**
* Runs each phase of upgrade test.
* 1. Chooses the classloader to use based on the release (old/new)
* 2. Gets a connection.
* 3. If connection is successful, checks the version using metadata,
* runs tests and shuts down the database.
*
* @param version Old or new version
* @param phase Upgrade test phase
* @throws Exception
*/
private void runPhase(int version, int phase)
throws Exception{
System.out.println("\n\nSTART - phase " + PHASES[phase]);
URLClassLoader classLoader = null;
switch(version) {
case OLD_RELEASE:
classLoader = oldClassLoader;
break;
case NEW_RELEASE:
classLoader = newClassLoader;
break;
default:
System.out.println("ERROR: Specified an invalid release type");
return;
}
boolean passed = true;
Connection conn = null;
setClassLoader(classLoader);
conn = getConnection(classLoader, phase);
if(conn != null) {
passed = caseVersionCheck(version, conn);
passed = caseReusableRecordIdSequenceNumber(conn, phase,
oldMajorVersion, oldMinorVersion) && passed;
passed = caseInitialize(conn, phase) && passed;
passed = caseProcedures(conn, phase, oldMajorVersion,
oldMinorVersion) && passed;
passed = caseTriggerVTI(conn, phase, oldMajorVersion,
oldMinorVersion) && passed;
passed = caseCompilationSchema(phase, conn) && passed;
passed = caseGrantRevoke(conn, phase, classLoader, false) && passed;
// Test grant/revoke feature with sql authorization
if(phase == PH_HARD_UPGRADE) {
setSQLAuthorization(conn, true);
conn = restartDatabase(classLoader);
passed = caseGrantRevoke(conn, phase, classLoader, true) && passed;
checkSysSchemas(conn);
checkRoutinePermissions(conn);
}
runMetadataTest(classLoader, conn);
conn.close();
shutdownDatabase(classLoader);
}
// when this test is run from the codeline using classes, the
// oldClassLoader class path contains the new derby engine
// classes also, this causes derby booting errors when database
// is encrypted (see DERBY-1898), until this test is modified to
// run without adding the whole class directory to the old derby
// classloader classpath, following two re-encryption test cases
// are run , only when this test is run using jar files.
if (isJar[0]) {
// test encryption of an un-encrypted database and
// encryption of an encrypted database with a new key.
passed = caseEncryptUnEncryptedDb(classLoader, phase) && passed;
passed = caseEncryptDatabaseWithNewKey(classLoader, phase) && passed;
}
setNullClassLoader();
System.out.println("END - " + (passed ? "PASS" : "FAIL") +
" - phase " + PHASES[phase]);
}
/**
* Get a connection to the database using the specified class loader.
* The connection attributes depend on the phase of upgrade test.
*
* @param classLoader Class loader
* @param phase Upgrade test phase
* @return connection to the database
* @throws Exception
*/
private Connection getConnection(URLClassLoader classLoader,
int phase) throws Exception{
Connection conn = null;
Properties prop = new Properties();
prop.setProperty("databaseName", dbName);
switch(phase) {
case PH_CREATE:
prop.setProperty("connectionAttributes", "create=true");
break;
case PH_SOFT_UPGRADE:
case PH_POST_SOFT_UPGRADE:
case PH_POST_HARD_UPGRADE:
break;
case PH_HARD_UPGRADE:
prop.setProperty("connectionAttributes", "upgrade=true");
break;
default:
break;
}
try {
conn = getConnectionUsingDataSource(classLoader, prop);
} catch (SQLException sqle) {
if(phase != PH_POST_HARD_UPGRADE)
throw sqle;
// After hard upgrade, we should not be able to boot
// the database with older version. Possible SQLStates are
// XSLAP, if the new release is alpha/beta; XSLAN, otherwise.
if(sqle.getSQLState().equals("XJ040")) {
SQLException nextSqle = sqle.getNextException();
if(nextSqle.getSQLState().equals("XSLAP") ||
nextSqle.getSQLState().equals("XSLAN") )
System.out.println("Expected exception: Failed to start" +
" database with old version after hard upgrade");
}
}
return conn;
}
/**
* Get a connection using data source obtained from TestUtil class.
* Load TestUtil class using the specified class loader.
*
* @param classLoader
* @param prop
* @return
* @throws Exception
*/
private Connection getConnectionUsingDataSource(URLClassLoader classLoader, Properties prop) throws Exception{
Connection conn = null;
try {
Class testUtilClass = Class.forName("org.apache.derbyTesting.functionTests.util.TestUtil",
true, classLoader);
Object testUtilObject = testUtilClass.newInstance();
// Instead of calling TestUtil.getDataSourceConnection, call
// TestUtil.getDataSource and then call its getConnection method.
// This is because we do not want to lose the SQLException
// which we get when shutting down the database.
java.lang.reflect.Method method = testUtilClass.getMethod("getDataSource", new Class[] { prop.getClass() });
DataSource ds = (DataSource) method.invoke(testUtilClass, new Object[] { prop });
conn = ds.getConnection();
} catch(SQLException sqle) {
throw sqle;
} catch (Exception e) {
handleReflectionExceptions(e);
throw e;
}
return conn;
}
/**
* Verify the product version from metadata
* @param version Old or new version
* @param conn Connection
* @throws SQLException
*/
private boolean caseVersionCheck(int version, Connection conn)
throws SQLException{
boolean passed = false;
int actualMajorVersion;
int actualMinorVersion;
if (conn == null)
return false;
actualMajorVersion = conn.getMetaData().getDatabaseMajorVersion();
actualMinorVersion = conn.getMetaData().getDatabaseMinorVersion();
switch(version) {
case OLD_RELEASE:
passed = (actualMajorVersion == oldMajorVersion) && (actualMinorVersion == oldMinorVersion);
break;
case NEW_RELEASE:
passed = (actualMajorVersion == newMajorVersion) && (actualMinorVersion == newMinorVersion);
break;
default:
passed = false;
break;
}
System.out.println("complete caseVersionCheck - passed " + passed);
return passed;
}
/**
* Verify the compilation schema is nullable after upgrade
* @param phase upgrade test phase
* @param conn Connection
* @throws SQLException
*/
private boolean caseCompilationSchema(int phase, Connection conn)
throws SQLException
{
boolean passed = false;
DatabaseMetaData dmd;
ResultSet rs;
String isNullable;
if (conn == null)
return false;
dmd = conn.getMetaData();
switch (phase)
{
case PH_CREATE:
case PH_POST_SOFT_UPGRADE:
case PH_POST_HARD_UPGRADE:
passed = true;
break;
case PH_SOFT_UPGRADE:
case PH_HARD_UPGRADE:
rs = dmd.getColumns(null, "SYS", "SYSSTATEMENTS", "COMPILATIONSCHEMAID");
rs.next();
isNullable = rs.getString("IS_NULLABLE");
System.out.println ("SYS.SYSSTATEMENTS.COMPILATIONSCHEMAID IS_NULLABLE=" + isNullable);
passed = ("YES".equals(isNullable));
rs = dmd.getColumns(null, "SYS", "SYSVIEWS", "COMPILATIONSCHEMAID");
rs.next();
isNullable = rs.getString("IS_NULLABLE");
System.out.println("SYS.SYSVIEWS.COMPILATIONSCHEMAID IS_NULLABLE=" + isNullable);
passed = ("YES".equals(isNullable)) && passed;
break;
default:
passed = false;
break;
}
System.out.println("complete caseCompilationSchema - passed " + passed);
return passed;
}
/**
* In 10.2: We will write a ReusableRecordIdSequenceNumber in the
* header of a FileContaienr.
*
* Verify here that a 10.1 Database does not malfunction from this.
* 10.1 Databases should ignore the field.
*/
static boolean caseReusableRecordIdSequenceNumber(Connection conn,
int phase,
int dbMajor, int dbMinor)
throws SQLException
{
boolean runCompress = dbMajor>10 || dbMajor==10 && dbMinor>=1;
final boolean passed;
switch(phase) {
case PH_CREATE: {
Statement s = conn.createStatement();
s.execute("create table CT1(id int)");
s.execute("insert into CT1 values 1,2,3,4,5,6,7,8,9,10");
conn.commit();
passed = true;
break;
}
case PH_SOFT_UPGRADE:
if (runCompress) {
System.out.println("caseReusableRecordIdSequenceNumber - Running compress");
PreparedStatement ps = conn.prepareStatement
("call SYSCS_UTIL.SYSCS_INPLACE_COMPRESS_TABLE(?,?,?,?,?)");
ps.setString(1, "APP"); // schema
ps.setString(2, "CT1"); // table name
ps.setInt(3, 1); // purge
ps.setInt(4, 1); // defragment rows
ps.setInt(5, 1); // truncate end
ps.executeUpdate();
conn.commit();
}
passed = true;
break;
case PH_POST_SOFT_UPGRADE: {
// We are now back to i.e 10.1
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("select * from CT1");
while (rs.next()) {
rs.getInt(1);
}
s.execute("insert into CT1 values 11,12,13,14,15,16,17,18,19");
conn.commit();
passed = true;
break;
}
case PH_HARD_UPGRADE:
passed = true;
break;
default:
passed = false;
break;
}
System.out.println("complete caseReusableRecordIdSequenceNumber - passed " + passed);
return passed;
}
/**
* Perform some transactions
*
* @param conn Connection
* @param phase Upgrade test phase
* @return true if the test passes
* @throws SQLException
*/
private boolean caseInitialize(Connection conn, int phase)
throws SQLException {
boolean passed = true;
switch (phase) {
case PH_CREATE:
conn.createStatement().executeUpdate("CREATE TABLE PHASE" +
"(id INT NOT NULL, ok INT)");
conn.createStatement().executeUpdate("CREATE TABLE TABLE1" +
"(id INT NOT NULL PRIMARY KEY, name varchar(200))");
break;
case PH_SOFT_UPGRADE:
break;
case PH_POST_SOFT_UPGRADE:
break;
case PH_HARD_UPGRADE:
break;
default:
passed = false;
break;
}
PreparedStatement ps = conn.prepareStatement("INSERT INTO PHASE(id) " +
"VALUES (?)");
ps.setInt(1, phase);
ps.executeUpdate();
ps.close();
// perform some transactions
ps = conn.prepareStatement("INSERT INTO TABLE1 VALUES (?, ?)");
for (int i = 1; i < 20; i++)
{
ps.setInt(1, i + (phase * 100));
ps.setString(2, "p" + phase + "i" + i);
ps.executeUpdate();
}
ps.close();
ps = conn.prepareStatement("UPDATE TABLE1 set name = name || 'U' " +
" where id = ?");
for (int i = 1; i < 20; i+=3)
{
ps.setInt(1, i + (phase * 100));
ps.executeUpdate();
}
ps.close();
ps = conn.prepareStatement("DELETE FROM TABLE1 where id = ?");
for (int i = 1; i < 20; i+=4)
{
ps.setInt(1, i + (phase * 100));
ps.executeUpdate();
}
ps.close();
System.out.println("complete caseInitialize - passed " + passed);
return passed;
}
/**
* Procedures
* 10.1 - Check that a procedure with a signature can not be added if the
* on-disk database version is 10.0.
*
* @param conn Connection
* @param phase Upgrade test phase
* @param dbMajor Major version of old release
* @param dbMinor Minor version of old release
* @return true, if the test passes
* @throws SQLException
*/
private boolean caseProcedures(Connection conn, int phase,
int dbMajor, int dbMinor)
throws SQLException {
boolean signaturesAllowedInOldRelease =
dbMajor > 10 || (dbMajor == 10 && dbMinor >= 1);
boolean passed = true;
switch (phase) {
case PH_CREATE:
break;
case PH_SOFT_UPGRADE:
try {
conn.createStatement().execute("CREATE PROCEDURE GC() " +
"LANGUAGE JAVA PARAMETER STYLE JAVA EXTERNAL NAME" +
" 'java.lang.System.gc()'");
if (!signaturesAllowedInOldRelease)
{
System.out.println("FAIL : created procedure with " +
"signature");
passed = false;
}
} catch (SQLException sqle) {
if (signaturesAllowedInOldRelease
|| !"XCL47".equals(sqle.getSQLState())) {
System.out.println("FAIL " + sqle.getSQLState()
+ " -- " + sqle.getMessage());
passed = false;
}
}
break;
case PH_POST_SOFT_UPGRADE:
try {
conn.createStatement().execute("CALL GC()");
if (!signaturesAllowedInOldRelease)
System.out.println("FAIL : procedure was created" +
" in soft upgrade!");
} catch (SQLException sqle)
{
if (signaturesAllowedInOldRelease)
System.out.println("FAIL : procedure was created not in " +
"soft upgrade!" + sqle.getMessage());
}
break;
case PH_HARD_UPGRADE:
if (!signaturesAllowedInOldRelease)
conn.createStatement().execute("CREATE PROCEDURE GC() " +
"LANGUAGE JAVA PARAMETER STYLE JAVA EXTERNAL NAME " +
"'java.lang.System.gc()'");
conn.createStatement().execute("CALL GC()");
break;
default:
passed = false;
break;
}
System.out.println("complete caseProcedures - passed " + passed);
return passed;
}
/**
* Triger (internal) VTI
* 10.2 - Check that a statement trigger created in 10.0
* or 10.1 can be executed in 10.2 and that a statement
* trigger created in soft upgrade in 10.2 can be used
* in older releases.
*
* The VTI implementing statement triggers changed in
* 10.2 from implementations of ResultSet to implementations
* of PreparedStatement. See DERBY-438. The internal
* api for the re-written action statement remains the
* same. The re-compile of the trigger on version changes
* should automatically switch between the two implementations.
*
* @param conn Connection
* @param phase Upgrade test phase
* @param dbMajor Major version of old release
* @param dbMinor Minor version of old release
* @return true, if the test passes
* @throws SQLException
*/
private boolean caseTriggerVTI(Connection conn, int phase,
int dbMajor, int dbMinor)
throws SQLException {
boolean passed = true;
Statement s = conn.createStatement();
switch (phase) {
case PH_CREATE:
s.execute("CREATE TABLE D438.T438(a int, b varchar(20), c int)");
s.execute("INSERT INTO D438.T438 VALUES(1, 'DERBY-438', 2)");
s.execute("CREATE TABLE D438.T438_T1(a int, b varchar(20))");
s.execute("CREATE TABLE D438.T438_T2(a int, c int)");
s.execute(
"create trigger D438.T438_ROW_1 after UPDATE on D438.T438 " +
"referencing new as n old as o " +
"for each row mode db2sql "+
"insert into D438.T438_T1(a, b) values (n.a, n.b || '_ROW')");
s.executeUpdate(
"create trigger D438.T438_STMT_1 after UPDATE on D438.T438 " +
"referencing new_table as n " +
"for each statement mode db2sql "+
"insert into D438.T438_T1(a, b) select n.a, n.b || '_STMT' from n");
conn.commit();
showTriggerVTITables(phase, s);
break;
case PH_SOFT_UPGRADE:
s.execute(
"create trigger D438.T438_ROW_2 after UPDATE on D438.T438 " +
"referencing new as n old as o " +
"for each row mode db2sql "+
"insert into D438.T438_T2(a, c) values (n.a, n.c + 100)");
s.executeUpdate(
"create trigger D438.T438_STMT_2 after UPDATE on D438.T438 " +
"referencing new_table as n " +
"for each statement mode db2sql "+
"insert into D438.T438_T2(a, c) select n.a, n.c + 4000 from n");
conn.commit();
showTriggerVTITables(phase, s);
break;
case PH_POST_SOFT_UPGRADE:
showTriggerVTITables(phase, s);
break;
case PH_HARD_UPGRADE:
showTriggerVTITables(phase, s);
break;
default:
passed = false;
break;
}
s.close();
System.out.println("complete caseTriggerVTI - passed " + passed);
return passed;
}
/**
* Display the tables populated by the triggers.
*/
private void showTriggerVTITables(int phase, Statement s) throws SQLException
{
System.out.println("Trigger VTI Phase: " + PHASES[phase]);
s.executeUpdate("UPDATE D438.T438 set c = c + 1");
s.getConnection().commit();
System.out.println("D438.T438_T1");
ResultSet rs = s.executeQuery("SELECT a,b from D438.T438_T1 ORDER BY 2");
while (rs.next()) {
System.out.println(rs.getInt(1) + ", " + rs.getString(2));
}
rs.close();
System.out.println("D438.T438_T2");
rs = s.executeQuery("SELECT a,c from D438.T438_T2 ORDER BY 2");
while (rs.next()) {
System.out.println(rs.getInt(1) + ", " + rs.getString(2));
}
rs.close();
s.executeUpdate("DELETE FROM D438.T438_T1");
s.executeUpdate("DELETE FROM D438.T438_T2");
s.getConnection().commit();
}
/**
* Grant/revoke is a new feature in 10.2. Test that this feature is not
* supported by default after upgrade from versions earlier than 10.2.
* This feature will not be available in soft upgrade. For grant/revoke
* to be available after a full upgrade, the database property
* "derby.database.sqlAuthorization" has to be set to true after upgrade.
*
* @param conn Connection
* @param phase Upgrade test phase
* @param classLoader Class loader
* @param sqlAuthorization Value of SQL authorization for the database
* @return true, if the test passes
* @throws Exception
*/
private boolean caseGrantRevoke(Connection conn, int phase,
URLClassLoader classLoader,
boolean sqlAuthorization)
throws Exception {
System.out.println("Test grant/revoke, Phase: " + PHASES[phase] + "; "
+ "derby.database.sqlAuthorization=" + sqlAuthorization);
boolean passed = true;
boolean grantRevokeSupport = ((oldMajorVersion==10 && oldMinorVersion>=2) ||
(newMajorVersion==10 && newMinorVersion>=2))
&& sqlAuthorization;
Statement s = conn.createStatement();
switch (phase) {
case PH_CREATE:
s.execute("create table GR_TAB (id int)");
break;
case PH_SOFT_UPGRADE:
case PH_POST_SOFT_UPGRADE:
passed = testGrantRevokeSupport(s, phase, grantRevokeSupport);
break;
case PH_HARD_UPGRADE:
passed = testGrantRevokeSupport(s, phase, grantRevokeSupport);
break;
default:
passed = false;
break;
}
s.close();
System.out.println("complete caseGrantRevoke - passed " + passed);
return passed;
}
/**
* Test to check whether grant/revoke is supported in a specific upgrade
* test phase.
*
* @param s SQL statement
* @param phase Upgrade test phase
* @param grantRevokeSupport true if grant/revoke feature is supported in
* a specific version/upgrade phase.
* @return true, if the test passes.
*/
private boolean testGrantRevokeSupport(Statement s, int phase,
boolean grantRevokeSupport) {
boolean passed = true;
try {
s.execute("grant select on GR_TAB to some_user");
} catch(SQLException sqle) {
passed = checkGrantRevokeException(sqle, phase, grantRevokeSupport);
}
try {
s.execute("revoke select on GR_TAB from some_user");
} catch(SQLException sqle) {
passed = checkGrantRevokeException(sqle, phase, grantRevokeSupport);
}
return passed;
}
/**
* Checks if the exception is expected based on whether grant/revoke is
* supported or not.
*
* @param sqle SQL Exception
* @param phase Upgrade test phase
* @param grantRevokeSupported true if grant/revoke feature is supported in
* a specific version/upgrade phase.
* @return
*/
private boolean checkGrantRevokeException(SQLException sqle, int phase,
boolean grantRevokeSupported) {
boolean passed = true;
// If grant/revoke is supported, we should not get an exception
if(grantRevokeSupported) {
dumpSQLExceptions(sqle);
return false;
}
switch (phase) {
case PH_SOFT_UPGRADE:
// feature not available in soft upgrade
passed = isExpectedException(sqle, "XCL47");
break;
case PH_POST_SOFT_UPGRADE:
// syntax error in versions earlier than 10.2
passed = isExpectedException(sqle, "42X01");
break;
case PH_HARD_UPGRADE:
// not supported because SQL authorization not set
passed = isExpectedException(sqle, "42Z60");
break;
default:
passed = false;
}
return passed;
}
/**
* Set derby.database.sqlAuthorization as a database property.
*
* @param conn Connection
* @param sqlAuth Value of property
*/
private void setSQLAuthorization(Connection conn, boolean sqlAuth) {
String authorization = sqlAuth ? "true" : "false";
try {
Statement s = conn.createStatement();
s.execute("call SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(" +
"'derby.database.sqlAuthorization', '" + authorization +
"')");
} catch (SQLException sqle) {
dumpSQLExceptions(sqle);
}
}
/**
* This method lists the schema names and authorization ids in
* SYS.SCHEMAS table. This is to test that the owner of system schemas is
* changed from pseudo user "DBA" to the user invoking upgrade.
*
* @param conn
* @throws SQLException
*/
private void checkSysSchemas(Connection conn) throws SQLException{
System.out.println("Checking SYSSCHEMAS");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("select * from SYS.SYSSCHEMAS");
while(rs.next()) {
System.out.println("SCHEMANAME: " + rs.getString(2) + " , "
+ "AUTHORIZATIONID: " + rs.getString(3));
}
rs.close();
s.close();
}
/**
* This method checks that some system routines are granted public access
* after a full upgrade.
*
* @param conn
* @throws SQLException
*/
private void checkRoutinePermissions(Connection conn) throws SQLException{
System.out.println("Checking routine permissions in SYSROUTINEPERMS");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("select aliases.ALIAS, " +
"routinePerms.GRANTEE, routinePerms.GRANTOR from " +
"SYS.SYSROUTINEPERMS routinePerms, " +
"SYS.SYSALIASES aliases " +
"where routinePerms.ALIASID=aliases.ALIASID " +
"order by aliases.ALIAS");
while(rs.next()) {
System.out.println("ROUTINE NAME: " + rs.getString(1) + " , " +
"GRANTEE: " + rs.getString(2) + " , " +
"GRANTOR: " + rs.getString(3));
}
rs.close();
s.close();
}
/**
* Run metadata test
*
* @param classLoader Class loader to be used to load the test class
* @param conn Connection
* @throws Exception
*/
private void runMetadataTest(URLClassLoader classLoader, Connection conn)
throws Exception{
try {
Statement stmt = conn.createStatement();
Class metadataClass = Class.forName("org.apache.derbyTesting.functionTests.tests.jdbcapi.metadata",
true, classLoader);
Object metadataObject = metadataClass.newInstance();
java.lang.reflect.Field f1 = metadataClass.getField("con");
f1.set(metadataObject, conn);
java.lang.reflect.Field f2 = metadataClass.getField("s");
f2.set(metadataObject, stmt);
java.lang.reflect.Method method = metadataClass.getMethod("runTest",
null);
method.invoke(metadataObject, null);
} catch(SQLException sqle) {
throw sqle;
} catch (Exception e) {
handleReflectionExceptions(e);
throw e;
}
}
/**
* This method checks if a database can be configured for
* encryption on hard upgrade to 10.2, but not on
* soft-upgrade to 10.2. Only in versions 10.2 or above
* an exisiting un-encrypted database can be configure
* for encryption.
*
* @param classLoader Class loader
* @param phase Upgrade test phase
* @throws Exception
*/
private boolean caseEncryptUnEncryptedDb(URLClassLoader classLoader,
int phase) throws Exception {
Properties prop = new Properties();
// create a new database for this test case,
// this database is used to test encryption of an
// already existing database during soft/upgrade
// phases.
String enDbName = "wombat_en";
prop.setProperty("databaseName", enDbName);
// check if the database at version 10.2 or above.
boolean reEncryptionAllowed = (oldMajorVersion > 10 ||
(oldMajorVersion ==10 &&
oldMinorVersion>=2));
boolean passed = true;
switch(phase) {
case PH_CREATE:
prop.setProperty("connectionAttributes",
"create=true");
break;
case PH_SOFT_UPGRADE:
// set attributes to encrypt database.
prop.setProperty("connectionAttributes",
"dataEncryption=true;" +
"bootPassword=xyz1234abc");
break;
case PH_POST_SOFT_UPGRADE:
// set attributes required to boot an encrypted database.
if (reEncryptionAllowed)
prop.setProperty("connectionAttributes",
"bootPassword=xyz1234abc");
break;
case PH_HARD_UPGRADE:
if (reEncryptionAllowed) {
// if database is already encrypted in
// softupgrade phase, just boot it.
prop.setProperty("connectionAttributes",
"upgrade=true;bootPassword=xyz1234abc");
} else {
// set attributes to encrypt the database,
// on hard upgrade.
prop.setProperty("connectionAttributes",
"upgrade=true;dataEncryption=true;" +
"bootPassword=xyz1234abc");
}
//prop.setProperty("connectionAttributes",
// "upgrade=true;bootPassword=xyz1234abc");
break;
default:
return passed;
}
Connection conn = null;
try {
conn = getConnectionUsingDataSource(classLoader, prop);
} catch (SQLException sqle) {
if(phase != PH_SOFT_UPGRADE)
throw sqle ;
else {
// on soft upgrade to 10.2, one should not be able to
// configure an un-encrypted database for encryption.
// It should fail failed with sql states "XJ040" and "XCL47".
if(!reEncryptionAllowed) {
passed = isExpectedException(sqle, "XJ040");
SQLException nextSqle = sqle.getNextException();
passed = isExpectedException(nextSqle, "XCL47");
} else
throw sqle;
}
}
if (conn != null) {
conn.close();
shutdownDatabase(classLoader, enDbName, false);
}
return passed;
}
/**
* This method checks if a database can be encrypted with a
* new encryption key(using boot password method)
* on hard upgrade to 10.2, but not on soft-upgrade to 10.2.
* Only ib versions 10.2 or above an exisiting encrypted
* database can be re-encrypted with a new key.
*
* @param classLoader Class loader
* @param phase Upgrade test phase
* @throws Exception
*/
private boolean caseEncryptDatabaseWithNewKey(URLClassLoader classLoader,
int phase) throws Exception{
Properties prop = new Properties();
// create a new database for this test case,
// this database is used to test re-encryption of an
// encrypted database during soft/upgrade
// phases.
String renDbName = "wombat_ren";
prop.setProperty("databaseName", renDbName);
// check if the database at version 10.2 or above
boolean reEncryptionAllowed = (oldMajorVersion > 10 ||
(oldMajorVersion ==10 &&
oldMinorVersion>=2));
boolean passed = true;
String bootPwd = (reEncryptionAllowed ? "new1234abc" : "xyz1234abc");
switch(phase) {
case PH_CREATE:
// set attributes to create an encrypted database.
prop.setProperty("connectionAttributes",
"create=true;" +
"dataEncryption=true;bootPassword=xyz1234abc");
break;
case PH_SOFT_UPGRADE:
// set attributes to rencrypt with a new password.
prop.setProperty("connectionAttributes",
"bootPassword=xyz1234abc;" +
"newBootPassword=new1234abc");
break;
case PH_POST_SOFT_UPGRADE:
prop.setProperty("connectionAttributes",
"bootPassword=" + bootPwd);
break;
case PH_HARD_UPGRADE:
prop.setProperty("connectionAttributes",
"upgrade=true;bootPassword=" + bootPwd +
";newBootPassword=new1234xyz");
break;
default:
return passed;
}
Connection conn = null;
try {
conn = getConnectionUsingDataSource(classLoader, prop);
} catch (SQLException sqle) {
if(phase != PH_SOFT_UPGRADE)
throw sqle ;
else {
// on soft upgrade to 10.2, one should not be able to
// re-encrypt an existing encrypted database with a new key or
// encrypt an un-encrypted database. It should have failed
// with sql states "XJ040" and "XCL47".
if(!reEncryptionAllowed) {
passed = isExpectedException(sqle, "XJ040");
SQLException nextSqle = sqle.getNextException();
passed = isExpectedException(nextSqle, "XCL47");
} else
throw sqle;
}
}
if (conn != null) {
conn.close();
shutdownDatabase(classLoader, renDbName, false);
}
return passed;
}
/**
* Shutdown the database
* @param classLoader
* @throws Exception
*/
private void shutdownDatabase(URLClassLoader classLoader)
throws Exception
{
shutdownDatabase(classLoader, dbName, true);
}
/**
* Shutdown the database
* @param classLoader
* @param databaseName name of the database to shutdown.
* @throws Exception
*/
private void shutdownDatabase(URLClassLoader classLoader,
String databaseName,
boolean printMessage)
throws Exception {
Properties prop = new Properties();
prop.setProperty("databaseName", databaseName);
prop.setProperty("connectionAttributes", "shutdown=true");
try {
getConnectionUsingDataSource(classLoader, prop);
} catch (SQLException sqle) {
if(sqle.getSQLState().equals("08006")) {
if (printMessage)
System.out.println("Expected exception during shutdown: "
+ sqle.getMessage());
} else
throw sqle;
}
}
/**
* Start the database
*
* @param classLoader
* @return
* @throws Exception
*/
private Connection startDatabase(URLClassLoader classLoader)
throws Exception {
Connection conn = null;
Properties prop = new Properties();
prop.setProperty("databaseName", dbName);
try {
conn = getConnectionUsingDataSource(classLoader, prop);
} catch (SQLException sqle) {
dumpSQLExceptions(sqle);
}
return conn;
}
/**
* Shutdown and reconnect to the database
* @param classLoader
* @return
* @throws Exception
*/
private Connection restartDatabase(URLClassLoader classLoader)
throws Exception {
shutdownDatabase(classLoader);
return startDatabase(classLoader);
}
/**
* Display the sql exception
* @param sqle SQLException
*/
public static void dumpSQLExceptions(SQLException sqle) {
do
{
System.out.println("SQLSTATE("+sqle.getSQLState()+"): "
+ sqle.getMessage());
sqle = sqle.getNextException();
} while (sqle != null);
}
/**
* Check if the exception is expected.
*
* @param sqle SQL Exception
* @param expectedSQLState Expected SQLState
* @return true, if SQLState of the exception is same as expected SQLState
*/
private boolean isExpectedException(SQLException sqle, String expectedSQLState) {
boolean passed = true;
if(!expectedSQLState.equals(sqle.getSQLState())) {
passed = false;
System.out.println("Fail - Unexpected exception:");
dumpSQLExceptions(sqle);
}
return passed;
}
/**
* Prints the possible causes for exceptions thrown when trying to
* load classes and invoke methods.
*
* @param e Exception
*/
private void handleReflectionExceptions(Exception e) {
System.out.println("FAIL - Unexpected exception - " + e.getMessage());
System.out.println("Possible Reason - Test could not find the " +
"location of jar files. Please check if you are running " +
"with jar files in the classpath. The test does not run with " +
"classes folder in the classpath. Also, check that old " +
"jars are checked out from the repository or specified in " +
"derbyTesting.jar.path property in ant.properties");
e.printStackTrace();
}
}
| java/testing/org/apache/derbyTesting/functionTests/tests/upgradeTests/UpgradeTester.java | /*
Derby - Class org.apache.derbyTesting.functionTests.tests.upgradeTests.UpgradeTester
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.apache.derbyTesting.functionTests.tests.upgradeTests;
import java.net.URLClassLoader;
import java.net.URL;
import java.net.MalformedURLException;
import java.util.Properties;
import java.io.File;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.apache.derbyTesting.functionTests.harness.jvm;
/**
* Tests upgrades including soft upgrade. Test consists of following phases:
<OL>
<LI> Create database with the <B>old</B> release.
<LI> Boot the database with the <B>new</B> release in soft upgrade mode.
Try to execute functionality that is not allowed in soft upgrade.
<LI> Boot the database with the <B>old</B> release to ensure the
database can be booted by the old release after soft upgrade.
<LI> Boot the database with the <B>new</B> release in hard upgrade mode,
specifying the upgrade=true attribute.
<LI> Boot the database with the <B>old</B> release to ensure the
database can not be booted by the old release after hard upgrade.
</OL>
<P>
That's the general idea for GA releases. Alpha/beta releases do not
support upgrade unless the derby.database.allowPreReleaseUpgrade
property is set to true, in which case this program modifies the expected
behaviour.
<P>
<P>
This tests the following specifically.
<BR>
10.1 Upgrade issues
<UL>
<LI> Routines with explicit Java signatures.
</UL>
Metadata tests
<BR>
10.2 Upgrade tests
<UL>
<LI> caseReusableRecordIdSequenceNumber
<LI> Trigger action re-writing and implementation changes (DERBY-438)
<LI> Grant/Revoke tests
</UL>
*/
public class UpgradeTester {
/**
* Phases in upgrade test
*/
private static final String[] PHASES =
{"CREATE", "SOFT UPGRADE", "POST SOFT UPGRADE", "UPGRADE", "POST UPGRADE"};
/**
* Create a database with old version
*/
static final int PH_CREATE = 0;
/**
* Perform soft upgrade with new version
*/
static final int PH_SOFT_UPGRADE = 1;
/**
* Boot the database with old release after soft upgrade
*/
static final int PH_POST_SOFT_UPGRADE = 2;
/**
* Perform hard upgrade with new version
*/
static final int PH_HARD_UPGRADE = 3;
/**
* Boot the database with old release after hard upgrade
*/
static final int PH_POST_HARD_UPGRADE = 4;
/**
* Use old release for this phase
*/
private static final int OLD_RELEASE = 0;
/**
* Use new release for this phase
*/
private static final int NEW_RELEASE = 1;
// Location of jar file of old and new release
private String oldJarLoc;
private String newJarLoc;
// Class loader for old and new release jars
private URLClassLoader oldClassLoader;
private URLClassLoader newClassLoader;
// Major and Minor version number of old release
private int oldMajorVersion;
private int oldMinorVersion;
// Major and Minor version number of new release
private int newMajorVersion;
private int newMinorVersion;
// Indicate if alpha/beta releases should support upgrade
private boolean allowPreReleaseUpgrade;
private final String dbName = "wombat";
// We can specify more jars, as required.
private String[] jarFiles = new String [] { "derby.jar",
"derbynet.jar",
"derbyclient.jar",
"derbytools.jar"};
// Test jar
private String testJar = "derbyTesting.jar";
// Boolean to indicate if the test is run using jars or classes folder
// in classpath
private boolean[] isJar = new boolean[1];
/**
* Constructor
*
* @param oldMajorVersion Major version number of old release
* @param oldMinorVersion Minor version number of old release
* @param newMajorVersion Major version number of new release
* @param newMinorVersion Minor version number of new release
* @param allowPreReleaseUpgrade If true, set the system property
* 'derby.database.allowPreReleaseUpgrade' to indicate alpha/beta releases
* to support upgrade.
*/
public UpgradeTester(int oldMajorVersion, int oldMinorVersion,
int newMajorVersion, int newMinorVersion,
boolean allowPreReleaseUpgrade) {
this.oldMajorVersion = oldMajorVersion;
this.oldMinorVersion = oldMinorVersion;
this.newMajorVersion = newMajorVersion;
this.newMinorVersion = newMinorVersion;
this.allowPreReleaseUpgrade = allowPreReleaseUpgrade;
}
/**
* Set the location of jar files for old and new release
*/
private void setJarLocations() {
this.oldJarLoc = getOldJarLocation();
this.newJarLoc = getNewJarLocation();
}
/**
* Get the location of jars of old release. The location is specified
* in the property "derbyTesting.jar.path".
*
* @return location of jars of old release
*/
private String getOldJarLocation() {
String jarLocation = null;
String jarPath = System.getProperty("derbyTesting.jar.path");
if((jarPath != null) && (jarPath.compareTo("JAR_PATH_NOT_SET") == 0)) {
System.out.println("FAIL: Path to previous release jars not set");
System.out.println("Check if derbyTesting.jar.path property has been set in ant.properties file");
System.exit(-1);
}
String version = oldMajorVersion + "." + oldMinorVersion;
jarLocation = jarPath + File.separator + version;
return jarLocation;
}
/**
* Get the location of jar of new release. This is obtained from the
* classpath using findCodeBase method in jvm class.
*
* @return location of jars of new release
*/
private String getNewJarLocation() {
return jvm.findCodeBase(isJar);
}
/**
* This method creates two class loaders - one for old release and
* other for new release. It calls the appropriate create methods
* depending on what is used in the user's classpath - jars or
* classes folder
*
* @throws MalformedURLException
*/
private void createClassLoaders() throws MalformedURLException{
if(isJar[0]){
oldClassLoader = createClassLoader(oldJarLoc);
newClassLoader = createClassLoader(newJarLoc);
} else {
// classes folder in classpath
createLoadersUsingClasses();
}
}
/**
* Create a class loader using jars in the specified location. Add all jars
* specified in jarFiles and the testing jar.
*
* @param jarLoc Location of jar files
* @return class loader
* @throws MalformedURLException
*/
private URLClassLoader createClassLoader(String jarLoc)
throws MalformedURLException {
URL[] url = new URL[jarFiles.length + 1];
for(int i=0; i < jarFiles.length; i++) {
url[i] = new File(jarLoc + File.separator + jarFiles[i]).toURL();
}
// Add derbyTesting.jar. Added from newer release
url[jarFiles.length] = new File(newJarLoc + File.separator + testJar).toURL();
// Specify null for parent class loader to avoid mixing up
// jars specified in the system classpath
return new URLClassLoader(url, null);
}
/**
* Create old and new class loader. This method is used when classes folder
* is specified in the user's classpath.
*
* @throws MalformedURLException
*/
private void createLoadersUsingClasses()
throws MalformedURLException {
URL[] oldUrl = new URL[jarFiles.length + 1];
for(int i=0; i < jarFiles.length; i++) {
oldUrl[i] = new File(oldJarLoc + File.separator + jarFiles[i]).toURL();
}
// Use derby testing classes from newer release. To get the
// testing classes from newer release, we need to add the whole
// classes folder. So the oldClassLoader may contain extra classes
// from the newer version
oldUrl[jarFiles.length] = new File(newJarLoc).toURL();
oldClassLoader = new URLClassLoader(oldUrl, null);
URL[] newUrl = new URL[] {new File(newJarLoc).toURL()};
newClassLoader = new URLClassLoader(newUrl, null);
}
/**
* Set the context class loader
* @param classLoader class loader
*/
private static void setClassLoader(URLClassLoader classLoader) {
Thread.currentThread().setContextClassLoader(classLoader);
}
/**
* Set the context class loader to null
*/
private static void setNullClassLoader() {
Thread.currentThread().setContextClassLoader(null);
}
/**
* Runs the upgrade tests by calling runPhase for each phase.
* @throws Exception
*/
public void runUpgradeTests() throws Exception{
// Set the system property to allow alpha/beta release
// upgrade as specified
if(allowPreReleaseUpgrade)
System.setProperty("derby.database.allowPreReleaseUpgrade",
"true");
else
System.setProperty("derby.database.allowPreReleaseUpgrade",
"false");
setJarLocations();
createClassLoaders();
runPhase(OLD_RELEASE, PH_CREATE);
runPhase(NEW_RELEASE, PH_SOFT_UPGRADE);
runPhase(OLD_RELEASE, PH_POST_SOFT_UPGRADE);
runPhase(NEW_RELEASE, PH_HARD_UPGRADE);
runPhase(OLD_RELEASE, PH_POST_HARD_UPGRADE);
}
/**
* Runs each phase of upgrade test.
* 1. Chooses the classloader to use based on the release (old/new)
* 2. Gets a connection.
* 3. If connection is successful, checks the version using metadata,
* runs tests and shuts down the database.
*
* @param version Old or new version
* @param phase Upgrade test phase
* @throws Exception
*/
private void runPhase(int version, int phase)
throws Exception{
System.out.println("\n\nSTART - phase " + PHASES[phase]);
URLClassLoader classLoader = null;
switch(version) {
case OLD_RELEASE:
classLoader = oldClassLoader;
break;
case NEW_RELEASE:
classLoader = newClassLoader;
break;
default:
System.out.println("ERROR: Specified an invalid release type");
return;
}
boolean passed = true;
Connection conn = null;
setClassLoader(classLoader);
conn = getConnection(classLoader, phase);
if(conn != null) {
passed = caseVersionCheck(version, conn);
passed = caseReusableRecordIdSequenceNumber(conn, phase,
oldMajorVersion, oldMinorVersion) && passed;
passed = caseInitialize(conn, phase) && passed;
passed = caseProcedures(conn, phase, oldMajorVersion,
oldMinorVersion) && passed;
passed = caseTriggerVTI(conn, phase, oldMajorVersion,
oldMinorVersion) && passed;
passed = caseCompilationSchema(phase, conn) && passed;
passed = caseGrantRevoke(conn, phase, classLoader, false) && passed;
// Test grant/revoke feature with sql authorization
if(phase == PH_HARD_UPGRADE) {
setSQLAuthorization(conn, true);
conn = restartDatabase(classLoader);
passed = caseGrantRevoke(conn, phase, classLoader, true) && passed;
checkSysSchemas(conn);
checkRoutinePermissions(conn);
}
runMetadataTest(classLoader, conn);
conn.close();
shutdownDatabase(classLoader);
}
setNullClassLoader();
System.out.println("END - " + (passed ? "PASS" : "FAIL") +
" - phase " + PHASES[phase]);
}
/**
* Get a connection to the database using the specified class loader.
* The connection attributes depend on the phase of upgrade test.
*
* @param classLoader Class loader
* @param phase Upgrade test phase
* @return connection to the database
* @throws Exception
*/
private Connection getConnection(URLClassLoader classLoader,
int phase) throws Exception{
Connection conn = null;
Properties prop = new Properties();
prop.setProperty("databaseName", dbName);
switch(phase) {
case PH_CREATE:
prop.setProperty("connectionAttributes", "create=true");
break;
case PH_SOFT_UPGRADE:
case PH_POST_SOFT_UPGRADE:
case PH_POST_HARD_UPGRADE:
break;
case PH_HARD_UPGRADE:
prop.setProperty("connectionAttributes", "upgrade=true");
break;
default:
break;
}
try {
conn = getConnectionUsingDataSource(classLoader, prop);
} catch (SQLException sqle) {
if(phase != PH_POST_HARD_UPGRADE)
throw sqle;
// After hard upgrade, we should not be able to boot
// the database with older version. Possible SQLStates are
// XSLAP, if the new release is alpha/beta; XSLAN, otherwise.
if(sqle.getSQLState().equals("XJ040")) {
SQLException nextSqle = sqle.getNextException();
if(nextSqle.getSQLState().equals("XSLAP") ||
nextSqle.getSQLState().equals("XSLAN") )
System.out.println("Expected exception: Failed to start" +
" database with old version after hard upgrade");
}
}
return conn;
}
/**
* Get a connection using data source obtained from TestUtil class.
* Load TestUtil class using the specified class loader.
*
* @param classLoader
* @param prop
* @return
* @throws Exception
*/
private Connection getConnectionUsingDataSource(URLClassLoader classLoader, Properties prop) throws Exception{
Connection conn = null;
try {
Class testUtilClass = Class.forName("org.apache.derbyTesting.functionTests.util.TestUtil",
true, classLoader);
Object testUtilObject = testUtilClass.newInstance();
// Instead of calling TestUtil.getDataSourceConnection, call
// TestUtil.getDataSource and then call its getConnection method.
// This is because we do not want to lose the SQLException
// which we get when shutting down the database.
java.lang.reflect.Method method = testUtilClass.getMethod("getDataSource", new Class[] { prop.getClass() });
DataSource ds = (DataSource) method.invoke(testUtilClass, new Object[] { prop });
conn = ds.getConnection();
} catch(SQLException sqle) {
throw sqle;
} catch (Exception e) {
handleReflectionExceptions(e);
throw e;
}
return conn;
}
/**
* Verify the product version from metadata
* @param version Old or new version
* @param conn Connection
* @throws SQLException
*/
private boolean caseVersionCheck(int version, Connection conn)
throws SQLException{
boolean passed = false;
int actualMajorVersion;
int actualMinorVersion;
if (conn == null)
return false;
actualMajorVersion = conn.getMetaData().getDatabaseMajorVersion();
actualMinorVersion = conn.getMetaData().getDatabaseMinorVersion();
switch(version) {
case OLD_RELEASE:
passed = (actualMajorVersion == oldMajorVersion) && (actualMinorVersion == oldMinorVersion);
break;
case NEW_RELEASE:
passed = (actualMajorVersion == newMajorVersion) && (actualMinorVersion == newMinorVersion);
break;
default:
passed = false;
break;
}
System.out.println("complete caseVersionCheck - passed " + passed);
return passed;
}
/**
* Verify the compilation schema is nullable after upgrade
* @param phase upgrade test phase
* @param conn Connection
* @throws SQLException
*/
private boolean caseCompilationSchema(int phase, Connection conn)
throws SQLException
{
boolean passed = false;
DatabaseMetaData dmd;
ResultSet rs;
String isNullable;
if (conn == null)
return false;
dmd = conn.getMetaData();
switch (phase)
{
case PH_CREATE:
case PH_POST_SOFT_UPGRADE:
case PH_POST_HARD_UPGRADE:
passed = true;
break;
case PH_SOFT_UPGRADE:
case PH_HARD_UPGRADE:
rs = dmd.getColumns(null, "SYS", "SYSSTATEMENTS", "COMPILATIONSCHEMAID");
rs.next();
isNullable = rs.getString("IS_NULLABLE");
System.out.println ("SYS.SYSSTATEMENTS.COMPILATIONSCHEMAID IS_NULLABLE=" + isNullable);
passed = ("YES".equals(isNullable));
rs = dmd.getColumns(null, "SYS", "SYSVIEWS", "COMPILATIONSCHEMAID");
rs.next();
isNullable = rs.getString("IS_NULLABLE");
System.out.println("SYS.SYSVIEWS.COMPILATIONSCHEMAID IS_NULLABLE=" + isNullable);
passed = ("YES".equals(isNullable)) && passed;
break;
default:
passed = false;
break;
}
System.out.println("complete caseCompilationSchema - passed " + passed);
return passed;
}
/**
* In 10.2: We will write a ReusableRecordIdSequenceNumber in the
* header of a FileContaienr.
*
* Verify here that a 10.1 Database does not malfunction from this.
* 10.1 Databases should ignore the field.
*/
static boolean caseReusableRecordIdSequenceNumber(Connection conn,
int phase,
int dbMajor, int dbMinor)
throws SQLException
{
boolean runCompress = dbMajor>10 || dbMajor==10 && dbMinor>=1;
final boolean passed;
switch(phase) {
case PH_CREATE: {
Statement s = conn.createStatement();
s.execute("create table CT1(id int)");
s.execute("insert into CT1 values 1,2,3,4,5,6,7,8,9,10");
conn.commit();
passed = true;
break;
}
case PH_SOFT_UPGRADE:
if (runCompress) {
System.out.println("caseReusableRecordIdSequenceNumber - Running compress");
PreparedStatement ps = conn.prepareStatement
("call SYSCS_UTIL.SYSCS_INPLACE_COMPRESS_TABLE(?,?,?,?,?)");
ps.setString(1, "APP"); // schema
ps.setString(2, "CT1"); // table name
ps.setInt(3, 1); // purge
ps.setInt(4, 1); // defragment rows
ps.setInt(5, 1); // truncate end
ps.executeUpdate();
conn.commit();
}
passed = true;
break;
case PH_POST_SOFT_UPGRADE: {
// We are now back to i.e 10.1
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("select * from CT1");
while (rs.next()) {
rs.getInt(1);
}
s.execute("insert into CT1 values 11,12,13,14,15,16,17,18,19");
conn.commit();
passed = true;
break;
}
case PH_HARD_UPGRADE:
passed = true;
break;
default:
passed = false;
break;
}
System.out.println("complete caseReusableRecordIdSequenceNumber - passed " + passed);
return passed;
}
/**
* Perform some transactions
*
* @param conn Connection
* @param phase Upgrade test phase
* @return true if the test passes
* @throws SQLException
*/
private boolean caseInitialize(Connection conn, int phase)
throws SQLException {
boolean passed = true;
switch (phase) {
case PH_CREATE:
conn.createStatement().executeUpdate("CREATE TABLE PHASE" +
"(id INT NOT NULL, ok INT)");
conn.createStatement().executeUpdate("CREATE TABLE TABLE1" +
"(id INT NOT NULL PRIMARY KEY, name varchar(200))");
break;
case PH_SOFT_UPGRADE:
break;
case PH_POST_SOFT_UPGRADE:
break;
case PH_HARD_UPGRADE:
break;
default:
passed = false;
break;
}
PreparedStatement ps = conn.prepareStatement("INSERT INTO PHASE(id) " +
"VALUES (?)");
ps.setInt(1, phase);
ps.executeUpdate();
ps.close();
// perform some transactions
ps = conn.prepareStatement("INSERT INTO TABLE1 VALUES (?, ?)");
for (int i = 1; i < 20; i++)
{
ps.setInt(1, i + (phase * 100));
ps.setString(2, "p" + phase + "i" + i);
ps.executeUpdate();
}
ps.close();
ps = conn.prepareStatement("UPDATE TABLE1 set name = name || 'U' " +
" where id = ?");
for (int i = 1; i < 20; i+=3)
{
ps.setInt(1, i + (phase * 100));
ps.executeUpdate();
}
ps.close();
ps = conn.prepareStatement("DELETE FROM TABLE1 where id = ?");
for (int i = 1; i < 20; i+=4)
{
ps.setInt(1, i + (phase * 100));
ps.executeUpdate();
}
ps.close();
System.out.println("complete caseInitialize - passed " + passed);
return passed;
}
/**
* Procedures
* 10.1 - Check that a procedure with a signature can not be added if the
* on-disk database version is 10.0.
*
* @param conn Connection
* @param phase Upgrade test phase
* @param dbMajor Major version of old release
* @param dbMinor Minor version of old release
* @return true, if the test passes
* @throws SQLException
*/
private boolean caseProcedures(Connection conn, int phase,
int dbMajor, int dbMinor)
throws SQLException {
boolean signaturesAllowedInOldRelease =
dbMajor > 10 || (dbMajor == 10 && dbMinor >= 1);
boolean passed = true;
switch (phase) {
case PH_CREATE:
break;
case PH_SOFT_UPGRADE:
try {
conn.createStatement().execute("CREATE PROCEDURE GC() " +
"LANGUAGE JAVA PARAMETER STYLE JAVA EXTERNAL NAME" +
" 'java.lang.System.gc()'");
if (!signaturesAllowedInOldRelease)
{
System.out.println("FAIL : created procedure with " +
"signature");
passed = false;
}
} catch (SQLException sqle) {
if (signaturesAllowedInOldRelease
|| !"XCL47".equals(sqle.getSQLState())) {
System.out.println("FAIL " + sqle.getSQLState()
+ " -- " + sqle.getMessage());
passed = false;
}
}
break;
case PH_POST_SOFT_UPGRADE:
try {
conn.createStatement().execute("CALL GC()");
if (!signaturesAllowedInOldRelease)
System.out.println("FAIL : procedure was created" +
" in soft upgrade!");
} catch (SQLException sqle)
{
if (signaturesAllowedInOldRelease)
System.out.println("FAIL : procedure was created not in " +
"soft upgrade!" + sqle.getMessage());
}
break;
case PH_HARD_UPGRADE:
if (!signaturesAllowedInOldRelease)
conn.createStatement().execute("CREATE PROCEDURE GC() " +
"LANGUAGE JAVA PARAMETER STYLE JAVA EXTERNAL NAME " +
"'java.lang.System.gc()'");
conn.createStatement().execute("CALL GC()");
break;
default:
passed = false;
break;
}
System.out.println("complete caseProcedures - passed " + passed);
return passed;
}
/**
* Triger (internal) VTI
* 10.2 - Check that a statement trigger created in 10.0
* or 10.1 can be executed in 10.2 and that a statement
* trigger created in soft upgrade in 10.2 can be used
* in older releases.
*
* The VTI implementing statement triggers changed in
* 10.2 from implementations of ResultSet to implementations
* of PreparedStatement. See DERBY-438. The internal
* api for the re-written action statement remains the
* same. The re-compile of the trigger on version changes
* should automatically switch between the two implementations.
*
* @param conn Connection
* @param phase Upgrade test phase
* @param dbMajor Major version of old release
* @param dbMinor Minor version of old release
* @return true, if the test passes
* @throws SQLException
*/
private boolean caseTriggerVTI(Connection conn, int phase,
int dbMajor, int dbMinor)
throws SQLException {
boolean passed = true;
Statement s = conn.createStatement();
switch (phase) {
case PH_CREATE:
s.execute("CREATE TABLE D438.T438(a int, b varchar(20), c int)");
s.execute("INSERT INTO D438.T438 VALUES(1, 'DERBY-438', 2)");
s.execute("CREATE TABLE D438.T438_T1(a int, b varchar(20))");
s.execute("CREATE TABLE D438.T438_T2(a int, c int)");
s.execute(
"create trigger D438.T438_ROW_1 after UPDATE on D438.T438 " +
"referencing new as n old as o " +
"for each row mode db2sql "+
"insert into D438.T438_T1(a, b) values (n.a, n.b || '_ROW')");
s.executeUpdate(
"create trigger D438.T438_STMT_1 after UPDATE on D438.T438 " +
"referencing new_table as n " +
"for each statement mode db2sql "+
"insert into D438.T438_T1(a, b) select n.a, n.b || '_STMT' from n");
conn.commit();
showTriggerVTITables(phase, s);
break;
case PH_SOFT_UPGRADE:
s.execute(
"create trigger D438.T438_ROW_2 after UPDATE on D438.T438 " +
"referencing new as n old as o " +
"for each row mode db2sql "+
"insert into D438.T438_T2(a, c) values (n.a, n.c + 100)");
s.executeUpdate(
"create trigger D438.T438_STMT_2 after UPDATE on D438.T438 " +
"referencing new_table as n " +
"for each statement mode db2sql "+
"insert into D438.T438_T2(a, c) select n.a, n.c + 4000 from n");
conn.commit();
showTriggerVTITables(phase, s);
break;
case PH_POST_SOFT_UPGRADE:
showTriggerVTITables(phase, s);
break;
case PH_HARD_UPGRADE:
showTriggerVTITables(phase, s);
break;
default:
passed = false;
break;
}
s.close();
System.out.println("complete caseTriggerVTI - passed " + passed);
return passed;
}
/**
* Display the tables populated by the triggers.
*/
private void showTriggerVTITables(int phase, Statement s) throws SQLException
{
System.out.println("Trigger VTI Phase: " + PHASES[phase]);
s.executeUpdate("UPDATE D438.T438 set c = c + 1");
s.getConnection().commit();
System.out.println("D438.T438_T1");
ResultSet rs = s.executeQuery("SELECT a,b from D438.T438_T1 ORDER BY 2");
while (rs.next()) {
System.out.println(rs.getInt(1) + ", " + rs.getString(2));
}
rs.close();
System.out.println("D438.T438_T2");
rs = s.executeQuery("SELECT a,c from D438.T438_T2 ORDER BY 2");
while (rs.next()) {
System.out.println(rs.getInt(1) + ", " + rs.getString(2));
}
rs.close();
s.executeUpdate("DELETE FROM D438.T438_T1");
s.executeUpdate("DELETE FROM D438.T438_T2");
s.getConnection().commit();
}
/**
* Grant/revoke is a new feature in 10.2. Test that this feature is not
* supported by default after upgrade from versions earlier than 10.2.
* This feature will not be available in soft upgrade. For grant/revoke
* to be available after a full upgrade, the database property
* "derby.database.sqlAuthorization" has to be set to true after upgrade.
*
* @param conn Connection
* @param phase Upgrade test phase
* @param classLoader Class loader
* @param sqlAuthorization Value of SQL authorization for the database
* @return true, if the test passes
* @throws Exception
*/
private boolean caseGrantRevoke(Connection conn, int phase,
URLClassLoader classLoader,
boolean sqlAuthorization)
throws Exception {
System.out.println("Test grant/revoke, Phase: " + PHASES[phase] + "; "
+ "derby.database.sqlAuthorization=" + sqlAuthorization);
boolean passed = true;
boolean grantRevokeSupport = ((oldMajorVersion==10 && oldMinorVersion>=2) ||
(newMajorVersion==10 && newMinorVersion>=2))
&& sqlAuthorization;
Statement s = conn.createStatement();
switch (phase) {
case PH_CREATE:
s.execute("create table GR_TAB (id int)");
break;
case PH_SOFT_UPGRADE:
case PH_POST_SOFT_UPGRADE:
passed = testGrantRevokeSupport(s, phase, grantRevokeSupport);
break;
case PH_HARD_UPGRADE:
passed = testGrantRevokeSupport(s, phase, grantRevokeSupport);
break;
default:
passed = false;
break;
}
s.close();
System.out.println("complete caseGrantRevoke - passed " + passed);
return passed;
}
/**
* Test to check whether grant/revoke is supported in a specific upgrade
* test phase.
*
* @param s SQL statement
* @param phase Upgrade test phase
* @param grantRevokeSupport true if grant/revoke feature is supported in
* a specific version/upgrade phase.
* @return true, if the test passes.
*/
private boolean testGrantRevokeSupport(Statement s, int phase,
boolean grantRevokeSupport) {
boolean passed = true;
try {
s.execute("grant select on GR_TAB to some_user");
} catch(SQLException sqle) {
passed = checkGrantRevokeException(sqle, phase, grantRevokeSupport);
}
try {
s.execute("revoke select on GR_TAB from some_user");
} catch(SQLException sqle) {
passed = checkGrantRevokeException(sqle, phase, grantRevokeSupport);
}
return passed;
}
/**
* Checks if the exception is expected based on whether grant/revoke is
* supported or not.
*
* @param sqle SQL Exception
* @param phase Upgrade test phase
* @param grantRevokeSupported true if grant/revoke feature is supported in
* a specific version/upgrade phase.
* @return
*/
private boolean checkGrantRevokeException(SQLException sqle, int phase,
boolean grantRevokeSupported) {
boolean passed = true;
// If grant/revoke is supported, we should not get an exception
if(grantRevokeSupported) {
dumpSQLExceptions(sqle);
return false;
}
switch (phase) {
case PH_SOFT_UPGRADE:
// feature not available in soft upgrade
passed = isExpectedException(sqle, "XCL47");
break;
case PH_POST_SOFT_UPGRADE:
// syntax error in versions earlier than 10.2
passed = isExpectedException(sqle, "42X01");
break;
case PH_HARD_UPGRADE:
// not supported because SQL authorization not set
passed = isExpectedException(sqle, "42Z60");
break;
default:
passed = false;
}
return passed;
}
/**
* Set derby.database.sqlAuthorization as a database property.
*
* @param conn Connection
* @param sqlAuth Value of property
*/
private void setSQLAuthorization(Connection conn, boolean sqlAuth) {
String authorization = sqlAuth ? "true" : "false";
try {
Statement s = conn.createStatement();
s.execute("call SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(" +
"'derby.database.sqlAuthorization', '" + authorization +
"')");
} catch (SQLException sqle) {
dumpSQLExceptions(sqle);
}
}
/**
* This method lists the schema names and authorization ids in
* SYS.SCHEMAS table. This is to test that the owner of system schemas is
* changed from pseudo user "DBA" to the user invoking upgrade.
*
* @param conn
* @throws SQLException
*/
private void checkSysSchemas(Connection conn) throws SQLException{
System.out.println("Checking SYSSCHEMAS");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("select * from SYS.SYSSCHEMAS");
while(rs.next()) {
System.out.println("SCHEMANAME: " + rs.getString(2) + " , "
+ "AUTHORIZATIONID: " + rs.getString(3));
}
rs.close();
s.close();
}
/**
* This method checks that some system routines are granted public access
* after a full upgrade.
*
* @param conn
* @throws SQLException
*/
private void checkRoutinePermissions(Connection conn) throws SQLException{
System.out.println("Checking routine permissions in SYSROUTINEPERMS");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("select aliases.ALIAS, " +
"routinePerms.GRANTEE, routinePerms.GRANTOR from " +
"SYS.SYSROUTINEPERMS routinePerms, " +
"SYS.SYSALIASES aliases " +
"where routinePerms.ALIASID=aliases.ALIASID " +
"order by aliases.ALIAS");
while(rs.next()) {
System.out.println("ROUTINE NAME: " + rs.getString(1) + " , " +
"GRANTEE: " + rs.getString(2) + " , " +
"GRANTOR: " + rs.getString(3));
}
rs.close();
s.close();
}
/**
* Run metadata test
*
* @param classLoader Class loader to be used to load the test class
* @param conn Connection
* @throws Exception
*/
private void runMetadataTest(URLClassLoader classLoader, Connection conn)
throws Exception{
try {
Statement stmt = conn.createStatement();
Class metadataClass = Class.forName("org.apache.derbyTesting.functionTests.tests.jdbcapi.metadata",
true, classLoader);
Object metadataObject = metadataClass.newInstance();
java.lang.reflect.Field f1 = metadataClass.getField("con");
f1.set(metadataObject, conn);
java.lang.reflect.Field f2 = metadataClass.getField("s");
f2.set(metadataObject, stmt);
java.lang.reflect.Method method = metadataClass.getMethod("runTest",
null);
method.invoke(metadataObject, null);
} catch(SQLException sqle) {
throw sqle;
} catch (Exception e) {
handleReflectionExceptions(e);
throw e;
}
}
/**
* Shutdown the database
* @param classLoader
* @throws Exception
*/
private void shutdownDatabase(URLClassLoader classLoader)
throws Exception {
Properties prop = new Properties();
prop.setProperty("databaseName", dbName);
prop.setProperty("connectionAttributes", "shutdown=true");
try {
getConnectionUsingDataSource(classLoader, prop);
} catch (SQLException sqle) {
if(sqle.getSQLState().equals("08006")) {
System.out.println("Expected exception during shutdown: "
+ sqle.getMessage());
} else
throw sqle;
}
}
/**
* Start the database
*
* @param classLoader
* @return
* @throws Exception
*/
private Connection startDatabase(URLClassLoader classLoader)
throws Exception {
Connection conn = null;
Properties prop = new Properties();
prop.setProperty("databaseName", dbName);
try {
conn = getConnectionUsingDataSource(classLoader, prop);
} catch (SQLException sqle) {
dumpSQLExceptions(sqle);
}
return conn;
}
/**
* Shutdown and reconnect to the database
* @param classLoader
* @return
* @throws Exception
*/
private Connection restartDatabase(URLClassLoader classLoader)
throws Exception {
shutdownDatabase(classLoader);
return startDatabase(classLoader);
}
/**
* Display the sql exception
* @param sqle SQLException
*/
public static void dumpSQLExceptions(SQLException sqle) {
do
{
System.out.println("SQLSTATE("+sqle.getSQLState()+"): "
+ sqle.getMessage());
sqle = sqle.getNextException();
} while (sqle != null);
}
/**
* Check if the exception is expected.
*
* @param sqle SQL Exception
* @param expectedSQLState Expected SQLState
* @return true, if SQLState of the exception is same as expected SQLState
*/
private boolean isExpectedException(SQLException sqle, String expectedSQLState) {
boolean passed = true;
if(!expectedSQLState.equals(sqle.getSQLState())) {
passed = false;
System.out.println("Fail - Unexpected exception:");
dumpSQLExceptions(sqle);
}
return passed;
}
/**
* Prints the possible causes for exceptions thrown when trying to
* load classes and invoke methods.
*
* @param e Exception
*/
private void handleReflectionExceptions(Exception e) {
System.out.println("FAIL - Unexpected exception - " + e.getMessage());
System.out.println("Possible Reason - Test could not find the " +
"location of jar files. Please check if you are running " +
"with jar files in the classpath. The test does not run with " +
"classes folder in the classpath. Also, check that old " +
"jars are checked out from the repository or specified in " +
"derbyTesting.jar.path property in ant.properties");
e.printStackTrace();
}
}
| DERBY-1925 : (Add re-encrytion of database test cases to the upgrade test.)
Merged fix (r452682) from 10.2 branch to trunk.
This patch adds test cases to the upgrade test to test encryption of an
un-encrypted database and re-encryption of encrypted database.
git-svn-id: 2c06e9c5008124d912b69f0b82df29d4867c0ce2@466279 13f79535-47bb-0310-9956-ffa450edef68
| java/testing/org/apache/derbyTesting/functionTests/tests/upgradeTests/UpgradeTester.java | DERBY-1925 : (Add re-encrytion of database test cases to the upgrade test.) |
|
Java | apache-2.0 | 1e24c0218fab346a85121e634acf06f1eee9f4f0 | 0 | apache/solr,apache/solr,apache/solr,apache/solr,apache/solr | package org.apache.solr.schema;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import com.google.common.base.Throwables;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.spatial4j.core.context.SpatialContext;
import com.spatial4j.core.context.SpatialContextFactory;
import com.spatial4j.core.distance.DistanceUtils;
import com.spatial4j.core.io.LegacyShapeReadWriterFormat;
import com.spatial4j.core.shape.Point;
import com.spatial4j.core.shape.Rectangle;
import com.spatial4j.core.shape.Shape;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.index.StorableField;
import org.apache.lucene.queries.function.FunctionQuery;
import org.apache.lucene.queries.function.ValueSource;
import org.apache.lucene.search.Filter;
import org.apache.lucene.search.FilteredQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.SortField;
import org.apache.lucene.spatial.SpatialStrategy;
import org.apache.lucene.spatial.query.SpatialArgs;
import org.apache.lucene.spatial.query.SpatialArgsParser;
import org.apache.lucene.spatial.query.SpatialOperation;
import org.apache.lucene.uninverting.UninvertingReader.Type;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.response.TextResponseWriter;
import org.apache.solr.search.QParser;
import org.apache.solr.search.SpatialOptions;
import org.apache.solr.util.MapListener;
import org.apache.solr.util.SpatialUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
/**
* Abstract base class for Solr FieldTypes based on a Lucene 4 {@link SpatialStrategy}.
*
* @lucene.experimental
*/
public abstract class AbstractSpatialFieldType<T extends SpatialStrategy> extends FieldType implements SpatialQueryable {
/** A local-param with one of "none" (default), "distance", or "recipDistance". */
public static final String SCORE_PARAM = "score";
/** A local-param boolean that can be set to false to only return the
* FunctionQuery (score), and thus not do filtering.
*/
public static final String FILTER_PARAM = "filter";
protected final Logger log = LoggerFactory.getLogger( getClass() );
protected SpatialContext ctx;
protected SpatialArgsParser argsParser;
private final Cache<String, T> fieldStrategyCache = CacheBuilder.newBuilder().build();
@Override
protected void init(IndexSchema schema, Map<String, String> args) {
super.init(schema, args);
String units = args.remove("units");
if (!"degrees".equals(units))
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
"Must specify units=\"degrees\" on field types with class "+getClass().getSimpleName());
//replace legacy rect format with ENVELOPE
String wbStr = args.get("worldBounds");
if (wbStr != null && !wbStr.toUpperCase(Locale.ROOT).startsWith("ENVELOPE")) {
log.warn("Using old worldBounds format? Should use ENVELOPE(xMin, xMax, yMax, yMin).");
String[] parts = wbStr.split(" ");//"xMin yMin xMax yMax"
if (parts.length == 4) {
args.put("worldBounds",
"ENVELOPE(" + parts[0] + ", " + parts[2] + ", " + parts[3] + ", " + parts[1] + ")");
} //else likely eventual exception
}
//Solr expects us to remove the parameters we've used.
MapListener<String, String> argsWrap = new MapListener<>(args);
ctx = SpatialContextFactory.makeSpatialContext(argsWrap, schema.getResourceLoader().getClassLoader());
args.keySet().removeAll(argsWrap.getSeenKeys());
argsParser = newSpatialArgsParser();
}
protected SpatialArgsParser newSpatialArgsParser() {
return new SpatialArgsParser() {
@Override
protected Shape parseShape(String str, SpatialContext ctx) throws ParseException {
return AbstractSpatialFieldType.this.parseShape(str);
}
};
}
//--------------------------------------------------------------
// Indexing
//--------------------------------------------------------------
@Override
public final Field createField(SchemaField field, Object val, float boost) {
throw new IllegalStateException("instead call createFields() because isPolyField() is true");
}
@Override
public Type getUninversionType(SchemaField sf) {
return null;
}
@Override
public List<StorableField> createFields(SchemaField field, Object val, float boost) {
String shapeStr = null;
Shape shape = null;
if (val instanceof Shape) {
shape = ((Shape) val);
} else {
shapeStr = val.toString();
shape = parseShape(shapeStr);
}
if (shape == null) {
log.debug("Field {}: null shape for input: {}", field, val);
return Collections.emptyList();
}
List<StorableField> result = new ArrayList<>();
if (field.indexed()) {
T strategy = getStrategy(field.getName());
result.addAll(Arrays.asList(strategy.createIndexableFields(shape)));
}
if (field.stored()) {
if (shapeStr == null)
shapeStr = shapeToString(shape);
result.add(new StoredField(field.getName(), shapeStr));
}
return result;
}
protected Shape parseShape(String str) {
if (str.length() == 0)
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "empty string shape");
//In Solr trunk we only support "lat, lon" (or x y) as an additional format; in v4.0 we do the
// weird Circle & Rect formats too (Spatial4j LegacyShapeReadWriterFormat).
try {
Shape shape = LegacyShapeReadWriterFormat.readShapeOrNull(str, ctx);
if (shape != null)
return shape;
return ctx.readShapeFromWkt(str);
} catch (Exception e) {
String message = e.getMessage();
if (!message.contains(str))
message = "Couldn't parse shape '" + str + "' because: " + message;
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, message, e);
}
}
/**
* Returns a String version of a shape to be used for the stored value. This method in Solr is only called if for some
* reason a Shape object is passed to the field type (perhaps via a custom UpdateRequestProcessor),
* *and* the field is marked as stored. <em>The default implementation throws an exception.</em>
* <p/>
* Spatial4j 0.4 is probably the last release to support SpatialContext.toString(shape) but it's deprecated with no
* planned replacement. Shapes do have a toString() method but they are generally internal/diagnostic and not
* standard WKT.
* The solution is subclassing and calling ctx.toString(shape) or directly using LegacyShapeReadWriterFormat or
* passing in some sort of custom wrapped shape that holds a reference to a String or can generate it.
*/
protected String shapeToString(Shape shape) {
// return ctx.toString(shape);
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
"Getting a String from a Shape is no longer possible. See javadocs for commentary.");
}
/** Called from {@link #getStrategy(String)} upon first use by fieldName. } */
protected abstract T newSpatialStrategy(String fieldName);
@Override
public final boolean isPolyField() {
return true;
}
//--------------------------------------------------------------
// Query Support
//--------------------------------------------------------------
/**
* Implemented for compatibility with geofilt & bbox query parsers:
* {@link SpatialQueryable}.
*/
@Override
public Query createSpatialQuery(QParser parser, SpatialOptions options) {
Point pt = SpatialUtils.parsePointSolrException(options.pointStr, ctx);
double distDeg = DistanceUtils.dist2Degrees(options.distance, options.radius);
Shape shape = ctx.makeCircle(pt, distDeg);
if (options.bbox)
shape = shape.getBoundingBox();
SpatialArgs spatialArgs = new SpatialArgs(SpatialOperation.Intersects, shape);
return getQueryFromSpatialArgs(parser, options.field, spatialArgs);
}
@Override
public Query getRangeQuery(QParser parser, SchemaField field, String part1, String part2, boolean minInclusive, boolean maxInclusive) {
if (!minInclusive || !maxInclusive)
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Both sides of spatial range query must be inclusive: " + field.getName());
Point p1 = SpatialUtils.parsePointSolrException(part1, ctx);
Point p2 = SpatialUtils.parsePointSolrException(part2, ctx);
Rectangle bbox = ctx.makeRectangle(p1, p2);
SpatialArgs spatialArgs = new SpatialArgs(SpatialOperation.Intersects, bbox);
return getQueryFromSpatialArgs(parser, field, spatialArgs);//won't score by default
}
@Override
public ValueSource getValueSource(SchemaField field, QParser parser) {
//This is different from Solr 3 LatLonType's approach which uses the MultiValueSource concept to directly expose
// the x & y pair of FieldCache value sources.
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
"A ValueSource isn't directly available from this field. Instead try a query using the distance as the score.");
}
@Override
public Query getFieldQuery(QParser parser, SchemaField field, String externalVal) {
return getQueryFromSpatialArgs(parser, field, parseSpatialArgs(parser, externalVal));
}
protected SpatialArgs parseSpatialArgs(QParser parser, String externalVal) {
try {
return argsParser.parse(externalVal, ctx);
} catch (SolrException e) {
throw e;
} catch (Exception e) {
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e);
}
}
protected Query getQueryFromSpatialArgs(QParser parser, SchemaField field, SpatialArgs spatialArgs) {
T strategy = getStrategy(field.getName());
SolrParams localParams = parser.getLocalParams();
String score = (localParams == null ? null : localParams.get(SCORE_PARAM));
if (score == null || "none".equals(score) || "".equals(score)) {
//FYI Solr FieldType doesn't have a getFilter(). We'll always grab
// getQuery() but it's possible a strategy has a more efficient getFilter
// that could be wrapped -- no way to know.
//See SOLR-2883 needScore
return strategy.makeQuery(spatialArgs); //ConstantScoreQuery
}
//We get the valueSource for the score then the filter and combine them.
ValueSource valueSource;
if ("distance".equals(score)) {
double multiplier = 1.0;//TODO support units=kilometers
valueSource = strategy.makeDistanceValueSource(spatialArgs.getShape().getCenter(), multiplier);
} else if ("recipDistance".equals(score)) {
valueSource = strategy.makeRecipDistanceValueSource(spatialArgs.getShape());
} else {
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "'score' local-param must be one of 'none', 'distance', or 'recipDistance'");
}
FunctionQuery functionQuery = new FunctionQuery(valueSource);
if (localParams != null && !localParams.getBool(FILTER_PARAM, true))
return functionQuery;
Filter filter = strategy.makeFilter(spatialArgs);
return new FilteredQuery(functionQuery, filter);
}
/**
* Gets the cached strategy for this field, creating it if necessary
* via {@link #newSpatialStrategy(String)}.
* @param fieldName Mandatory reference to the field name
* @return Non-null.
*/
public T getStrategy(final String fieldName) {
try {
return fieldStrategyCache.get(fieldName, new Callable<T>() {
@Override
public T call() throws Exception {
return newSpatialStrategy(fieldName);
}
});
} catch (ExecutionException e) {
throw Throwables.propagate(e.getCause());
}
}
@Override
public void write(TextResponseWriter writer, String name, StorableField f) throws IOException {
writer.writeStr(name, f.stringValue(), true);
}
@Override
public SortField getSortField(SchemaField field, boolean top) {
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Sorting not supported on SpatialField: " + field.getName()+
", instead try sorting by query.");
}
}
| solr/core/src/java/org/apache/solr/schema/AbstractSpatialFieldType.java | package org.apache.solr.schema;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import com.google.common.base.Throwables;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.spatial4j.core.context.SpatialContext;
import com.spatial4j.core.context.SpatialContextFactory;
import com.spatial4j.core.distance.DistanceUtils;
import com.spatial4j.core.io.LegacyShapeReadWriterFormat;
import com.spatial4j.core.shape.Point;
import com.spatial4j.core.shape.Rectangle;
import com.spatial4j.core.shape.Shape;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.index.StorableField;
import org.apache.lucene.queries.function.FunctionQuery;
import org.apache.lucene.queries.function.ValueSource;
import org.apache.lucene.search.Filter;
import org.apache.lucene.search.FilteredQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.SortField;
import org.apache.lucene.spatial.SpatialStrategy;
import org.apache.lucene.spatial.query.SpatialArgs;
import org.apache.lucene.spatial.query.SpatialArgsParser;
import org.apache.lucene.spatial.query.SpatialOperation;
import org.apache.lucene.uninverting.UninvertingReader.Type;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.response.TextResponseWriter;
import org.apache.solr.search.QParser;
import org.apache.solr.search.SpatialOptions;
import org.apache.solr.util.MapListener;
import org.apache.solr.util.SpatialUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
/**
* Abstract base class for Solr FieldTypes based on a Lucene 4 {@link SpatialStrategy}.
*
* @lucene.experimental
*/
public abstract class AbstractSpatialFieldType<T extends SpatialStrategy> extends FieldType implements SpatialQueryable {
/** A local-param with one of "none" (default), "distance", or "recipDistance". */
public static final String SCORE_PARAM = "score";
/** A local-param boolean that can be set to false to only return the
* FunctionQuery (score), and thus not do filtering.
*/
public static final String FILTER_PARAM = "filter";
protected final Logger log = LoggerFactory.getLogger( getClass() );
protected SpatialContext ctx;
protected SpatialArgsParser argsParser;
private final Cache<String, T> fieldStrategyCache = CacheBuilder.newBuilder().build();
@Override
protected void init(IndexSchema schema, Map<String, String> args) {
super.init(schema, args);
String units = args.remove("units");
if (!"degrees".equals(units))
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
"Must specify units=\"degrees\" on field types with class "+getClass().getSimpleName());
//replace legacy rect format with ENVELOPE
String wbStr = args.get("worldBounds");
if (wbStr != null && !wbStr.toUpperCase(Locale.ROOT).startsWith("ENVELOPE")) {
log.warn("Using old worldBounds format? Should use ENVELOPE(xMin, xMax, yMax, yMin).");
String[] parts = wbStr.split(" ");//"xMin yMin xMax yMax"
if (parts.length == 4) {
args.put("worldBounds",
"ENVELOPE(" + parts[0] + ", " + parts[2] + ", " + parts[3] + ", " + parts[1] + ")");
} //else likely eventual exception
}
//Solr expects us to remove the parameters we've used.
MapListener<String, String> argsWrap = new MapListener<>(args);
ctx = SpatialContextFactory.makeSpatialContext(argsWrap, schema.getResourceLoader().getClassLoader());
args.keySet().removeAll(argsWrap.getSeenKeys());
argsParser = newSpatialArgsParser();
}
protected SpatialArgsParser newSpatialArgsParser() {
return new SpatialArgsParser() {
@Override
protected Shape parseShape(String str, SpatialContext ctx) throws ParseException {
return AbstractSpatialFieldType.this.parseShape(str);
}
};
}
//--------------------------------------------------------------
// Indexing
//--------------------------------------------------------------
@Override
public final Field createField(SchemaField field, Object val, float boost) {
throw new IllegalStateException("instead call createFields() because isPolyField() is true");
}
@Override
public Type getUninversionType(SchemaField sf) {
return null;
}
@Override
public List<StorableField> createFields(SchemaField field, Object val, float boost) {
String shapeStr = null;
Shape shape = null;
if (val instanceof Shape) {
shape = ((Shape) val);
} else {
shapeStr = val.toString();
shape = parseShape(shapeStr);
}
if (shape == null) {
log.debug("Field {}: null shape for input: {}", field, val);
return Collections.emptyList();
}
List<StorableField> result = new ArrayList<>();
if (field.indexed()) {
T strategy = getStrategy(field.getName());
result.addAll(Arrays.asList(strategy.createIndexableFields(shape)));
}
if (field.stored()) {
if (shapeStr == null)
shapeStr = shapeToString(shape);
result.add(new StoredField(field.getName(), shapeStr));
}
return result;
}
protected Shape parseShape(String str) {
if (str.length() == 0)
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "empty string shape");
//In Solr trunk we only support "lat, lon" (or x y) as an additional format; in v4.0 we do the
// weird Circle & Rect formats too (Spatial4j LegacyShapeReadWriterFormat).
try {
Shape shape = LegacyShapeReadWriterFormat.readShapeOrNull(str, ctx);
if (shape != null)
return shape;
return ctx.readShapeFromWkt(str);
} catch (Exception e) {
String message = e.getMessage();
if (!message.contains(str))
message = "Couldn't parse shape '" + str + "' because: " + message;
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, message, e);
}
}
/**
* Returns a String version of a shape to be used for the stored value. This method in Solr is only called if for some
* reason a Shape object is passed to the field type (perhaps via a custom UpdateRequestProcessor),
* *and* the field is marked as stored. <em>The default implementation throws an exception.</em>
* <p/>
* Spatial4j 0.4 is probably the last release to support SpatialContext.toString(shape) but it's deprecated with no
* planned replacement. Shapes do have a toString() method but they are generally internal/diagnostic and not
* standard WKT.
* The solution is subclassing and calling ctx.toString(shape) or directly using LegacyShapeReadWriterFormat or
* passing in some sort of custom wrapped shape that holds a reference to a String or can generate it.
*/
protected String shapeToString(Shape shape) {
// return ctx.toString(shape);
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
"Getting a String from a Shape is no longer possible. See javadocs for commentary.");
}
/** Called from {@link #getStrategy(String)} upon first use by fieldName. } */
protected abstract T newSpatialStrategy(String fieldName);
@Override
public final boolean isPolyField() {
return true;
}
//--------------------------------------------------------------
// Query Support
//--------------------------------------------------------------
/**
* Implemented for compatibility with geofilt & bbox query parsers:
* {@link SpatialQueryable}.
*/
@Override
public Query createSpatialQuery(QParser parser, SpatialOptions options) {
Point pt = SpatialUtils.parsePointSolrException(options.pointStr, ctx);
double distDeg = DistanceUtils.dist2Degrees(options.distance, options.radius);
Shape shape = ctx.makeCircle(pt, distDeg);
if (options.bbox)
shape = shape.getBoundingBox();
SpatialArgs spatialArgs = new SpatialArgs(SpatialOperation.Intersects, shape);
return getQueryFromSpatialArgs(parser, options.field, spatialArgs);
}
@Override
public Query getRangeQuery(QParser parser, SchemaField field, String part1, String part2, boolean minInclusive, boolean maxInclusive) {
if (!minInclusive || !maxInclusive)
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Both sides of spatial range query must be inclusive: " + field.getName());
Point p1 = SpatialUtils.parsePointSolrException(part1, ctx);
Point p2 = SpatialUtils.parsePointSolrException(part2, ctx);
Rectangle bbox = ctx.makeRectangle(p1, p2);
SpatialArgs spatialArgs = new SpatialArgs(SpatialOperation.Intersects, bbox);
return getQueryFromSpatialArgs(parser, field, spatialArgs);//won't score by default
}
@Override
public ValueSource getValueSource(SchemaField field, QParser parser) {
//This is different from Solr 3 LatLonType's approach which uses the MultiValueSource concept to directly expose
// the x & y pair of FieldCache value sources.
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
"A ValueSource isn't directly available from this field. Instead try a query using the distance as the score.");
}
@Override
public Query getFieldQuery(QParser parser, SchemaField field, String externalVal) {
return getQueryFromSpatialArgs(parser, field, parseSpatialArgs(externalVal));
}
protected SpatialArgs parseSpatialArgs(String externalVal) {
try {
return argsParser.parse(externalVal, ctx);
} catch (SolrException e) {
throw e;
} catch (Exception e) {
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e);
}
}
private Query getQueryFromSpatialArgs(QParser parser, SchemaField field, SpatialArgs spatialArgs) {
T strategy = getStrategy(field.getName());
SolrParams localParams = parser.getLocalParams();
String score = (localParams == null ? null : localParams.get(SCORE_PARAM));
if (score == null || "none".equals(score) || "".equals(score)) {
//FYI Solr FieldType doesn't have a getFilter(). We'll always grab
// getQuery() but it's possible a strategy has a more efficient getFilter
// that could be wrapped -- no way to know.
//See SOLR-2883 needScore
return strategy.makeQuery(spatialArgs); //ConstantScoreQuery
}
//We get the valueSource for the score then the filter and combine them.
ValueSource valueSource;
if ("distance".equals(score)) {
double multiplier = 1.0;//TODO support units=kilometers
valueSource = strategy.makeDistanceValueSource(spatialArgs.getShape().getCenter(), multiplier);
} else if ("recipDistance".equals(score)) {
valueSource = strategy.makeRecipDistanceValueSource(spatialArgs.getShape());
} else {
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "'score' local-param must be one of 'none', 'distance', or 'recipDistance'");
}
FunctionQuery functionQuery = new FunctionQuery(valueSource);
if (localParams != null && !localParams.getBool(FILTER_PARAM, true))
return functionQuery;
Filter filter = strategy.makeFilter(spatialArgs);
return new FilteredQuery(functionQuery, filter);
}
/**
* Gets the cached strategy for this field, creating it if necessary
* via {@link #newSpatialStrategy(String)}.
* @param fieldName Mandatory reference to the field name
* @return Non-null.
*/
public T getStrategy(final String fieldName) {
try {
return fieldStrategyCache.get(fieldName, new Callable<T>() {
@Override
public T call() throws Exception {
return newSpatialStrategy(fieldName);
}
});
} catch (ExecutionException e) {
throw Throwables.propagate(e.getCause());
}
}
@Override
public void write(TextResponseWriter writer, String name, StorableField f) throws IOException {
writer.writeStr(name, f.stringValue(), true);
}
@Override
public SortField getSortField(SchemaField field, boolean top) {
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Sorting not supported on SpatialField: " + field.getName()+
", instead try sorting by query.");
}
}
| SOLR-6103: Add QParser arg to AbstractSpatialFieldType.parseSpatialArgs(). Make getQueryFromSpatialArgs protected no private.
git-svn-id: 308d55f399f3bd9aa0560a10e81a003040006c48@1600556 13f79535-47bb-0310-9956-ffa450edef68
| solr/core/src/java/org/apache/solr/schema/AbstractSpatialFieldType.java | SOLR-6103: Add QParser arg to AbstractSpatialFieldType.parseSpatialArgs(). Make getQueryFromSpatialArgs protected no private. |
|
Java | apache-2.0 | 3d0cdd2601b101eb5c2a07622c186d7abfeb9f6e | 0 | davidmoten/state-machine,davidmoten/state-machine | package com.github.davidmoten.fsm.graph;
import static org.apache.commons.lang3.StringEscapeUtils.escapeXml10;
import java.io.PrintWriter;
public class GraphmlWriter {
public void printGraphml(PrintWriter out, Graph graph) {
out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<graphml xmlns=\"http://graphml.graphdrawing.org/xmlns\" \n"
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
+ " xmlns:y=\"http://www.yworks.com/xml/graphml\"\n"
+ " xsi:schemaLocation=\"http://graphml.graphdrawing.org/xmlns\n"
+ " http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd\">");
out.println(" <key for=\"node\" id=\"d1\" yfiles.type=\"nodegraphics\"/>");
out.println(" <key for=\"edge\" id=\"d2\" attr.name=\"Event\" attr.type=\"string\"/>");
out.println(" <key for=\"edge\" id=\"d3\" yfiles.type=\"edgegraphics\"/>");
out.println(" <graph id=\"G\" edgedefault=\"directed\">");
for (GraphNode node : graph.getNodes()) {
printNode(out, node.name(), node.descriptionHtml());
}
for (GraphEdge edge : graph.getEdges()) {
printEdge(out, edge.getFrom().name(), edge.getTo().name(), edge.label());
}
out.println(" </graph>");
out.println("</graphml>");
out.close();
}
private static void printEdge(PrintWriter out, String from, String to, String label) {
out.println(" <edge source=\"" + escapeXml10(from) + "\" target=\"" + escapeXml10(to)
+ "\">");
out.println(" <data key=\"d2\">" + label + "</data>");
out.println("<data key=\"d3\">\n" + " <y:PolyLineEdge>\n"
+ " <y:Path sx=\"0.0\" sy=\"75.0\" tx=\"-75.0\" ty=\"-0.0\">\n"
+ " <y:Point x=\"75.0\" y=\"250.0\"/>\n" + " </y:Path>\n"
+ " <y:LineStyle color=\"#000000\" type=\"line\" width=\"1.0\"/>\n"
+ " <y:Arrows source=\"none\" target=\"standard\"/>\n"
+ " <y:EdgeLabel alignment=\"center\" configuration=\"AutoFlippingLabel\" distance=\"2.0\" fontFamily=\"Dialog\" fontSize=\"12\" fontStyle=\"plain\" hasBackgroundColor=\"false\" hasLineColor=\"false\" height=\"17.96875\" modelName=\"custom\" preferredPlacement=\"anywhere\" ratio=\"0.5\" textColor=\"#000000\" visible=\"true\" width=\"68.822265625\" x=\"-64.4111328125\" y=\"48.0078125\">"
+ label + "<y:LabelModel>\n"
+ " <y:SmartEdgeLabelModel autoRotationEnabled=\"false\" defaultAngle=\"0.0\" defaultDistance=\"10.0\"/>\n"
+ " </y:LabelModel>\n" + " <y:ModelParameter>\n"
+ " <y:SmartEdgeLabelModelParameter angle=\"0.0\" distance=\"30.0\" distanceToCenter=\"true\" position=\"right\" ratio=\"0.5\" segment=\"0\"/>\n"
+ " </y:ModelParameter>\n"
+ " <y:PreferredPlacementDescriptor angle=\"0.0\" angleOffsetOnRightSide=\"0\" angleReference=\"absolute\" angleRotationOnRightSide=\"co\" distance=\"-1.0\" frozen=\"true\" placement=\"anywhere\" side=\"anywhere\" sideReference=\"relative_to_edge_flow\"/>\n"
+ " </y:EdgeLabel>\n" + " <y:BendStyle smoothed=\"false\"/>\n"
+ " </y:PolyLineEdge>\n" + " </data>");
out.println(" </edge>");
}
private static void printNode(PrintWriter out, String nodeName, String descriptionHtml) {
String fillColor = "#F3F2C0";
out.println(" <node id=\"" + escapeXml10(nodeName) + "\">");
out.println(" <data key=\"d1\">");
out.println(" <y:ShapeNode>");
out.println(
" <y:Geometry height=\"150.0\" width=\"250.0\" x=\"77.0\" y=\"113.0\"/>\n"
+ " <y:Fill color=\"" + fillColor + "\" transparent=\"false\"/>\n"
+ " <y:BorderStyle color=\"#000000\" type=\"line\" width=\"1.0\"/>");
out.println(" <y:NodeLabel>"
+ escapeXml10("<html><p><b>" + nodeName + "</b></p>"
+ "<div style=\"font-size:smaller;\">" + descriptionHtml + "</div></html>")
+ "</y:NodeLabel>");
out.println(" </y:ShapeNode>");
out.println(" </data>");
out.println(" </node>");
}
}
| state-machine-generator/src/main/java/com/github/davidmoten/fsm/graph/GraphmlWriter.java | package com.github.davidmoten.fsm.graph;
import static org.apache.commons.lang3.StringEscapeUtils.escapeXml10;
import java.io.PrintWriter;
public class GraphmlWriter {
public void printGraphml(PrintWriter out, Graph graph) {
out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<graphml xmlns=\"http://graphml.graphdrawing.org/xmlns\" \n"
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
+ " xmlns:y=\"http://www.yworks.com/xml/graphml\"\n"
+ " xsi:schemaLocation=\"http://graphml.graphdrawing.org/xmlns\n"
+ " http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd\">");
out.println(" <key for=\"node\" id=\"d1\" yfiles.type=\"nodegraphics\"/>");
out.println(" <key for=\"edge\" id=\"d2\" attr.name=\"Event\" attr.type=\"string\"/>");
out.println(" <key for=\"edge\" id=\"d3\" yfiles.type=\"edgegraphics\"/>");
out.println(" <graph id=\"G\" edgedefault=\"directed\">");
for (GraphNode node : graph.getNodes()) {
printNode(out, node.name(), node.descriptionHtml());
}
for (GraphEdge edge : graph.getEdges()) {
printEdge(out, edge.getFrom().name(), edge.getTo().name(), edge.label());
}
out.println(" </graph>");
out.println("</graphml>");
out.close();
}
private static void printEdge(PrintWriter out, String from, String to, String label) {
out.println(" <edge source=\"" + escapeXml10(from) + "\" target=\"" + escapeXml10(to)
+ "\">");
out.println(" <data key=\"d2\">" + label + "</data>");
out.println("<data key=\"d3\">\n" + " <y:PolyLineEdge>\n"
+ " <y:Path sx=\"0.0\" sy=\"75.0\" tx=\"-75.0\" ty=\"-0.0\">\n"
+ " <y:Point x=\"75.0\" y=\"250.0\"/>\n" + " </y:Path>\n"
+ " <y:LineStyle color=\"#000000\" type=\"line\" width=\"1.0\"/>\n"
+ " <y:Arrows source=\"none\" target=\"standard\"/>\n"
+ " <y:EdgeLabel alignment=\"center\" configuration=\"AutoFlippingLabel\" distance=\"2.0\" fontFamily=\"Dialog\" fontSize=\"12\" fontStyle=\"plain\" hasBackgroundColor=\"false\" hasLineColor=\"false\" height=\"17.96875\" modelName=\"custom\" preferredPlacement=\"anywhere\" ratio=\"0.5\" textColor=\"#000000\" visible=\"true\" width=\"68.822265625\" x=\"-64.4111328125\" y=\"48.0078125\">"
+ label + "<y:LabelModel>\n"
+ " <y:SmartEdgeLabelModel autoRotationEnabled=\"false\" defaultAngle=\"0.0\" defaultDistance=\"10.0\"/>\n"
+ " </y:LabelModel>\n" + " <y:ModelParameter>\n"
+ " <y:SmartEdgeLabelModelParameter angle=\"0.0\" distance=\"30.0\" distanceToCenter=\"true\" position=\"right\" ratio=\"0.5\" segment=\"0\"/>\n"
+ " </y:ModelParameter>\n"
+ " <y:PreferredPlacementDescriptor angle=\"0.0\" angleOffsetOnRightSide=\"0\" angleReference=\"absolute\" angleRotationOnRightSide=\"co\" distance=\"-1.0\" frozen=\"true\" placement=\"anywhere\" side=\"anywhere\" sideReference=\"relative_to_edge_flow\"/>\n"
+ " </y:EdgeLabel>\n" + " <y:BendStyle smoothed=\"false\"/>\n"
+ " </y:PolyLineEdge>\n" + " </data>");
out.println(" </edge>");
}
private static void printNode(PrintWriter out, String nodeName, String descriptionHtml) {
String fillColor = "#F3F2C0";
out.println(" <node id=\"" + escapeXml10(nodeName) + "\">");
out.println(" <data key=\"d1\">");
out.println(" <y:ShapeNode>");
out.println(
" <y:Geometry height=\"150.0\" width=\"250.0\" x=\"77.0\" y=\"113.0\"/>\n"
+ " <y:Fill color=\"" + fillColor + "\" transparent=\"false\"/>\n"
+ " <y:BorderStyle color=\"#000000\" type=\"line\" width=\"1.0\"/>");
out.println(" <y:NodeLabel>"
+ escapeXml10("<html><p>" + nodeName + "</p>" + descriptionHtml + "</html>")
+ "</y:NodeLabel>");
out.println(" </y:ShapeNode>");
out.println(" </data>");
out.println(" </node>");
}
}
| update graph
| state-machine-generator/src/main/java/com/github/davidmoten/fsm/graph/GraphmlWriter.java | update graph |
|
Java | apache-2.0 | f755ff809caaa1dc880c92971f4a1c9425628a5c | 0 | adataylor/ios-driver,seem-sky/ios-driver,masbog/ios-driver,ios-driver/ios-driver,crashlytics/ios-driver,azaytsev/ios-driver,azaytsev/ios-driver,adataylor/ios-driver,shutkou/ios-driver,seem-sky/ios-driver,azaytsev/ios-driver,ios-driver/ios-driver,darraghgrace/ios-driver,crashlytics/ios-driver,masbog/ios-driver,darraghgrace/ios-driver,seem-sky/ios-driver,adataylor/ios-driver,shutkou/ios-driver,azaytsev/ios-driver,shutkou/ios-driver,darraghgrace/ios-driver,darraghgrace/ios-driver,shutkou/ios-driver,ios-driver/ios-driver,azaytsev/ios-driver,shutkou/ios-driver,masbog/ios-driver,crashlytics/ios-driver,seem-sky/ios-driver,darraghgrace/ios-driver,ios-driver/ios-driver,masbog/ios-driver,ios-driver/ios-driver,adataylor/ios-driver,crashlytics/ios-driver,masbog/ios-driver,adataylor/ios-driver,crashlytics/ios-driver,shutkou/ios-driver | /*
* Copyright 2012 ios-driver committers.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.uiautomation.ios.server.utils;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.WebDriverException;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.Writer;
/**
* Concatenate all the small JS files into 1 file passed to instruments, and replace variables by
* their value.
*
* @author freynaud
*/
public class ScriptHelper {
private final String main = "instruments-js/main.js";
private final String json = "instruments-js/json2.js";
private final String common = "instruments-js/common.js";
private final String lib1 = "instruments-js/UIAutomation.js";
private final String lib2 = "instruments-js/UIAElement.js";
private final String lib3 = "instruments-js/UIAApplication.js";
private final String lib4 = "instruments-js/UIATarget.js";
private final String lib5 = "instruments-js/UIAAlert.js";
private final String lib6 = "instruments-js/Cache.js";
private static final String FILE_NAME = "uiamasterscript";
private String load(String resource) throws IOException {
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource);
if (is == null) {
throw new WebDriverException("cannot load : " + resource);
}
StringWriter writer = new StringWriter();
IOUtils.copy(is, writer, "UTF-8");
String content = writer.toString();
return content;
}
private String generateScriptContent(int port, String aut, String opaqueKey) throws IOException {
StringBuilder scriptContent = new StringBuilder();
String c = load(lib1);
c = c.replace("$PORT", String.format("%d", port));
c = c.replace("$AUT", String.format("%s", aut));
c = c.replace("$SESSION", String.format("%s", opaqueKey));
scriptContent.append(load(json));
scriptContent.append(load(common));
scriptContent.append(load(lib4));
scriptContent.append(load(lib3));
scriptContent.append(load(lib2));
scriptContent.append(load(lib5));
scriptContent.append(load(lib6));
scriptContent.append(c);
scriptContent.append(load(main));
return scriptContent.toString();
}
public File createTmpScript(String content) {
try {
File res = File.createTempFile(FILE_NAME, ".js");
Writer writer = new FileWriter(res);
IOUtils.copy(IOUtils.toInputStream(content), writer, "UTF-8");
IOUtils.closeQuietly(writer);
return res;
} catch (Exception e) {
throw new WebDriverException("Cannot generate script.");
}
}
public File getScript(int port, String aut, String opaqueKey) {
try {
String content = generateScriptContent(port, aut, opaqueKey);
return createTmpScript(content);
} catch (Exception e) {
throw new WebDriverException("cannot generate the script for instrument.", e);
}
}
}
| server/src/main/java/org/uiautomation/ios/server/utils/ScriptHelper.java | /*
* Copyright 2012 ios-driver committers.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.uiautomation.ios.server.utils;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.WebDriverException;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.Writer;
/**
* Concatenate all the small JS files into 1 file passed to instruments, and replace variables by
* their value.
*
* @author freynaud
*/
public class ScriptHelper {
private final String main = "instruments-js/main.js";
private final String json = "instruments-js/json2.js";
private final String common = "instruments-js/common.js";
private final String lib1 = "instruments-js/UIAutomation.js";
private final String lib2 = "instruments-js/UIAElement.js";
private final String lib3 = "instruments-js/UIAApplication.js";
private final String lib4 = "instruments-js/UIATarget.js";
private final String lib5 = "instruments-js/UIAAlert.js";
private final String lib6 = "instruments-js/Cache.js";
private static final String FILE_NAME = "uiamasterscript";
private String load(String resource) throws IOException {
InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(resource);
if (is == null) {
throw new WebDriverException("cannot load : " + resource);
}
StringWriter writer = new StringWriter();
IOUtils.copy(is, writer, "UTF-8");
String content = writer.toString();
return content;
}
private String generateScriptContent(int port, String aut, String opaqueKey) throws IOException {
StringBuilder scriptContent = new StringBuilder();
String c = load(lib1);
c = c.replace("$PORT", String.format("%d", port));
c = c.replace("$AUT", String.format("%s", aut));
c = c.replace("$SESSION", String.format("%s", opaqueKey));
scriptContent.append(load(json));
scriptContent.append(load(common));
scriptContent.append(load(lib4));
scriptContent.append(load(lib3));
scriptContent.append(load(lib2));
scriptContent.append(load(lib5));
scriptContent.append(load(lib6));
scriptContent.append(c);
scriptContent.append(load(main));
return scriptContent.toString();
}
public File createTmpScript(String content) {
try {
//File res = File.createTempFile(FILE_NAME, ".js");
File res = new File("/Users/freynaud/master.js");
Writer writer = new FileWriter(res);
IOUtils.copy(IOUtils.toInputStream(content), writer, "UTF-8");
IOUtils.closeQuietly(writer);
return res;
} catch (Exception e) {
throw new WebDriverException("Cannot generate script.");
}
}
public File getScript(int port, String aut, String opaqueKey) {
try {
String content = generateScriptContent(port, aut, opaqueKey);
return createTmpScript(content);
} catch (Exception e) {
throw new WebDriverException("cannot generate the script for instrument.", e);
}
}
}
| removing hardcoded path.
| server/src/main/java/org/uiautomation/ios/server/utils/ScriptHelper.java | removing hardcoded path. |
|
Java | apache-2.0 | f0da276cceff81b3aa1097a9f8aa303aba46b963 | 0 | anzhdanov/seeding-realistic-concurrency-bugs,anzhdanov/seeding-realistic-concurrency-bugs,rikles/commons-lang,rikles/commons-lang,anzhdanov/seeding-realistic-concurrency-bugs,rikles/commons-lang | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.lang3.time;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.text.DateFormatSymbols;
import java.text.ParseException;
import java.text.ParsePosition;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.SortedMap;
import java.util.TimeZone;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* <p>FastDateParser is a fast and thread-safe version of
* {@link java.text.SimpleDateFormat}.</p>
*
* <p>To obtain a proxy to a FastDateParser, use {@link FastDateFormat#getInstance(String, TimeZone, Locale)}
* or another variation of the factory methods of {@link FastDateFormat}.</p>
*
* <p>Since FastDateParser is thread safe, you can use a static member instance:</p>
* <code>
* private static final DateParser DATE_PARSER = FastDateFormat.getInstance("yyyy-MM-dd");
* </code>
*
* <p>This class can be used as a direct replacement for
* <code>SimpleDateFormat</code> in most parsing situations.
* This class is especially useful in multi-threaded server environments.
* <code>SimpleDateFormat</code> is not thread-safe in any JDK version,
* nor will it be as Sun has closed the
* <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4228335">bug</a>/RFE.
* </p>
*
* <p>Only parsing is supported, but all patterns are compatible with
* SimpleDateFormat.</p>
*
* <p>Timing tests indicate this class is as about as fast as SimpleDateFormat
* in single thread applications and about 25% faster in multi-thread applications.</p>
*
* @version $Id$
* @since 3.2
*/
public class FastDateParser implements DateParser, Serializable {
/**
* Required for serialization support.
*
* @see java.io.Serializable
*/
private static final long serialVersionUID = 2L;
static final Locale JAPANESE_IMPERIAL = new Locale("ja","JP","JP");
// defining fields
private final String pattern;
private final TimeZone timeZone;
private final Locale locale;
private final int century;
private final int startYear;
// derived fields
private transient Pattern parsePattern;
private transient Strategy[] strategies;
// dynamic fields to communicate with Strategy
private transient String currentFormatField;
private transient Strategy nextStrategy;
/**
* <p>Constructs a new FastDateParser.</p>
*
* @param pattern non-null {@link java.text.SimpleDateFormat} compatible
* pattern
* @param timeZone non-null time zone to use
* @param locale non-null locale
*/
protected FastDateParser(final String pattern, final TimeZone timeZone, final Locale locale) {
this(pattern, timeZone, locale, null);
}
/**
* <p>Constructs a new FastDateParser.</p>
*
* @param pattern non-null {@link java.text.SimpleDateFormat} compatible
* pattern
* @param timeZone non-null time zone to use
* @param locale non-null locale
* @param centuryStart The start of the century for 2 digit year parsing
*
* @since 3.3
*/
protected FastDateParser(final String pattern, final TimeZone timeZone, final Locale locale, final Date centuryStart) {
this.pattern = pattern;
this.timeZone = timeZone;
this.locale = locale;
final Calendar definingCalendar = Calendar.getInstance(timeZone, locale);
int centuryStartYear;
if(centuryStart!=null) {
definingCalendar.setTime(centuryStart);
centuryStartYear= definingCalendar.get(Calendar.YEAR);
}
else if(locale.equals(JAPANESE_IMPERIAL)) {
centuryStartYear= 0;
}
else {
// from 80 years ago to 20 years from now
definingCalendar.setTime(new Date());
centuryStartYear= definingCalendar.get(Calendar.YEAR)-80;
}
century= centuryStartYear / 100 * 100;
startYear= centuryStartYear - century;
init(definingCalendar);
}
/**
* Initialize derived fields from defining fields.
* This is called from constructor and from readObject (de-serialization)
*
* @param definingCalendar the {@link java.util.Calendar} instance used to initialize this FastDateParser
*/
private void init(Calendar definingCalendar) {
final StringBuilder regex= new StringBuilder();
final List<Strategy> collector = new ArrayList<Strategy>();
final Matcher patternMatcher= formatPattern.matcher(pattern);
if(!patternMatcher.lookingAt()) {
throw new IllegalArgumentException(
"Illegal pattern character '" + pattern.charAt(patternMatcher.regionStart()) + "'");
}
currentFormatField= patternMatcher.group();
Strategy currentStrategy= getStrategy(currentFormatField, definingCalendar);
for(;;) {
patternMatcher.region(patternMatcher.end(), patternMatcher.regionEnd());
if(!patternMatcher.lookingAt()) {
nextStrategy = null;
break;
}
final String nextFormatField= patternMatcher.group();
nextStrategy = getStrategy(nextFormatField, definingCalendar);
if(currentStrategy.addRegex(this, regex)) {
collector.add(currentStrategy);
}
currentFormatField= nextFormatField;
currentStrategy= nextStrategy;
}
if (patternMatcher.regionStart() != patternMatcher.regionEnd()) {
throw new IllegalArgumentException("Failed to parse \""+pattern+"\" ; gave up at index "+patternMatcher.regionStart());
}
if(currentStrategy.addRegex(this, regex)) {
collector.add(currentStrategy);
}
currentFormatField= null;
strategies= collector.toArray(new Strategy[collector.size()]);
parsePattern= Pattern.compile(regex.toString());
}
// Accessors
//-----------------------------------------------------------------------
/* (non-Javadoc)
* @see org.apache.commons.lang3.time.DateParser#getPattern()
*/
@Override
public String getPattern() {
return pattern;
}
/* (non-Javadoc)
* @see org.apache.commons.lang3.time.DateParser#getTimeZone()
*/
@Override
public TimeZone getTimeZone() {
return timeZone;
}
/* (non-Javadoc)
* @see org.apache.commons.lang3.time.DateParser#getLocale()
*/
@Override
public Locale getLocale() {
return locale;
}
/**
* Returns the generated pattern (for testing purposes).
*
* @return the generated pattern
*/
Pattern getParsePattern() {
return parsePattern;
}
// Basics
//-----------------------------------------------------------------------
/**
* <p>Compare another object for equality with this object.</p>
*
* @param obj the object to compare to
* @return <code>true</code>if equal to this instance
*/
@Override
public boolean equals(final Object obj) {
if (! (obj instanceof FastDateParser) ) {
return false;
}
final FastDateParser other = (FastDateParser) obj;
return pattern.equals(other.pattern)
&& timeZone.equals(other.timeZone)
&& locale.equals(other.locale);
}
/**
* <p>Return a hashcode compatible with equals.</p>
*
* @return a hashcode compatible with equals
*/
@Override
public int hashCode() {
return pattern.hashCode() + 13 * (timeZone.hashCode() + 13 * locale.hashCode());
}
/**
* <p>Get a string version of this formatter.</p>
*
* @return a debugging string
*/
@Override
public String toString() {
return "FastDateParser[" + pattern + "," + locale + "," + timeZone.getID() + "]";
}
// Serializing
//-----------------------------------------------------------------------
/**
* Create the object after serialization. This implementation reinitializes the
* transient properties.
*
* @param in ObjectInputStream from which the object is being deserialized.
* @throws IOException if there is an IO issue.
* @throws ClassNotFoundException if a class cannot be found.
*/
private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
final Calendar definingCalendar = Calendar.getInstance(timeZone, locale);
init(definingCalendar);
}
/* (non-Javadoc)
* @see org.apache.commons.lang3.time.DateParser#parseObject(java.lang.String)
*/
@Override
public Object parseObject(final String source) throws ParseException {
return parse(source);
}
/* (non-Javadoc)
* @see org.apache.commons.lang3.time.DateParser#parse(java.lang.String)
*/
@Override
public Date parse(final String source) throws ParseException {
final Date date= parse(source, new ParsePosition(0));
if(date==null) {
// Add a note re supported date range
if (locale.equals(JAPANESE_IMPERIAL)) {
throw new ParseException(
"(The " +locale + " locale does not support dates before 1868 AD)\n" +
"Unparseable date: \""+source+"\" does not match "+parsePattern.pattern(), 0);
}
throw new ParseException("Unparseable date: \""+source+"\" does not match "+parsePattern.pattern(), 0);
}
return date;
}
/* (non-Javadoc)
* @see org.apache.commons.lang3.time.DateParser#parseObject(java.lang.String, java.text.ParsePosition)
*/
@Override
public Object parseObject(final String source, final ParsePosition pos) {
return parse(source, pos);
}
/* (non-Javadoc)
* @see org.apache.commons.lang3.time.DateParser#parse(java.lang.String, java.text.ParsePosition)
*/
@Override
public Date parse(final String source, final ParsePosition pos) {
final int offset= pos.getIndex();
final Matcher matcher= parsePattern.matcher(source.substring(offset));
if(!matcher.lookingAt()) {
return null;
}
// timing tests indicate getting new instance is 19% faster than cloning
final Calendar cal= Calendar.getInstance(timeZone, locale);
cal.clear();
for(int i=0; i<strategies.length;) {
final Strategy strategy= strategies[i++];
strategy.setCalendar(this, cal, matcher.group(i));
}
pos.setIndex(offset+matcher.end());
return cal.getTime();
}
// Support for strategies
//-----------------------------------------------------------------------
/**
* Escape constant fields into regular expression
* @param regex The destination regex
* @param value The source field
* @param unquote If true, replace two success quotes ('') with single quote (')
* @return The <code>StringBuilder</code>
*/
private static StringBuilder escapeRegex(final StringBuilder regex, final String value, final boolean unquote) {
regex.append("\\Q");
for(int i= 0; i<value.length(); ++i) {
char c= value.charAt(i);
switch(c) {
case '\'':
if(unquote) {
if(++i==value.length()) {
return regex;
}
c= value.charAt(i);
}
break;
case '\\':
if(++i==value.length()) {
break;
}
/*
* If we have found \E, we replace it with \E\\E\Q, i.e. we stop the quoting,
* quote the \ in \E, then restart the quoting.
*
* Otherwise we just output the two characters.
* In each case the initial \ needs to be output and the final char is done at the end
*/
regex.append(c); // we always want the original \
c = value.charAt(i); // Is it followed by E ?
if (c == 'E') { // \E detected
regex.append("E\\\\E\\"); // see comment above
c = 'Q'; // appended below
}
break;
default:
break;
}
regex.append(c);
}
regex.append("\\E");
return regex;
}
/**
* Get the short and long values displayed for a field
* @param field The field of interest
* @param definingCalendar The calendar to obtain the short and long values
* @param locale The locale of display names
* @return A Map of the field key / value pairs
*/
private static Map<String, Integer> getDisplayNames(final int field, final Calendar definingCalendar, final Locale locale) {
return definingCalendar.getDisplayNames(field, Calendar.ALL_STYLES, locale);
}
/**
* Adjust dates to be within appropriate century
* @param twoDigitYear The year to adjust
* @return A value between centuryStart(inclusive) to centuryStart+100(exclusive)
*/
private int adjustYear(final int twoDigitYear) {
int trial= century + twoDigitYear;
return twoDigitYear>=startYear ?trial :trial+100;
}
/**
* Is the next field a number?
* @return true, if next field will be a number
*/
boolean isNextNumber() {
return nextStrategy!=null && nextStrategy.isNumber();
}
/**
* What is the width of the current field?
* @return The number of characters in the current format field
*/
int getFieldWidth() {
return currentFormatField.length();
}
/**
* A strategy to parse a single field from the parsing pattern
*/
private static abstract class Strategy {
/**
* Is this field a number?
* The default implementation returns false.
*
* @return true, if field is a number
*/
boolean isNumber() {
return false;
}
/**
* Set the Calendar with the parsed field.
*
* The default implementation does nothing.
*
* @param parser The parser calling this strategy
* @param cal The <code>Calendar</code> to set
* @param value The parsed field to translate and set in cal
*/
void setCalendar(final FastDateParser parser, final Calendar cal, final String value) {
}
/**
* Generate a <code>Pattern</code> regular expression to the <code>StringBuilder</code>
* which will accept this field
* @param parser The parser calling this strategy
* @param regex The <code>StringBuilder</code> to append to
* @return true, if this field will set the calendar;
* false, if this field is a constant value
*/
abstract boolean addRegex(FastDateParser parser, StringBuilder regex);
}
/**
* A <code>Pattern</code> to parse the user supplied SimpleDateFormat pattern
*/
private static final Pattern formatPattern= Pattern.compile(
"D+|E+|F+|G+|H+|K+|M+|S+|W+|Z+|a+|d+|h+|k+|m+|s+|w+|y+|z+|''|'[^']++(''[^']*+)*+'|[^'A-Za-z]++");
/**
* Obtain a Strategy given a field from a SimpleDateFormat pattern
* @param formatField A sub-sequence of the SimpleDateFormat pattern
* @param definingCalendar The calendar to obtain the short and long values
* @return The Strategy that will handle parsing for the field
*/
private Strategy getStrategy(final String formatField, final Calendar definingCalendar) {
switch(formatField.charAt(0)) {
case '\'':
if(formatField.length()>2) {
return new CopyQuotedStrategy(formatField.substring(1, formatField.length()-1));
}
//$FALL-THROUGH$
default:
return new CopyQuotedStrategy(formatField);
case 'D':
return DAY_OF_YEAR_STRATEGY;
case 'E':
return getLocaleSpecificStrategy(Calendar.DAY_OF_WEEK, definingCalendar);
case 'F':
return DAY_OF_WEEK_IN_MONTH_STRATEGY;
case 'G':
return getLocaleSpecificStrategy(Calendar.ERA, definingCalendar);
case 'H':
return MODULO_HOUR_OF_DAY_STRATEGY;
case 'K':
return HOUR_STRATEGY;
case 'M':
return formatField.length()>=3 ?getLocaleSpecificStrategy(Calendar.MONTH, definingCalendar) :NUMBER_MONTH_STRATEGY;
case 'S':
return MILLISECOND_STRATEGY;
case 'W':
return WEEK_OF_MONTH_STRATEGY;
case 'a':
return getLocaleSpecificStrategy(Calendar.AM_PM, definingCalendar);
case 'd':
return DAY_OF_MONTH_STRATEGY;
case 'h':
return MODULO_HOUR_STRATEGY;
case 'k':
return HOUR_OF_DAY_STRATEGY;
case 'm':
return MINUTE_STRATEGY;
case 's':
return SECOND_STRATEGY;
case 'w':
return WEEK_OF_YEAR_STRATEGY;
case 'y':
return formatField.length()>2 ?LITERAL_YEAR_STRATEGY :ABBREVIATED_YEAR_STRATEGY;
case 'Z':
case 'z':
return getLocaleSpecificStrategy(Calendar.ZONE_OFFSET, definingCalendar);
}
}
@SuppressWarnings("unchecked") // OK because we are creating an array with no entries
private static final ConcurrentMap<Locale, Strategy>[] caches = new ConcurrentMap[Calendar.FIELD_COUNT];
/**
* Get a cache of Strategies for a particular field
* @param field The Calendar field
* @return a cache of Locale to Strategy
*/
private static ConcurrentMap<Locale, Strategy> getCache(final int field) {
synchronized(caches) {
if(caches[field]==null) {
caches[field]= new ConcurrentHashMap<Locale,Strategy>(3);
}
return caches[field];
}
}
/**
* Construct a Strategy that parses a Text field
* @param field The Calendar field
* @param definingCalendar The calendar to obtain the short and long values
* @return a TextStrategy for the field and Locale
*/
private Strategy getLocaleSpecificStrategy(final int field, final Calendar definingCalendar) {
final ConcurrentMap<Locale,Strategy> cache = getCache(field);
Strategy strategy= cache.get(locale);
if(strategy==null) {
strategy= field==Calendar.ZONE_OFFSET
? new TimeZoneStrategy(locale)
: new CaseInsensitiveTextStrategy(field, definingCalendar, locale);
final Strategy inCache= cache.putIfAbsent(locale, strategy);
if(inCache!=null) {
return inCache;
}
}
return strategy;
}
/**
* A strategy that copies the static or quoted field in the parsing pattern
*/
private static class CopyQuotedStrategy extends Strategy {
private final String formatField;
/**
* Construct a Strategy that ensures the formatField has literal text
* @param formatField The literal text to match
*/
CopyQuotedStrategy(final String formatField) {
this.formatField= formatField;
}
/**
* {@inheritDoc}
*/
@Override
boolean isNumber() {
char c= formatField.charAt(0);
if(c=='\'') {
c= formatField.charAt(1);
}
return Character.isDigit(c);
}
/**
* {@inheritDoc}
*/
@Override
boolean addRegex(final FastDateParser parser, final StringBuilder regex) {
escapeRegex(regex, formatField, true);
return false;
}
}
/**
* A strategy that handles a text field in the parsing pattern
*/
private static class CaseInsensitiveTextStrategy extends Strategy {
private final int field;
private final Locale locale;
private final Map<String, Integer> keyValues;
private final Map<String, Integer> lKeyValues;
/**
* Construct a Strategy that parses a Text field
* @param field The Calendar field
* @param definingCalendar The Calendar to use
* @param locale The Locale to use
*/
CaseInsensitiveTextStrategy(final int field, final Calendar definingCalendar, final Locale locale) {
this.field= field;
this.locale= locale;
this.keyValues= getDisplayNames(field, definingCalendar, locale);
this.lKeyValues= new HashMap<String,Integer>();
for(Map.Entry<String, Integer> entry : keyValues.entrySet()) {
lKeyValues.put(entry.getKey().toLowerCase(locale), entry.getValue());
}
}
/**
* {@inheritDoc}
*/
@Override
boolean addRegex(final FastDateParser parser, final StringBuilder regex) {
regex.append("((?iu)");
for(final String textKeyValue : keyValues.keySet()) {
escapeRegex(regex, textKeyValue, false).append('|');
}
regex.setCharAt(regex.length()-1, ')');
return true;
}
/**
* {@inheritDoc}
*/
@Override
void setCalendar(final FastDateParser parser, final Calendar cal, final String value) {
final Integer iVal = lKeyValues.get(value.toLowerCase(locale));
if(iVal == null) {
final StringBuilder sb= new StringBuilder(value);
sb.append(" not in (");
for(final String textKeyValue : keyValues.keySet()) {
sb.append(textKeyValue).append(' ');
}
sb.setCharAt(sb.length()-1, ')');
throw new IllegalArgumentException(sb.toString());
}
cal.set(field, iVal.intValue());
}
}
/**
* A strategy that handles a number field in the parsing pattern
*/
private static class NumberStrategy extends Strategy {
private final int field;
/**
* Construct a Strategy that parses a Number field
* @param field The Calendar field
*/
NumberStrategy(final int field) {
this.field= field;
}
/**
* {@inheritDoc}
*/
@Override
boolean isNumber() {
return true;
}
/**
* {@inheritDoc}
*/
@Override
boolean addRegex(final FastDateParser parser, final StringBuilder regex) {
// See LANG-954: We use {Nd} rather than {IsNd} because Android does not support the Is prefix
if(parser.isNextNumber()) {
regex.append("(\\p{Nd}{").append(parser.getFieldWidth()).append("}+)");
}
else {
regex.append("(\\p{Nd}++)");
}
return true;
}
/**
* {@inheritDoc}
*/
@Override
void setCalendar(final FastDateParser parser, final Calendar cal, final String value) {
cal.set(field, modify(Integer.parseInt(value)));
}
/**
* Make any modifications to parsed integer
* @param iValue The parsed integer
* @return The modified value
*/
int modify(final int iValue) {
return iValue;
}
}
private static final Strategy ABBREVIATED_YEAR_STRATEGY = new NumberStrategy(Calendar.YEAR) {
/**
* {@inheritDoc}
*/
@Override
void setCalendar(final FastDateParser parser, final Calendar cal, final String value) {
int iValue= Integer.parseInt(value);
if(iValue<100) {
iValue= parser.adjustYear(iValue);
}
cal.set(Calendar.YEAR, iValue);
}
};
/**
* A strategy that handles a timezone field in the parsing pattern
*/
private static class TimeZoneStrategy extends Strategy {
private final String validTimeZoneChars;
private final SortedMap<String, TimeZone> tzNames= new TreeMap<String, TimeZone>(String.CASE_INSENSITIVE_ORDER);
/**
* Index of zone id
*/
private static final int ID = 0;
/**
* Index of the long name of zone in standard time
*/
private static final int LONG_STD = 1;
/**
* Index of the short name of zone in standard time
*/
private static final int SHORT_STD = 2;
/**
* Index of the long name of zone in daylight saving time
*/
private static final int LONG_DST = 3;
/**
* Index of the short name of zone in daylight saving time
*/
private static final int SHORT_DST = 4;
/**
* Construct a Strategy that parses a TimeZone
* @param locale The Locale
*/
TimeZoneStrategy(final Locale locale) {
final String[][] zones = DateFormatSymbols.getInstance(locale).getZoneStrings();
for (String[] zone : zones) {
if (zone[ID].startsWith("GMT")) {
continue;
}
final TimeZone tz = TimeZone.getTimeZone(zone[ID]);
if (!tzNames.containsKey(zone[LONG_STD])){
tzNames.put(zone[LONG_STD], tz);
}
if (!tzNames.containsKey(zone[SHORT_STD])){
tzNames.put(zone[SHORT_STD], tz);
}
if (tz.useDaylightTime()) {
if (!tzNames.containsKey(zone[LONG_DST])){
tzNames.put(zone[LONG_DST], tz);
}
if (!tzNames.containsKey(zone[SHORT_DST])){
tzNames.put(zone[SHORT_DST], tz);
}
}
}
final StringBuilder sb= new StringBuilder();
sb.append("(GMT[+\\-]\\d{0,1}\\d{2}|[+\\-]\\d{2}:?\\d{2}|");
for(final String id : tzNames.keySet()) {
escapeRegex(sb, id, false).append('|');
}
sb.setCharAt(sb.length()-1, ')');
validTimeZoneChars= sb.toString();
}
/**
* {@inheritDoc}
*/
@Override
boolean addRegex(final FastDateParser parser, final StringBuilder regex) {
regex.append(validTimeZoneChars);
return true;
}
/**
* {@inheritDoc}
*/
@Override
void setCalendar(final FastDateParser parser, final Calendar cal, final String value) {
TimeZone tz;
if(value.charAt(0)=='+' || value.charAt(0)=='-') {
tz= TimeZone.getTimeZone("GMT"+value);
}
else if(value.startsWith("GMT")) {
tz= TimeZone.getTimeZone(value);
}
else {
tz= tzNames.get(value);
if(tz==null) {
throw new IllegalArgumentException(value + " is not a supported timezone name");
}
}
cal.setTimeZone(tz);
}
}
private static final Strategy NUMBER_MONTH_STRATEGY = new NumberStrategy(Calendar.MONTH) {
@Override
int modify(final int iValue) {
return iValue-1;
}
};
private static final Strategy LITERAL_YEAR_STRATEGY = new NumberStrategy(Calendar.YEAR);
private static final Strategy WEEK_OF_YEAR_STRATEGY = new NumberStrategy(Calendar.WEEK_OF_YEAR);
private static final Strategy WEEK_OF_MONTH_STRATEGY = new NumberStrategy(Calendar.WEEK_OF_MONTH);
private static final Strategy DAY_OF_YEAR_STRATEGY = new NumberStrategy(Calendar.DAY_OF_YEAR);
private static final Strategy DAY_OF_MONTH_STRATEGY = new NumberStrategy(Calendar.DAY_OF_MONTH);
private static final Strategy DAY_OF_WEEK_IN_MONTH_STRATEGY = new NumberStrategy(Calendar.DAY_OF_WEEK_IN_MONTH);
private static final Strategy HOUR_OF_DAY_STRATEGY = new NumberStrategy(Calendar.HOUR_OF_DAY);
private static final Strategy MODULO_HOUR_OF_DAY_STRATEGY = new NumberStrategy(Calendar.HOUR_OF_DAY) {
@Override
int modify(final int iValue) {
return iValue%24;
}
};
private static final Strategy MODULO_HOUR_STRATEGY = new NumberStrategy(Calendar.HOUR) {
@Override
int modify(final int iValue) {
return iValue%12;
}
};
private static final Strategy HOUR_STRATEGY = new NumberStrategy(Calendar.HOUR);
private static final Strategy MINUTE_STRATEGY = new NumberStrategy(Calendar.MINUTE);
private static final Strategy SECOND_STRATEGY = new NumberStrategy(Calendar.SECOND);
private static final Strategy MILLISECOND_STRATEGY = new NumberStrategy(Calendar.MILLISECOND);
}
| src/main/java/org/apache/commons/lang3/time/FastDateParser.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.lang3.time;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;
import java.text.DateFormatSymbols;
import java.text.ParseException;
import java.text.ParsePosition;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.SortedMap;
import java.util.TimeZone;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* <p>FastDateParser is a fast and thread-safe version of
* {@link java.text.SimpleDateFormat}.</p>
*
* <p>To obtain a proxy to a FastDateParser, use {@link FastDateFormat#getInstance(String, TimeZone, Locale)}
* or another variation of the factory methods of {@link FastDateFormat}.</p>
*
* <p>Since FastDateParser is thread safe, you can use a static member instance:</p>
* <code>
* private static final DateParser DATE_PARSER = FastDateFormat.getInstance("yyyy-MM-dd");
* </code>
*
* <p>This class can be used as a direct replacement for
* <code>SimpleDateFormat</code> in most parsing situations.
* This class is especially useful in multi-threaded server environments.
* <code>SimpleDateFormat</code> is not thread-safe in any JDK version,
* nor will it be as Sun has closed the
* <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4228335">bug</a>/RFE.
* </p>
*
* <p>Only parsing is supported, but all patterns are compatible with
* SimpleDateFormat.</p>
*
* <p>Timing tests indicate this class is as about as fast as SimpleDateFormat
* in single thread applications and about 25% faster in multi-thread applications.</p>
*
* @version $Id$
* @since 3.2
*/
public class FastDateParser implements DateParser, Serializable {
/**
* Required for serialization support.
*
* @see java.io.Serializable
*/
private static final long serialVersionUID = 2L;
static final Locale JAPANESE_IMPERIAL = new Locale("ja","JP","JP");
// defining fields
private final String pattern;
private final TimeZone timeZone;
private final Locale locale;
private final int century;
private final int startYear;
// derived fields
private transient Pattern parsePattern;
private transient Strategy[] strategies;
// dynamic fields to communicate with Strategy
private transient String currentFormatField;
private transient Strategy nextStrategy;
/**
* <p>Constructs a new FastDateParser.</p>
*
* @param pattern non-null {@link java.text.SimpleDateFormat} compatible
* pattern
* @param timeZone non-null time zone to use
* @param locale non-null locale
*/
protected FastDateParser(final String pattern, final TimeZone timeZone, final Locale locale) {
this(pattern, timeZone, locale, null);
}
/**
* <p>Constructs a new FastDateParser.</p>
*
* @param pattern non-null {@link java.text.SimpleDateFormat} compatible
* pattern
* @param timeZone non-null time zone to use
* @param locale non-null locale
* @param centuryStart The start of the century for 2 digit year parsing
*
* @since 3.3
*/
protected FastDateParser(final String pattern, final TimeZone timeZone, final Locale locale, final Date centuryStart) {
this.pattern = pattern;
this.timeZone = timeZone;
this.locale = locale;
final Calendar definingCalendar = Calendar.getInstance(timeZone, locale);
int centuryStartYear;
if(centuryStart!=null) {
definingCalendar.setTime(centuryStart);
centuryStartYear= definingCalendar.get(Calendar.YEAR);
}
else if(locale.equals(JAPANESE_IMPERIAL)) {
centuryStartYear= 0;
}
else {
// from 80 years ago to 20 years from now
definingCalendar.setTime(new Date());
centuryStartYear= definingCalendar.get(Calendar.YEAR)-80;
}
century= centuryStartYear / 100 * 100;
startYear= centuryStartYear - century;
init(definingCalendar);
}
/**
* Initialize derived fields from defining fields.
* This is called from constructor and from readObject (de-serialization)
*
* @param definingCalendar the {@link java.util.Calendar} instance used to initialize this FastDateParser
*/
private void init(Calendar definingCalendar) {
final StringBuilder regex= new StringBuilder();
final List<Strategy> collector = new ArrayList<Strategy>();
final Matcher patternMatcher= formatPattern.matcher(pattern);
if(!patternMatcher.lookingAt()) {
throw new IllegalArgumentException(
"Illegal pattern character '" + pattern.charAt(patternMatcher.regionStart()) + "'");
}
currentFormatField= patternMatcher.group();
Strategy currentStrategy= getStrategy(currentFormatField, definingCalendar);
for(;;) {
patternMatcher.region(patternMatcher.end(), patternMatcher.regionEnd());
if(!patternMatcher.lookingAt()) {
nextStrategy = null;
break;
}
final String nextFormatField= patternMatcher.group();
nextStrategy = getStrategy(nextFormatField, definingCalendar);
if(currentStrategy.addRegex(this, regex)) {
collector.add(currentStrategy);
}
currentFormatField= nextFormatField;
currentStrategy= nextStrategy;
}
if (patternMatcher.regionStart() != patternMatcher.regionEnd()) {
throw new IllegalArgumentException("Failed to parse \""+pattern+"\" ; gave up at index "+patternMatcher.regionStart());
}
if(currentStrategy.addRegex(this, regex)) {
collector.add(currentStrategy);
}
currentFormatField= null;
strategies= collector.toArray(new Strategy[collector.size()]);
parsePattern= Pattern.compile(regex.toString());
}
// Accessors
//-----------------------------------------------------------------------
/* (non-Javadoc)
* @see org.apache.commons.lang3.time.DateParser#getPattern()
*/
@Override
public String getPattern() {
return pattern;
}
/* (non-Javadoc)
* @see org.apache.commons.lang3.time.DateParser#getTimeZone()
*/
@Override
public TimeZone getTimeZone() {
return timeZone;
}
/* (non-Javadoc)
* @see org.apache.commons.lang3.time.DateParser#getLocale()
*/
@Override
public Locale getLocale() {
return locale;
}
/**
* Returns the generated pattern (for testing purposes).
*
* @return the generated pattern
*/
Pattern getParsePattern() {
return parsePattern;
}
// Basics
//-----------------------------------------------------------------------
/**
* <p>Compare another object for equality with this object.</p>
*
* @param obj the object to compare to
* @return <code>true</code>if equal to this instance
*/
@Override
public boolean equals(final Object obj) {
if (! (obj instanceof FastDateParser) ) {
return false;
}
final FastDateParser other = (FastDateParser) obj;
return pattern.equals(other.pattern)
&& timeZone.equals(other.timeZone)
&& locale.equals(other.locale);
}
/**
* <p>Return a hashcode compatible with equals.</p>
*
* @return a hashcode compatible with equals
*/
@Override
public int hashCode() {
return pattern.hashCode() + 13 * (timeZone.hashCode() + 13 * locale.hashCode());
}
/**
* <p>Get a string version of this formatter.</p>
*
* @return a debugging string
*/
@Override
public String toString() {
return "FastDateParser[" + pattern + "," + locale + "," + timeZone.getID() + "]";
}
// Serializing
//-----------------------------------------------------------------------
/**
* Create the object after serialization. This implementation reinitializes the
* transient properties.
*
* @param in ObjectInputStream from which the object is being deserialized.
* @throws IOException if there is an IO issue.
* @throws ClassNotFoundException if a class cannot be found.
*/
private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
final Calendar definingCalendar = Calendar.getInstance(timeZone, locale);
init(definingCalendar);
}
/* (non-Javadoc)
* @see org.apache.commons.lang3.time.DateParser#parseObject(java.lang.String)
*/
@Override
public Object parseObject(final String source) throws ParseException {
return parse(source);
}
/* (non-Javadoc)
* @see org.apache.commons.lang3.time.DateParser#parse(java.lang.String)
*/
@Override
public Date parse(final String source) throws ParseException {
final Date date= parse(source, new ParsePosition(0));
if(date==null) {
// Add a note re supported date range
if (locale.equals(JAPANESE_IMPERIAL)) {
throw new ParseException(
"(The " +locale + " locale does not support dates before 1868 AD)\n" +
"Unparseable date: \""+source+"\" does not match "+parsePattern.pattern(), 0);
}
throw new ParseException("Unparseable date: \""+source+"\" does not match "+parsePattern.pattern(), 0);
}
return date;
}
/* (non-Javadoc)
* @see org.apache.commons.lang3.time.DateParser#parseObject(java.lang.String, java.text.ParsePosition)
*/
@Override
public Object parseObject(final String source, final ParsePosition pos) {
return parse(source, pos);
}
/* (non-Javadoc)
* @see org.apache.commons.lang3.time.DateParser#parse(java.lang.String, java.text.ParsePosition)
*/
@Override
public Date parse(final String source, final ParsePosition pos) {
final int offset= pos.getIndex();
final Matcher matcher= parsePattern.matcher(source.substring(offset));
if(!matcher.lookingAt()) {
return null;
}
// timing tests indicate getting new instance is 19% faster than cloning
final Calendar cal= Calendar.getInstance(timeZone, locale);
cal.clear();
for(int i=0; i<strategies.length;) {
final Strategy strategy= strategies[i++];
strategy.setCalendar(this, cal, matcher.group(i));
}
pos.setIndex(offset+matcher.end());
return cal.getTime();
}
// Support for strategies
//-----------------------------------------------------------------------
/**
* Escape constant fields into regular expression
* @param regex The destination regex
* @param value The source field
* @param unquote If true, replace two success quotes ('') with single quote (')
* @return The <code>StringBuilder</code>
*/
private static StringBuilder escapeRegex(final StringBuilder regex, final String value, final boolean unquote) {
regex.append("\\Q");
for(int i= 0; i<value.length(); ++i) {
char c= value.charAt(i);
switch(c) {
case '\'':
if(unquote) {
if(++i==value.length()) {
return regex;
}
c= value.charAt(i);
}
break;
case '\\':
if(++i==value.length()) {
break;
}
/*
* If we have found \E, we replace it with \E\\E\Q, i.e. we stop the quoting,
* quote the \ in \E, then restart the quoting.
*
* Otherwise we just output the two characters.
* In each case the initial \ needs to be output and the final char is done at the end
*/
regex.append(c); // we always want the original \
c = value.charAt(i); // Is it followed by E ?
if (c == 'E') { // \E detected
regex.append("E\\\\E\\"); // see comment above
c = 'Q'; // appended below
}
break;
default:
break;
}
regex.append(c);
}
regex.append("\\E");
return regex;
}
/**
* Get the short and long values displayed for a field
* @param field The field of interest
* @param definingCalendar The calendar to obtain the short and long values
* @param locale The locale of display names
* @return A Map of the field key / value pairs
*/
private static Map<String, Integer> getDisplayNames(final int field, final Calendar definingCalendar, final Locale locale) {
return definingCalendar.getDisplayNames(field, Calendar.ALL_STYLES, locale);
}
/**
* Adjust dates to be within appropriate century
* @param twoDigitYear The year to adjust
* @return A value between centuryStart(inclusive) to centuryStart+100(exclusive)
*/
private int adjustYear(final int twoDigitYear) {
int trial= century + twoDigitYear;
return twoDigitYear>=startYear ?trial :trial+100;
}
/**
* Is the next field a number?
* @return true, if next field will be a number
*/
boolean isNextNumber() {
return nextStrategy!=null && nextStrategy.isNumber();
}
/**
* What is the width of the current field?
* @return The number of characters in the current format field
*/
int getFieldWidth() {
return currentFormatField.length();
}
/**
* A strategy to parse a single field from the parsing pattern
*/
private static abstract class Strategy {
/**
* Is this field a number?
* The default implementation returns false.
*
* @return true, if field is a number
*/
boolean isNumber() {
return false;
}
/**
* Set the Calendar with the parsed field.
*
* The default implementation does nothing.
*
* @param parser The parser calling this strategy
* @param cal The <code>Calendar</code> to set
* @param value The parsed field to translate and set in cal
*/
void setCalendar(final FastDateParser parser, final Calendar cal, final String value) {
}
/**
* Generate a <code>Pattern</code> regular expression to the <code>StringBuilder</code>
* which will accept this field
* @param parser The parser calling this strategy
* @param regex The <code>StringBuilder</code> to append to
* @return true, if this field will set the calendar;
* false, if this field is a constant value
*/
abstract boolean addRegex(FastDateParser parser, StringBuilder regex);
}
/**
* A <code>Pattern</code> to parse the user supplied SimpleDateFormat pattern
*/
private static final Pattern formatPattern= Pattern.compile(
"D+|E+|F+|G+|H+|K+|M+|S+|W+|Z+|a+|d+|h+|k+|m+|s+|w+|y+|z+|''|'[^']++(''[^']*+)*+'|[^'A-Za-z]++");
/**
* Obtain a Strategy given a field from a SimpleDateFormat pattern
* @param formatField A sub-sequence of the SimpleDateFormat pattern
* @param definingCalendar The calendar to obtain the short and long values
* @return The Strategy that will handle parsing for the field
*/
private Strategy getStrategy(final String formatField, final Calendar definingCalendar) {
switch(formatField.charAt(0)) {
case '\'':
if(formatField.length()>2) {
return new CopyQuotedStrategy(formatField.substring(1, formatField.length()-1));
}
//$FALL-THROUGH$
default:
return new CopyQuotedStrategy(formatField);
case 'D':
return DAY_OF_YEAR_STRATEGY;
case 'E':
return getLocaleSpecificStrategy(Calendar.DAY_OF_WEEK, definingCalendar);
case 'F':
return DAY_OF_WEEK_IN_MONTH_STRATEGY;
case 'G':
return getLocaleSpecificStrategy(Calendar.ERA, definingCalendar);
case 'H':
return MODULO_HOUR_OF_DAY_STRATEGY;
case 'K':
return HOUR_STRATEGY;
case 'M':
return formatField.length()>=3 ?getLocaleSpecificStrategy(Calendar.MONTH, definingCalendar) :NUMBER_MONTH_STRATEGY;
case 'S':
return MILLISECOND_STRATEGY;
case 'W':
return WEEK_OF_MONTH_STRATEGY;
case 'a':
return getLocaleSpecificStrategy(Calendar.AM_PM, definingCalendar);
case 'd':
return DAY_OF_MONTH_STRATEGY;
case 'h':
return MODULO_HOUR_STRATEGY;
case 'k':
return HOUR_OF_DAY_STRATEGY;
case 'm':
return MINUTE_STRATEGY;
case 's':
return SECOND_STRATEGY;
case 'w':
return WEEK_OF_YEAR_STRATEGY;
case 'y':
return formatField.length()>2 ?LITERAL_YEAR_STRATEGY :ABBREVIATED_YEAR_STRATEGY;
case 'Z':
case 'z':
return getLocaleSpecificStrategy(Calendar.ZONE_OFFSET, definingCalendar);
}
}
@SuppressWarnings("unchecked") // OK because we are creating an array with no entries
private static final ConcurrentMap<Locale, Strategy>[] caches = new ConcurrentMap[Calendar.FIELD_COUNT];
/**
* Get a cache of Strategies for a particular field
* @param field The Calendar field
* @return a cache of Locale to Strategy
*/
private static ConcurrentMap<Locale, Strategy> getCache(final int field) {
synchronized(caches) {
if(caches[field]==null) {
caches[field]= new ConcurrentHashMap<Locale,Strategy>(3);
}
return caches[field];
}
}
/**
* Construct a Strategy that parses a Text field
* @param field The Calendar field
* @param definingCalendar The calendar to obtain the short and long values
* @return a TextStrategy for the field and Locale
*/
private Strategy getLocaleSpecificStrategy(final int field, final Calendar definingCalendar) {
final ConcurrentMap<Locale,Strategy> cache = getCache(field);
Strategy strategy= cache.get(locale);
if(strategy==null) {
strategy= field==Calendar.ZONE_OFFSET
? new TimeZoneStrategy(locale)
: new TextStrategy(field, definingCalendar, locale);
final Strategy inCache= cache.putIfAbsent(locale, strategy);
if(inCache!=null) {
return inCache;
}
}
return strategy;
}
/**
* A strategy that copies the static or quoted field in the parsing pattern
*/
private static class CopyQuotedStrategy extends Strategy {
private final String formatField;
/**
* Construct a Strategy that ensures the formatField has literal text
* @param formatField The literal text to match
*/
CopyQuotedStrategy(final String formatField) {
this.formatField= formatField;
}
/**
* {@inheritDoc}
*/
@Override
boolean isNumber() {
char c= formatField.charAt(0);
if(c=='\'') {
c= formatField.charAt(1);
}
return Character.isDigit(c);
}
/**
* {@inheritDoc}
*/
@Override
boolean addRegex(final FastDateParser parser, final StringBuilder regex) {
escapeRegex(regex, formatField, true);
return false;
}
}
/**
* A strategy that handles a text field in the parsing pattern
*/
private static class TextStrategy extends Strategy {
private final int field;
private final Locale locale;
private final Map<String, Integer> keyValues;
private final Map<String, Integer> lKeyValues;
/**
* Construct a Strategy that parses a Text field
* @param field The Calendar field
* @param definingCalendar The Calendar to use
* @param locale The Locale to use
*/
TextStrategy(final int field, final Calendar definingCalendar, final Locale locale) {
this.field= field;
this.locale= locale;
this.keyValues= getDisplayNames(field, definingCalendar, locale);
this.lKeyValues= new HashMap<String,Integer>();
for(Map.Entry<String, Integer> entry : keyValues.entrySet()) {
lKeyValues.put(entry.getKey().toLowerCase(locale), entry.getValue());
}
}
/**
* {@inheritDoc}
*/
@Override
boolean addRegex(final FastDateParser parser, final StringBuilder regex) {
regex.append("((?iu)");
for(final String textKeyValue : keyValues.keySet()) {
escapeRegex(regex, textKeyValue, false).append('|');
}
regex.setCharAt(regex.length()-1, ')');
return true;
}
/**
* {@inheritDoc}
*/
@Override
void setCalendar(final FastDateParser parser, final Calendar cal, final String value) {
final Integer iVal = lKeyValues.get(value.toLowerCase(locale));
if(iVal == null) {
final StringBuilder sb= new StringBuilder(value);
sb.append(" not in (");
for(final String textKeyValue : keyValues.keySet()) {
sb.append(textKeyValue).append(' ');
}
sb.setCharAt(sb.length()-1, ')');
throw new IllegalArgumentException(sb.toString());
}
cal.set(field, iVal.intValue());
}
}
/**
* A strategy that handles a number field in the parsing pattern
*/
private static class NumberStrategy extends Strategy {
private final int field;
/**
* Construct a Strategy that parses a Number field
* @param field The Calendar field
*/
NumberStrategy(final int field) {
this.field= field;
}
/**
* {@inheritDoc}
*/
@Override
boolean isNumber() {
return true;
}
/**
* {@inheritDoc}
*/
@Override
boolean addRegex(final FastDateParser parser, final StringBuilder regex) {
// See LANG-954: We use {Nd} rather than {IsNd} because Android does not support the Is prefix
if(parser.isNextNumber()) {
regex.append("(\\p{Nd}{").append(parser.getFieldWidth()).append("}+)");
}
else {
regex.append("(\\p{Nd}++)");
}
return true;
}
/**
* {@inheritDoc}
*/
@Override
void setCalendar(final FastDateParser parser, final Calendar cal, final String value) {
cal.set(field, modify(Integer.parseInt(value)));
}
/**
* Make any modifications to parsed integer
* @param iValue The parsed integer
* @return The modified value
*/
int modify(final int iValue) {
return iValue;
}
}
private static final Strategy ABBREVIATED_YEAR_STRATEGY = new NumberStrategy(Calendar.YEAR) {
/**
* {@inheritDoc}
*/
@Override
void setCalendar(final FastDateParser parser, final Calendar cal, final String value) {
int iValue= Integer.parseInt(value);
if(iValue<100) {
iValue= parser.adjustYear(iValue);
}
cal.set(Calendar.YEAR, iValue);
}
};
/**
* A strategy that handles a timezone field in the parsing pattern
*/
private static class TimeZoneStrategy extends Strategy {
private final String validTimeZoneChars;
private final SortedMap<String, TimeZone> tzNames= new TreeMap<String, TimeZone>(String.CASE_INSENSITIVE_ORDER);
/**
* Index of zone id
*/
private static final int ID = 0;
/**
* Index of the long name of zone in standard time
*/
private static final int LONG_STD = 1;
/**
* Index of the short name of zone in standard time
*/
private static final int SHORT_STD = 2;
/**
* Index of the long name of zone in daylight saving time
*/
private static final int LONG_DST = 3;
/**
* Index of the short name of zone in daylight saving time
*/
private static final int SHORT_DST = 4;
/**
* Construct a Strategy that parses a TimeZone
* @param locale The Locale
*/
TimeZoneStrategy(final Locale locale) {
final String[][] zones = DateFormatSymbols.getInstance(locale).getZoneStrings();
for (String[] zone : zones) {
if (zone[ID].startsWith("GMT")) {
continue;
}
final TimeZone tz = TimeZone.getTimeZone(zone[ID]);
if (!tzNames.containsKey(zone[LONG_STD])){
tzNames.put(zone[LONG_STD], tz);
}
if (!tzNames.containsKey(zone[SHORT_STD])){
tzNames.put(zone[SHORT_STD], tz);
}
if (tz.useDaylightTime()) {
if (!tzNames.containsKey(zone[LONG_DST])){
tzNames.put(zone[LONG_DST], tz);
}
if (!tzNames.containsKey(zone[SHORT_DST])){
tzNames.put(zone[SHORT_DST], tz);
}
}
}
final StringBuilder sb= new StringBuilder();
sb.append("(GMT[+\\-]\\d{0,1}\\d{2}|[+\\-]\\d{2}:?\\d{2}|");
for(final String id : tzNames.keySet()) {
escapeRegex(sb, id, false).append('|');
}
sb.setCharAt(sb.length()-1, ')');
validTimeZoneChars= sb.toString();
}
/**
* {@inheritDoc}
*/
@Override
boolean addRegex(final FastDateParser parser, final StringBuilder regex) {
regex.append(validTimeZoneChars);
return true;
}
/**
* {@inheritDoc}
*/
@Override
void setCalendar(final FastDateParser parser, final Calendar cal, final String value) {
TimeZone tz;
if(value.charAt(0)=='+' || value.charAt(0)=='-') {
tz= TimeZone.getTimeZone("GMT"+value);
}
else if(value.startsWith("GMT")) {
tz= TimeZone.getTimeZone(value);
}
else {
tz= tzNames.get(value);
if(tz==null) {
throw new IllegalArgumentException(value + " is not a supported timezone name");
}
}
cal.setTimeZone(tz);
}
}
private static final Strategy NUMBER_MONTH_STRATEGY = new NumberStrategy(Calendar.MONTH) {
@Override
int modify(final int iValue) {
return iValue-1;
}
};
private static final Strategy LITERAL_YEAR_STRATEGY = new NumberStrategy(Calendar.YEAR);
private static final Strategy WEEK_OF_YEAR_STRATEGY = new NumberStrategy(Calendar.WEEK_OF_YEAR);
private static final Strategy WEEK_OF_MONTH_STRATEGY = new NumberStrategy(Calendar.WEEK_OF_MONTH);
private static final Strategy DAY_OF_YEAR_STRATEGY = new NumberStrategy(Calendar.DAY_OF_YEAR);
private static final Strategy DAY_OF_MONTH_STRATEGY = new NumberStrategy(Calendar.DAY_OF_MONTH);
private static final Strategy DAY_OF_WEEK_IN_MONTH_STRATEGY = new NumberStrategy(Calendar.DAY_OF_WEEK_IN_MONTH);
private static final Strategy HOUR_OF_DAY_STRATEGY = new NumberStrategy(Calendar.HOUR_OF_DAY);
private static final Strategy MODULO_HOUR_OF_DAY_STRATEGY = new NumberStrategy(Calendar.HOUR_OF_DAY) {
@Override
int modify(final int iValue) {
return iValue%24;
}
};
private static final Strategy MODULO_HOUR_STRATEGY = new NumberStrategy(Calendar.HOUR) {
@Override
int modify(final int iValue) {
return iValue%12;
}
};
private static final Strategy HOUR_STRATEGY = new NumberStrategy(Calendar.HOUR);
private static final Strategy MINUTE_STRATEGY = new NumberStrategy(Calendar.MINUTE);
private static final Strategy SECOND_STRATEGY = new NumberStrategy(Calendar.SECOND);
private static final Strategy MILLISECOND_STRATEGY = new NumberStrategy(Calendar.MILLISECOND);
}
| Rename TextStrategy to CaseInsensitiveTextStrategy per sebb's suggestion
git-svn-id: bab3daebc4e66440cbcc4aded890e63215874748@1590054 13f79535-47bb-0310-9956-ffa450edef68
| src/main/java/org/apache/commons/lang3/time/FastDateParser.java | Rename TextStrategy to CaseInsensitiveTextStrategy per sebb's suggestion |
|
Java | apache-2.0 | dfdbbb93351fc8d2f33ee5e07af7b2f66f4edcbd | 0 | google/oss-fuzz,google/oss-fuzz,google/oss-fuzz,google/oss-fuzz,google/oss-fuzz,google/oss-fuzz,google/oss-fuzz,google/oss-fuzz,google/oss-fuzz,google/oss-fuzz,google/oss-fuzz | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
import com.code_intelligence.jazzer.api.FuzzedDataProvider;
import java.util.*;
import java.util.regex.Pattern;
import java.io.Reader;
import java.io.StringReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.FileOutputStream;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.File;
import java.io.InputStream;
import java.io.DataInput;
import java.io.EOFException;
import java.lang.IllegalArgumentException;
import java.net.URI;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.DeserializationConfig;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.TreeNode;
import com.fasterxml.jackson.core.filter.TokenFilter;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.JsonNode;
import java.lang.ClassCastException;
import com.fasterxml.jackson.core.json.JsonReadFeature;
// For NoCheckSubTypeValidator
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.cfg.MapperConfig;
import com.fasterxml.jackson.databind.jsontype.PolymorphicTypeValidator;
public class AdaLObjectReader3Fuzzer {
public static void fuzzerTestOneInput(FuzzedDataProvider data) {
boolean doThis;
byte[] fileData;
int fuzzInt1, fuzzInt2;
FileOutputStream out;
Object o;
Reader stringR;
ObjectReader r, r2, r3;
JsonParser jp;
MapperFeature[] mapperfeatures = new MapperFeature[]{MapperFeature.AUTO_DETECT_CREATORS,
MapperFeature.AUTO_DETECT_FIELDS,
MapperFeature.AUTO_DETECT_GETTERS,
MapperFeature.AUTO_DETECT_IS_GETTERS,
MapperFeature.AUTO_DETECT_SETTERS,
MapperFeature.REQUIRE_SETTERS_FOR_GETTERS,
MapperFeature.USE_GETTERS_AS_SETTERS,
MapperFeature.INFER_CREATOR_FROM_CONSTRUCTOR_PROPERTIES,
MapperFeature.INFER_PROPERTY_MUTATORS,
MapperFeature.ALLOW_FINAL_FIELDS_AS_MUTATORS,
MapperFeature.ALLOW_VOID_VALUED_PROPERTIES,
MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS,
MapperFeature.OVERRIDE_PUBLIC_ACCESS_MODIFIERS,
MapperFeature.SORT_PROPERTIES_ALPHABETICALLY,
MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME,
MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS,
MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS,
MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES,
MapperFeature.ACCEPT_CASE_INSENSITIVE_VALUES,
MapperFeature.ALLOW_EXPLICIT_PROPERTY_RENAMING,
MapperFeature.USE_STD_BEAN_NAMING,
MapperFeature.ALLOW_COERCION_OF_SCALARS,
MapperFeature.DEFAULT_VIEW_INCLUSION,
MapperFeature.IGNORE_DUPLICATE_MODULE_REGISTRATIONS,
MapperFeature.IGNORE_MERGE_FOR_UNMERGEABLE,
MapperFeature.USE_BASE_TYPE_AS_DEFAULT_IMPL,
MapperFeature.USE_STATIC_TYPING,
MapperFeature.BLOCK_UNSAFE_POLYMORPHIC_BASE_TYPES};
SerializationFeature[] serializationfeatures = new SerializationFeature[]{SerializationFeature.INDENT_OUTPUT,
SerializationFeature.CLOSE_CLOSEABLE,
SerializationFeature.WRAP_ROOT_VALUE,
SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS,
SerializationFeature.WRITE_CHAR_ARRAYS_AS_JSON_ARRAYS,
SerializationFeature.WRITE_ENUMS_USING_TO_STRING,
SerializationFeature.WRITE_ENUMS_USING_INDEX,
SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED,
SerializationFeature.WRITE_BIGDECIMAL_AS_PLAIN,
SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS,
SerializationFeature.USE_EQUALITY_FOR_OBJECT_ID,
SerializationFeature.FAIL_ON_EMPTY_BEANS,
SerializationFeature.WRAP_EXCEPTIONS,
SerializationFeature.FLUSH_AFTER_WRITE_VALUE,
SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,
SerializationFeature.WRITE_NULL_MAP_VALUES,
SerializationFeature.WRITE_EMPTY_JSON_ARRAYS,
SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS,
SerializationFeature.EAGER_SERIALIZER_FETCH};
DeserializationFeature[] deserializationfeatures = new DeserializationFeature[]{DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS,
DeserializationFeature.USE_BIG_INTEGER_FOR_INTS,
DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY,
DeserializationFeature.READ_ENUMS_USING_TO_STRING,
DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY,
DeserializationFeature.UNWRAP_ROOT_VALUE,
DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS,
DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT,
DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT,
DeserializationFeature.ACCEPT_FLOAT_AS_INT,
DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE,
DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS,
DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL,
DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE,
DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES,
DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
DeserializationFeature.FAIL_ON_INVALID_SUBTYPE,
DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES,
DeserializationFeature.FAIL_ON_NUMBERS_FOR_ENUMS,
DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY,
DeserializationFeature.FAIL_ON_UNRESOLVED_OBJECT_IDS,
DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES,
DeserializationFeature.WRAP_EXCEPTIONS,
DeserializationFeature.FAIL_ON_TRAILING_TOKENS,
DeserializationFeature.EAGER_DESERIALIZER_FETCH};
ObjectMapper.DefaultTyping[] typings = new ObjectMapper.DefaultTyping[]{ObjectMapper.DefaultTyping.JAVA_LANG_OBJECT,
ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE,
ObjectMapper.DefaultTyping.NON_CONCRETE_AND_ARRAYS,
ObjectMapper.DefaultTyping.NON_FINAL,
ObjectMapper.DefaultTyping.EVERYTHING};
JsonReadFeature[] rfeatures = new JsonReadFeature[]{JsonReadFeature.ALLOW_JAVA_COMMENTS,
JsonReadFeature.ALLOW_YAML_COMMENTS,
JsonReadFeature.ALLOW_SINGLE_QUOTES,
JsonReadFeature.ALLOW_UNQUOTED_FIELD_NAMES,
JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS,
JsonReadFeature.ALLOW_LEADING_ZEROS_FOR_NUMBERS,
JsonReadFeature.ALLOW_LEADING_PLUS_SIGN_FOR_NUMBERS,
JsonReadFeature.ALLOW_LEADING_DECIMAL_POINT_FOR_NUMBERS,
JsonReadFeature.ALLOW_TRAILING_DECIMAL_POINT_FOR_NUMBERS,
JsonReadFeature.ALLOW_NON_NUMERIC_NUMBERS,
JsonReadFeature.ALLOW_MISSING_VALUES,
JsonReadFeature.ALLOW_TRAILING_COMMA};
ObjectMapper mapper = new ObjectMapper();
// Maybe create a mapper with different typing settings. Let the fuzzer decide
doThis = data.consumeBoolean();
if (doThis) {
JsonMapper.Builder b = JsonMapper.builder();
for (int i = 0; i < typings.length; i++) {
if (data.consumeBoolean()) {
b.activateDefaultTyping(NoCheckSubTypeValidator.instance, typings[i]);
}
}
mapper = b.build();
}
for (int i = 0; i < mapperfeatures.length; i++) {
if (data.consumeBoolean()) {
mapper.enable(mapperfeatures[i]);
} else {
mapper.disable(mapperfeatures[i]);
}
}
for (int i = 0; i < serializationfeatures.length; i++) {
if (data.consumeBoolean()) {
mapper.enable(serializationfeatures[i]);
} else {
mapper.disable(serializationfeatures[i]);
}
}
if (data.consumeBoolean()) {
DeserializationConfig config = mapper.getDeserializationConfig();
for (int i = 0; i < rfeatures.length; i++) {
if (data.consumeBoolean()) {
config = config.with(rfeatures[i]);
} else {
config = config.without(rfeatures[i]);
}
}
mapper.setConfig(config);
}
int idx = data.consumeInt(0, classes.length - 1);
r = mapper.readerFor(classes[idx]); // To initialize
switch (data.consumeInt(0, 4)) {
case 0:
r = mapper.readerFor(classes[idx]);
case 1:
r = mapper.readerForMapOf(classes[idx]);
case 2:
r = mapper.readerForListOf(classes[idx]);
case 3:
r = mapper.readerForArrayOf(classes[idx]);
case 4:
fuzzInt1 = data.consumeInt(0, classes.length - 1);
r = r.forType(mapper.constructType(classes[fuzzInt1]));
}
// set reader settings
for (int i = 0; i < deserializationfeatures.length; i++) {
if (data.consumeBoolean()) {
r = r.with(deserializationfeatures[i]);
} else {
r = r.without(deserializationfeatures[i]);
}
}
try {
// Select a method and call it
int callType = data.consumeInt();
switch (callType%7) {
case 0:
// readValue
switch (data.consumeInt(0, 14)){
case 0:
r.readValue(data.consumeString(100000));
case 1:
r.readValue(new MockFuzzDataInput(data.consumeString(100000)));
case 2:
r.readValue(data.consumeBytes(100000));
case 3:
jp = _createParser(data, mapper, r);
o = r.readValue(jp);
doThis = data.consumeBoolean();
if (doThis) {
r3 = r.withValueToUpdate(o);
}
case 4:
jp = _createParser(data, mapper, r);
fuzzInt1 = data.consumeInt(0, classes.length - 1);
r.readValue(jp, mapper.constructType(classes[fuzzInt1]));
case 5:
jp = _createParser(data, mapper, r);
fuzzInt1 = data.consumeInt(0, classes.length - 1);
r.readValue(jp, classes[fuzzInt1]);
case 6:
stringR = new StringReader(new String(data.consumeBytes(100000)));
r.readValue(stringR);
case 7:
fileData = data.consumeRemainingAsBytes();
out = new FileOutputStream("fuzzFile");
out.write(fileData);
out.close();
r.readValue(new File("fuzzFile"));
case 8:
fuzzInt1 = data.consumeInt();
fuzzInt2 = data.consumeInt();
r.readValue(data.consumeBytes(100000), fuzzInt1, fuzzInt2);
case 9:
fuzzInt1 = data.consumeInt(0, classes.length - 1);
r.readValue(data.consumeBytes(100000), classes[idx]);
case 10:
fuzzInt1 = data.consumeInt(0, classes.length - 1);
r.readValue(data.consumeString(100000), classes[idx]);
case 11:
fuzzInt1 = data.consumeInt(0, classes.length - 1);
mapper.readValue(data.consumeBytes(1000000), data.consumeInt(), data.consumeInt(), classes[fuzzInt1]);
case 12:
fuzzInt1 = data.consumeInt(0, classes.length - 1);
mapper.readValue(data.consumeBytes(1000000), mapper.constructType(classes[fuzzInt1]));
case 13:
fuzzInt1 = data.consumeInt(0, classes.length - 1);
mapper.readValue(data.consumeString(1000000), mapper.constructType(classes[fuzzInt1]));
case 14:
r.readValue(new ByteArrayInputStream(data.consumeBytes(100000)));
}
case 1:
// readTree
switch (data.consumeInt(0, 7)){
case 0:
jp = _createParser(data, mapper, r);
o = r.readTree(jp);
if (data.consumeBoolean()) {
r3 = r.withValueToUpdate(o);
}
case 1:
r.readTree(data.consumeString(100000));
case 2:
r.readTree(data.consumeBytes(100000));
case 3:
stringR = new StringReader(new String(data.consumeRemainingAsBytes()));
r.readTree(stringR);
case 4:
fuzzInt1 = data.consumeInt();
fuzzInt2 = data.consumeInt();
r.readTree(data.consumeRemainingAsBytes(), fuzzInt1, fuzzInt2);
case 5:
mapper.readTree(data.consumeBytes(1000000));
case 6:
mapper.readTree(data.consumeString(1000000));
case 7:
fuzzInt1 = data.consumeInt(0, classes.length - 1);
switch (data.consumeInt(0,1)) {
case 0:
r.readValue(data.consumeRemainingAsBytes(), classes[fuzzInt1]);
case 1:
r.readValue(data.consumeRemainingAsString(), classes[fuzzInt1]);
}
}
case 2:
// readValues
switch (data.consumeInt(0, 8)){
case 0:
stringR = new StringReader(new String(data.consumeRemainingAsBytes()));
r.readValues(stringR);
case 1:
r.readValues(data.consumeRemainingAsString());
case 2:
doThis = data.consumeBoolean();
jp = _createParser(data, mapper, r);
o = r.readValues(jp);
if (doThis) {
r3 = r.withValueToUpdate(o);
}
case 3:
fileData = data.consumeRemainingAsBytes();
out = new FileOutputStream("fuzzFile");
out.write(fileData);
out.close();
r.readValues(new File("fuzzFile"));
case 4:
fuzzInt1 = data.consumeInt();
fuzzInt2 = data.consumeInt();
r.readValues(data.consumeBytes(1000000), fuzzInt1, fuzzInt2);
case 5:
fuzzInt1 = data.consumeInt(0, classes.length - 1);
jp = _createParser(data, mapper, r);
mapper.readValues(jp, mapper.constructType(classes[fuzzInt1]));
case 6:
fuzzInt1 = data.consumeInt(0, classes.length - 1);
jp = _createParser(data, mapper, r);
mapper.readValues(jp, classes[fuzzInt1]);
case 7:
r.readValues(new MockFuzzDataInput(data.consumeString(1000000)));
case 8:
r.readValues(new ByteArrayInputStream(data.consumeBytes(100000)));
}
case 3:
fuzzInt1 = data.consumeInt(0, classes.length - 1);
fuzzInt2 = data.consumeInt(0, classes.length - 1);
mapper.addMixIn(classes[fuzzInt1], classes[fuzzInt2]);
case 4:
JsonNode tree = mapper.readTree(data.consumeString(1000000));
JsonNode node = tree.at(data.consumeString(1000000));
doThis = data.consumeBoolean();
if (doThis) {
fuzzInt1 = data.consumeInt(0, classes.length - 1);
mapper.treeToValue(node, classes[fuzzInt1]);
}
doThis = data.consumeBoolean();
if (doThis) {
fuzzInt1 = data.consumeInt(0, classes.length - 1);
mapper.treeToValue(node, mapper.constructType(classes[fuzzInt1]));
}
doThis = data.consumeBoolean();
if (doThis) {
r.readValue(node);
}
doThis = data.consumeBoolean();
fuzzInt1 = data.consumeInt(0, classes.length - 1);
if (doThis) {
r.readValue(node, classes[fuzzInt1]);
}
case 5:
switch (data.consumeInt(0, 2)){
case 0:
mapper.readTree(new ByteArrayInputStream(data.consumeBytes(100000)));
case 1:
ObjectNode src = (ObjectNode) mapper.readTree(data.consumeString(100000));
TreeNode tn = src;
fuzzInt1 = data.consumeInt(0, classes.length - 1);
mapper.treeToValue(tn, classes[fuzzInt1]);
case 2:
r.readTree(new MockFuzzDataInput(data.consumeString(100000)));
}
case 6:
fuzzInt1 = data.consumeInt(0, classes.length - 1);
mapper.canSerialize(classes[fuzzInt1]);
}
// target with();
if (data.consumeBoolean()) {
JsonFactory jf = new JsonFactory();
r2 = r.with(jf);
}
} catch (IOException | IllegalArgumentException | ClassCastException e) { }
try {
Files.delete(Paths.get("fuzzFile"));
} catch (IOException e) { }
}
public static JsonParser _createParser(FuzzedDataProvider data, ObjectMapper mapper, ObjectReader r) throws IOException {
int fuzzInt1, fuzzInt2;
byte[] fileData;
switch (data.consumeInt(0, 6)) {
case 0:
return r.createParser(data.consumeBytes(100000));
case 1:
fileData = data.consumeBytes(100000);
FileOutputStream out = new FileOutputStream("fuzzFile");
out.write(fileData);
out.close();
return r.createParser(new File("fuzzFile"));
case 2:
fuzzInt1 = data.consumeInt();
fuzzInt2 = data.consumeInt();
return r.createParser(data.consumeBytes(100000), fuzzInt1, fuzzInt2);
case 3:
mapper.createParser(data.consumeBytes(100000));
case 4:
return mapper.createParser(data.consumeString(1000000));
case 5:
fuzzInt1 = data.consumeInt();
fuzzInt2 = data.consumeInt();
return mapper.createParser(data.consumeBytes(100000), fuzzInt1, fuzzInt2);
case 6:
return r.createParser(new ByteArrayInputStream(data.consumeBytes(100000)));
}
return r.createParser(data.consumeBytes(100000));
}
public static Class[] classes = { DummyClass.class, Integer.class, String.class, Byte.class, List.class, Map.class,
TreeMap.class, BitSet.class, TimeZone.class, Date.class, Calendar.class, Locale.class, Long.class };
public static class DummyClass {
public TreeMap<String, Integer> _treeMap;
public List<String> _arrayList;
public Set<String> _hashSet;
public Map<String, Object> _hashMap;
public List<Integer> _asList = Arrays.asList(1, 2, 3);
public int[] _intArray;
public long[] _longArray;
public short[] _shortArray;
public float[] _floatArray;
public double[] _doubleArray;
public byte[] _byteArray;
public char[] _charArray;
public String[] _stringArray;
public BitSet _bitSet;
public Date _date;
public TimeZone _timeZone;
public Calendar _calendar;
public Locale _locale;
public Integer[] _integerArray;
public boolean _boolean;
public char _char;
public byte _byte;
public short _short;
public int _int;
public float _float;
public Long _long;
public Double _double;
}
// Test util classes
public static final class NoCheckSubTypeValidator
extends PolymorphicTypeValidator.Base
{
private static final long serialVersionUID = 1L;
public static final NoCheckSubTypeValidator instance = new NoCheckSubTypeValidator();
@Override
public Validity validateBaseType(MapperConfig<?> config, JavaType baseType) {
return Validity.INDETERMINATE;
}
@Override
public Validity validateSubClassName(MapperConfig<?> config,
JavaType baseType, String subClassName) {
return Validity.ALLOWED;
}
@Override
public Validity validateSubType(MapperConfig<?> config, JavaType baseType,
JavaType subType) {
return Validity.ALLOWED;
}
}
public static class MockFuzzDataInput implements DataInput
{
private final InputStream _input;
public MockFuzzDataInput(byte[] data) {
_input = new ByteArrayInputStream(data);
}
public MockFuzzDataInput(String utf8Data) throws IOException {
_input = new ByteArrayInputStream(utf8Data.getBytes("UTF-8"));
}
public MockFuzzDataInput(InputStream in) {
_input = in;
}
@Override
public void readFully(byte[] b) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public void readFully(byte[] b, int off, int len) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public int skipBytes(int n) throws IOException {
return (int) _input.skip(n);
}
@Override
public boolean readBoolean() throws IOException {
throw new UnsupportedOperationException();
}
@Override
public byte readByte() throws IOException {
int ch = _input.read();
if (ch < 0) {
throw new EOFException("End-of-input for readByte()");
}
return (byte) ch;
}
@Override
public int readUnsignedByte() throws IOException {
return readByte() & 0xFF;
}
@Override
public short readShort() throws IOException {
throw new UnsupportedOperationException();
}
@Override
public int readUnsignedShort() throws IOException {
throw new UnsupportedOperationException();
}
@Override
public char readChar() throws IOException {
throw new UnsupportedOperationException();
}
@Override
public int readInt() throws IOException {
throw new UnsupportedOperationException();
}
@Override
public long readLong() throws IOException {
throw new UnsupportedOperationException();
}
@Override
public float readFloat() throws IOException {
throw new UnsupportedOperationException();
}
@Override
public double readDouble() throws IOException {
throw new UnsupportedOperationException();
}
@Override
public String readLine() throws IOException {
throw new UnsupportedOperationException();
}
@Override
public String readUTF() throws IOException {
throw new UnsupportedOperationException();
}
}
}
| projects/jackson-databind/AdaLObjectReader3Fuzzer.java | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
import com.code_intelligence.jazzer.api.FuzzedDataProvider;
import java.util.*;
import java.util.regex.Pattern;
import java.io.Reader;
import java.io.StringReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.FileOutputStream;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.File;
import java.io.InputStream;
import java.io.DataInput;
import java.io.EOFException;
import java.lang.IllegalArgumentException;
import java.net.URI;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.TreeNode;
import com.fasterxml.jackson.core.filter.TokenFilter;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.JsonNode;
import java.lang.ClassCastException;
// For NoCheckSubTypeValidator
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.cfg.MapperConfig;
import com.fasterxml.jackson.databind.jsontype.PolymorphicTypeValidator;
public class AdaLObjectReader3Fuzzer {
public static void fuzzerTestOneInput(FuzzedDataProvider data) {
boolean doThis;
byte[] fileData;
int fuzzInt1, fuzzInt2;
FileOutputStream out;
Object o;
Reader stringR;
ObjectReader r, r2, r3;
JsonParser jp;
MapperFeature[] mapperfeatures = new MapperFeature[]{MapperFeature.AUTO_DETECT_CREATORS,
MapperFeature.AUTO_DETECT_FIELDS,
MapperFeature.AUTO_DETECT_GETTERS,
MapperFeature.AUTO_DETECT_IS_GETTERS,
MapperFeature.AUTO_DETECT_SETTERS,
MapperFeature.REQUIRE_SETTERS_FOR_GETTERS,
MapperFeature.USE_GETTERS_AS_SETTERS,
MapperFeature.INFER_CREATOR_FROM_CONSTRUCTOR_PROPERTIES,
MapperFeature.INFER_PROPERTY_MUTATORS,
MapperFeature.ALLOW_FINAL_FIELDS_AS_MUTATORS,
MapperFeature.ALLOW_VOID_VALUED_PROPERTIES,
MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS,
MapperFeature.OVERRIDE_PUBLIC_ACCESS_MODIFIERS,
MapperFeature.SORT_PROPERTIES_ALPHABETICALLY,
MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME,
MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS,
MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS,
MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES,
MapperFeature.ACCEPT_CASE_INSENSITIVE_VALUES,
MapperFeature.ALLOW_EXPLICIT_PROPERTY_RENAMING,
MapperFeature.USE_STD_BEAN_NAMING,
MapperFeature.ALLOW_COERCION_OF_SCALARS,
MapperFeature.DEFAULT_VIEW_INCLUSION,
MapperFeature.IGNORE_DUPLICATE_MODULE_REGISTRATIONS,
MapperFeature.IGNORE_MERGE_FOR_UNMERGEABLE,
MapperFeature.USE_BASE_TYPE_AS_DEFAULT_IMPL,
MapperFeature.USE_STATIC_TYPING,
MapperFeature.BLOCK_UNSAFE_POLYMORPHIC_BASE_TYPES};
SerializationFeature[] serializationfeatures = new SerializationFeature[]{SerializationFeature.INDENT_OUTPUT,
SerializationFeature.CLOSE_CLOSEABLE,
SerializationFeature.WRAP_ROOT_VALUE,
SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS,
SerializationFeature.WRITE_CHAR_ARRAYS_AS_JSON_ARRAYS,
SerializationFeature.WRITE_ENUMS_USING_TO_STRING,
SerializationFeature.WRITE_ENUMS_USING_INDEX,
SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED,
SerializationFeature.WRITE_BIGDECIMAL_AS_PLAIN,
SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS,
SerializationFeature.USE_EQUALITY_FOR_OBJECT_ID,
SerializationFeature.FAIL_ON_EMPTY_BEANS,
SerializationFeature.WRAP_EXCEPTIONS,
SerializationFeature.FLUSH_AFTER_WRITE_VALUE,
SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,
SerializationFeature.WRITE_NULL_MAP_VALUES,
SerializationFeature.WRITE_EMPTY_JSON_ARRAYS,
SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS,
SerializationFeature.EAGER_SERIALIZER_FETCH};
DeserializationFeature[] deserializationfeatures = new DeserializationFeature[]{DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS,
DeserializationFeature.USE_BIG_INTEGER_FOR_INTS,
DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY,
DeserializationFeature.READ_ENUMS_USING_TO_STRING,
DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY,
DeserializationFeature.UNWRAP_ROOT_VALUE,
DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS,
DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT,
DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT,
DeserializationFeature.ACCEPT_FLOAT_AS_INT,
DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE,
DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS,
DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL,
DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE,
DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES,
DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
DeserializationFeature.FAIL_ON_INVALID_SUBTYPE,
DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES,
DeserializationFeature.FAIL_ON_NUMBERS_FOR_ENUMS,
DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY,
DeserializationFeature.FAIL_ON_UNRESOLVED_OBJECT_IDS,
DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES,
DeserializationFeature.WRAP_EXCEPTIONS,
DeserializationFeature.FAIL_ON_TRAILING_TOKENS,
DeserializationFeature.EAGER_DESERIALIZER_FETCH};
ObjectMapper.DefaultTyping[] typings = new ObjectMapper.DefaultTyping[]{ObjectMapper.DefaultTyping.JAVA_LANG_OBJECT,
ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE,
ObjectMapper.DefaultTyping.NON_CONCRETE_AND_ARRAYS,
ObjectMapper.DefaultTyping.NON_FINAL,
ObjectMapper.DefaultTyping.EVERYTHING};
ObjectMapper mapper = new ObjectMapper();
// Maybe create a mapper with different typing settings. Let the fuzzer decide
doThis = data.consumeBoolean();
if (doThis) {
JsonMapper.Builder b = JsonMapper.builder();
for (int i = 0; i < typings.length; i++) {
if (data.consumeBoolean()) {
b.activateDefaultTyping(NoCheckSubTypeValidator.instance, typings[i]);
}
}
mapper = b.build();
}
for (int i = 0; i < mapperfeatures.length; i++) {
if (data.consumeBoolean()) {
mapper.enable(mapperfeatures[i]);
} else {
mapper.disable(mapperfeatures[i]);
}
}
for (int i = 0; i < serializationfeatures.length; i++) {
if (data.consumeBoolean()) {
mapper.enable(serializationfeatures[i]);
} else {
mapper.disable(serializationfeatures[i]);
}
}
int idx = data.consumeInt(0, classes.length - 1);
r = mapper.readerFor(classes[idx]); // To initialize-
switch (data.consumeInt(0, 4)) {
case 0:
r = mapper.readerFor(classes[idx]);
case 1:
r = mapper.readerForMapOf(classes[idx]);
case 2:
r = mapper.readerForListOf(classes[idx]);
case 3:
r = mapper.readerForArrayOf(classes[idx]);
case 4:
fuzzInt1 = data.consumeInt(0, classes.length - 1);
r = r.forType(mapper.constructType(classes[fuzzInt1]));
}
// set reader settings
for (int i = 0; i < deserializationfeatures.length; i++) {
if (data.consumeBoolean()) {
r = r.with(deserializationfeatures[i]);
} else {
r = r.without(deserializationfeatures[i]);
}
}
try {
// Select a method and call it
int callType = data.consumeInt();
switch (callType%7) {
case 0:
// readValue
switch (data.consumeInt(0, 12)){
case 0:
r.readValue(data.consumeString(100000));
case 1:
r.readValue(new MockFuzzDataInput(data.consumeString(100000)));
case 2:
r.readValue(data.consumeBytes(100000));
case 3:
jp = _createParser(data, mapper, r);
o = r.readValue(jp);
doThis = data.consumeBoolean();
if (doThis) {
r3 = r.withValueToUpdate(o);
}
case 4:
jp = _createParser(data, mapper, r);
fuzzInt1 = data.consumeInt(0, classes.length - 1);
r.readValue(jp, mapper.constructType(classes[fuzzInt1]));
case 5:
jp = _createParser(data, mapper, r);
fuzzInt1 = data.consumeInt(0, classes.length - 1);
r.readValue(jp, classes[fuzzInt1]);
case 6:
stringR = new StringReader(new String(data.consumeBytes(100000)));
r.readValue(stringR);
case 7:
fileData = data.consumeRemainingAsBytes();
out = new FileOutputStream("fuzzFile");
out.write(fileData);
out.close();
r.readValue(new File("fuzzFile"));
case 8:
fuzzInt1 = data.consumeInt();
fuzzInt2 = data.consumeInt();
r.readValue(data.consumeBytes(100000), fuzzInt1, fuzzInt2);
case 9:
fuzzInt1 = data.consumeInt(0, classes.length - 1);
r.readValue(data.consumeBytes(100000), classes[idx]);
case 10:
fuzzInt1 = data.consumeInt(0, classes.length - 1);
r.readValue(data.consumeString(100000), classes[idx]);
case 11:
fuzzInt1 = data.consumeInt(0, classes.length - 1);
mapper.readValue(data.consumeBytes(1000000), data.consumeInt(), data.consumeInt(), classes[fuzzInt1]);
case 12:
fuzzInt1 = data.consumeInt(0, classes.length - 1);
mapper.readValue(data.consumeBytes(1000000), mapper.constructType(classes[fuzzInt1]));
case 13:
fuzzInt1 = data.consumeInt(0, classes.length - 1);
mapper.readValue(data.consumeString(1000000), mapper.constructType(classes[fuzzInt1]));
}
case 1:
// readTree
switch (data.consumeInt(0, 6)){
case 0:
jp = _createParser(data, mapper, r);
o = r.readTree(jp);
if (data.consumeBoolean()) {
r3 = r.withValueToUpdate(o);
}
case 1:
r.readTree(data.consumeString(100000));
case 2:
r.readTree(data.consumeBytes(100000));
case 3:
stringR = new StringReader(new String(data.consumeRemainingAsBytes()));
r.readTree(stringR);
case 4:
fuzzInt1 = data.consumeInt();
fuzzInt2 = data.consumeInt();
r.readTree(data.consumeRemainingAsBytes(), fuzzInt1, fuzzInt2);
case 5:
mapper.readTree(data.consumeBytes(1000000));
case 6:
mapper.readTree(data.consumeString(1000000));
case 7:
fuzzInt1 = data.consumeInt(0, classes.length - 1);
switch (data.consumeInt(0,1)) {
case 0:
r.readValue(data.consumeRemainingAsBytes(), classes[fuzzInt1]);
case 1:
r.readValue(data.consumeRemainingAsString(), classes[fuzzInt1]);
}
}
case 2:
// readValues
switch (data.consumeInt(0, 7)){
case 0:
stringR = new StringReader(new String(data.consumeRemainingAsBytes()));
r.readValues(stringR);
case 1:
r.readValues(data.consumeRemainingAsString());
case 2:
doThis = data.consumeBoolean();
jp = _createParser(data, mapper, r);
o = r.readValues(jp);
if (doThis) {
r3 = r.withValueToUpdate(o);
}
case 3:
fileData = data.consumeRemainingAsBytes();
out = new FileOutputStream("fuzzFile");
out.write(fileData);
out.close();
r.readValues(new File("fuzzFile"));
case 4:
fuzzInt1 = data.consumeInt();
fuzzInt2 = data.consumeInt();
r.readValues(data.consumeBytes(1000000), fuzzInt1, fuzzInt2);
case 5:
fuzzInt1 = data.consumeInt(0, classes.length - 1);
jp = _createParser(data, mapper, r);
mapper.readValues(jp, mapper.constructType(classes[fuzzInt1]));
case 6:
fuzzInt1 = data.consumeInt(0, classes.length - 1);
jp = _createParser(data, mapper, r);
mapper.readValues(jp, classes[fuzzInt1]);
case 7:
r.readValues(new MockFuzzDataInput(data.consumeString(1000000)));
}
case 3:
fuzzInt1 = data.consumeInt(0, classes.length - 1);
fuzzInt2 = data.consumeInt(0, classes.length - 1);
mapper.addMixIn(classes[fuzzInt1], classes[fuzzInt2]);
case 4:
JsonNode tree = mapper.readTree(data.consumeString(1000000));
JsonNode node = tree.at(data.consumeString(1000000));
doThis = data.consumeBoolean();
if (doThis) {
fuzzInt1 = data.consumeInt(0, classes.length - 1);
mapper.treeToValue(node, classes[fuzzInt1]);
}
doThis = data.consumeBoolean();
if (doThis) {
fuzzInt1 = data.consumeInt(0, classes.length - 1);
mapper.treeToValue(node, mapper.constructType(classes[fuzzInt1]));
}
doThis = data.consumeBoolean();
if (doThis) {
r.readValue(node);
}
doThis = data.consumeBoolean();
fuzzInt1 = data.consumeInt(0, classes.length - 1);
if (doThis) {
r.readValue(node, classes[fuzzInt1]);
}
case 5:
switch (data.consumeInt(0, 1)){
case 0:
mapper.readTree(new ByteArrayInputStream(data.consumeBytes(100000)));
case 1:
ObjectNode src = (ObjectNode) mapper.readTree(data.consumeString(100000));
TreeNode tn = src;
fuzzInt1 = data.consumeInt(0, classes.length - 1);
mapper.treeToValue(tn, classes[fuzzInt1]);
case 2:
r.readTree(new MockFuzzDataInput(data.consumeString(100000)));
}
case 6:
fuzzInt1 = data.consumeInt(0, classes.length - 1);
mapper.canSerialize(classes[fuzzInt1]);
}
// target with();
if (data.consumeBoolean()) {
JsonFactory jf = new JsonFactory();
r2 = r.with(jf);
}
} catch (IOException | IllegalArgumentException | ClassCastException e) { }
try {
Files.delete(Paths.get("fuzzFile"));
} catch (IOException e) { }
}
public static JsonParser _createParser(FuzzedDataProvider data, ObjectMapper mapper, ObjectReader r) throws IOException {
int fuzzInt1, fuzzInt2;
byte[] fileData;
switch (data.consumeInt(0, 6)) {
case 0:
return r.createParser(data.consumeBytes(100000));
case 1:
fileData = data.consumeBytes(100000);
FileOutputStream out = new FileOutputStream("fuzzFile");
out.write(fileData);
out.close();
return r.createParser(new File("fuzzFile"));
case 2:
fuzzInt1 = data.consumeInt();
fuzzInt2 = data.consumeInt();
return r.createParser(data.consumeBytes(100000), fuzzInt1, fuzzInt2);
case 3:
mapper.createParser(data.consumeBytes(100000));
case 4:
return mapper.createParser(data.consumeString(1000000));
case 5:
fuzzInt1 = data.consumeInt();
fuzzInt2 = data.consumeInt();
return mapper.createParser(data.consumeBytes(100000), fuzzInt1, fuzzInt2);
}
return r.createParser(data.consumeBytes(100000));
}
public static Class[] classes = { DummyClass.class, Integer.class, String.class, Byte.class, List.class, Map.class,
TreeMap.class, BitSet.class, TimeZone.class, Date.class, Calendar.class, Locale.class, Long.class };
public static class DummyClass {
public TreeMap<String, Integer> _treeMap;
public List<String> _arrayList;
public Set<String> _hashSet;
public Map<String, Object> _hashMap;
public List<Integer> _asList = Arrays.asList(1, 2, 3);
public int[] _intArray;
public long[] _longArray;
public short[] _shortArray;
public float[] _floatArray;
public double[] _doubleArray;
public byte[] _byteArray;
public char[] _charArray;
public String[] _stringArray;
public BitSet _bitSet;
public Date _date;
public TimeZone _timeZone;
public Calendar _calendar;
public Locale _locale;
public Integer[] _integerArray;
public boolean _boolean;
public char _char;
public byte _byte;
public short _short;
public int _int;
public float _float;
public Long _long;
public Double _double;
}
// Test util classes
public static final class NoCheckSubTypeValidator
extends PolymorphicTypeValidator.Base
{
private static final long serialVersionUID = 1L;
public static final NoCheckSubTypeValidator instance = new NoCheckSubTypeValidator();
@Override
public Validity validateBaseType(MapperConfig<?> config, JavaType baseType) {
return Validity.INDETERMINATE;
}
@Override
public Validity validateSubClassName(MapperConfig<?> config,
JavaType baseType, String subClassName) {
return Validity.ALLOWED;
}
@Override
public Validity validateSubType(MapperConfig<?> config, JavaType baseType,
JavaType subType) {
return Validity.ALLOWED;
}
}
public static class MockFuzzDataInput implements DataInput
{
private final InputStream _input;
public MockFuzzDataInput(byte[] data) {
_input = new ByteArrayInputStream(data);
}
public MockFuzzDataInput(String utf8Data) throws IOException {
_input = new ByteArrayInputStream(utf8Data.getBytes("UTF-8"));
}
public MockFuzzDataInput(InputStream in) {
_input = in;
}
@Override
public void readFully(byte[] b) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public void readFully(byte[] b, int off, int len) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public int skipBytes(int n) throws IOException {
return (int) _input.skip(n);
}
@Override
public boolean readBoolean() throws IOException {
throw new UnsupportedOperationException();
}
@Override
public byte readByte() throws IOException {
int ch = _input.read();
if (ch < 0) {
throw new EOFException("End-of-input for readByte()");
}
return (byte) ch;
}
@Override
public int readUnsignedByte() throws IOException {
return readByte() & 0xFF;
}
@Override
public short readShort() throws IOException {
throw new UnsupportedOperationException();
}
@Override
public int readUnsignedShort() throws IOException {
throw new UnsupportedOperationException();
}
@Override
public char readChar() throws IOException {
throw new UnsupportedOperationException();
}
@Override
public int readInt() throws IOException {
throw new UnsupportedOperationException();
}
@Override
public long readLong() throws IOException {
throw new UnsupportedOperationException();
}
@Override
public float readFloat() throws IOException {
throw new UnsupportedOperationException();
}
@Override
public double readDouble() throws IOException {
throw new UnsupportedOperationException();
}
@Override
public String readLine() throws IOException {
throw new UnsupportedOperationException();
}
@Override
public String readUTF() throws IOException {
throw new UnsupportedOperationException();
}
}
}
| jackson-databind: improve fuzzer (#8834)
Adds a few more targets.
Improve formatting of the fuzzer.
Signed-off-by: AdamKorcz <[email protected]>
Signed-off-by: AdamKorcz <[email protected]> | projects/jackson-databind/AdaLObjectReader3Fuzzer.java | jackson-databind: improve fuzzer (#8834) |
|
Java | apache-2.0 | 277bb5345a708533ca84504f4895df87bf1435a1 | 0 | allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.formatter;
import com.intellij.formatting.*;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CommonCodeStyleSettings;
import com.intellij.psi.impl.source.tree.TreeUtil;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.ArrayUtil;
import com.jetbrains.python.PyElementTypes;
import com.jetbrains.python.PyTokenTypes;
import com.jetbrains.python.psi.*;
import com.jetbrains.python.psi.impl.PyPsiUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import static com.jetbrains.python.formatter.PyCodeStyleSettings.DICT_ALIGNMENT_ON_COLON;
import static com.jetbrains.python.formatter.PyCodeStyleSettings.DICT_ALIGNMENT_ON_VALUE;
import static com.jetbrains.python.formatter.PythonFormattingModelBuilder.STATEMENT_OR_DECLARATION;
import static com.jetbrains.python.psi.PyUtil.as;
/**
* @author yole
*/
public class PyBlock implements ASTBlock {
private static final TokenSet ourListElementTypes = TokenSet.create(PyElementTypes.LIST_LITERAL_EXPRESSION,
PyElementTypes.LIST_COMP_EXPRESSION,
PyElementTypes.DICT_LITERAL_EXPRESSION,
PyElementTypes.DICT_COMP_EXPRESSION,
PyElementTypes.SET_LITERAL_EXPRESSION,
PyElementTypes.SET_COMP_EXPRESSION,
PyElementTypes.ARGUMENT_LIST,
PyElementTypes.PARAMETER_LIST,
PyElementTypes.TUPLE_EXPRESSION,
PyElementTypes.PARENTHESIZED_EXPRESSION,
PyElementTypes.SLICE_EXPRESSION,
PyElementTypes.SUBSCRIPTION_EXPRESSION,
PyElementTypes.GENERATOR_EXPRESSION);
private static final TokenSet ourCollectionLiteralTypes = TokenSet.create(PyElementTypes.LIST_LITERAL_EXPRESSION,
PyElementTypes.LIST_COMP_EXPRESSION,
PyElementTypes.DICT_LITERAL_EXPRESSION,
PyElementTypes.DICT_COMP_EXPRESSION,
PyElementTypes.SET_LITERAL_EXPRESSION,
PyElementTypes.SET_COMP_EXPRESSION);
private static final TokenSet ourBrackets = TokenSet.create(PyTokenTypes.LPAR, PyTokenTypes.RPAR,
PyTokenTypes.LBRACE, PyTokenTypes.RBRACE,
PyTokenTypes.LBRACKET, PyTokenTypes.RBRACKET);
private static final TokenSet ourHangingIndentOwners = TokenSet.create(PyElementTypes.LIST_LITERAL_EXPRESSION,
PyElementTypes.LIST_COMP_EXPRESSION,
PyElementTypes.DICT_LITERAL_EXPRESSION,
PyElementTypes.DICT_COMP_EXPRESSION,
PyElementTypes.SET_LITERAL_EXPRESSION,
PyElementTypes.SET_COMP_EXPRESSION,
PyElementTypes.ARGUMENT_LIST,
PyElementTypes.PARAMETER_LIST,
PyElementTypes.TUPLE_EXPRESSION,
PyElementTypes.PARENTHESIZED_EXPRESSION,
PyElementTypes.GENERATOR_EXPRESSION,
PyElementTypes.FUNCTION_DECLARATION,
PyElementTypes.CALL_EXPRESSION,
PyElementTypes.FROM_IMPORT_STATEMENT);
public static final Key<Boolean> IMPORT_GROUP_BEGIN = Key.create("com.jetbrains.python.formatter.importGroupBegin");
private static final boolean ALIGN_CONDITIONS_WITHOUT_PARENTHESES = false;
private final PyBlock myParent;
private final Alignment myAlignment;
private final Indent myIndent;
private final ASTNode myNode;
private final Wrap myWrap;
private final PyBlockContext myContext;
private List<PyBlock> mySubBlocks = null;
private Map<ASTNode, PyBlock> mySubBlockByNode = null;
private final boolean myEmptySequence;
// Shared among multiple children sub-blocks
private Alignment myChildAlignment = null;
private Alignment myDictAlignment = null;
private Wrap myDictWrapping = null;
private Wrap myFromImportWrapping = null;
public PyBlock(@Nullable PyBlock parent,
@NotNull ASTNode node,
@Nullable Alignment alignment,
@NotNull Indent indent,
@Nullable Wrap wrap,
@NotNull PyBlockContext context) {
myParent = parent;
myAlignment = alignment;
myIndent = indent;
myNode = node;
myWrap = wrap;
myContext = context;
myEmptySequence = isEmptySequence(node);
final PyCodeStyleSettings pySettings = myContext.getPySettings();
if (node.getElementType() == PyElementTypes.DICT_LITERAL_EXPRESSION) {
myDictAlignment = Alignment.createAlignment(true);
myDictWrapping = Wrap.createWrap(pySettings.DICT_WRAPPING, true);
}
else if (node.getElementType() == PyElementTypes.FROM_IMPORT_STATEMENT) {
myFromImportWrapping = Wrap.createWrap(pySettings.FROM_IMPORT_WRAPPING, false);
}
}
@Override
@NotNull
public ASTNode getNode() {
return myNode;
}
@Override
@NotNull
public TextRange getTextRange() {
return myNode.getTextRange();
}
private Alignment getAlignmentForChildren() {
if (myChildAlignment == null) {
myChildAlignment = Alignment.createAlignment();
}
return myChildAlignment;
}
@Override
@NotNull
public List<Block> getSubBlocks() {
if (mySubBlocks == null) {
mySubBlockByNode = buildSubBlocks();
mySubBlocks = new ArrayList<>(mySubBlockByNode.values());
}
return Collections.unmodifiableList(mySubBlocks);
}
@Nullable
private PyBlock getSubBlockByNode(@NotNull ASTNode node) {
return mySubBlockByNode.get(node);
}
@Nullable
private PyBlock getSubBlockByIndex(int index) {
return mySubBlocks.get(index);
}
@NotNull
private Map<ASTNode, PyBlock> buildSubBlocks() {
final Map<ASTNode, PyBlock> blocks = new LinkedHashMap<>();
for (ASTNode child: getSubBlockNodes()) {
final IElementType childType = child.getElementType();
if (child.getTextRange().isEmpty()) continue;
if (childType == TokenType.WHITE_SPACE) {
continue;
}
blocks.put(child, buildSubBlock(child));
}
return Collections.unmodifiableMap(blocks);
}
@NotNull
protected Iterable<ASTNode> getSubBlockNodes() {
if (myNode.getElementType() == PyElementTypes.BINARY_EXPRESSION) {
final ArrayList<ASTNode> result = new ArrayList<>();
collectChildrenOperatorAndOperandNodes(myNode, result);
return result;
}
return Arrays.asList(myNode.getChildren(null));
}
private static void collectChildrenOperatorAndOperandNodes(@NotNull ASTNode node, @NotNull List<ASTNode> result) {
if (node.getElementType() == PyElementTypes.BINARY_EXPRESSION) {
for (ASTNode child : node.getChildren(null)) {
collectChildrenOperatorAndOperandNodes(child, result);
}
}
else {
result.add(node);
}
}
@NotNull
private PyBlock buildSubBlock(@NotNull ASTNode child) {
final IElementType parentType = myNode.getElementType();
final ASTNode grandParentNode = myNode.getTreeParent();
final IElementType grandparentType = grandParentNode == null ? null : grandParentNode.getElementType();
final IElementType childType = child.getElementType();
Wrap childWrap = null;
Indent childIndent = Indent.getNoneIndent();
Alignment childAlignment = null;
final PyCodeStyleSettings settings = myContext.getPySettings();
if (childType == PyElementTypes.STATEMENT_LIST) {
if (hasLineBreaksBeforeInSameParent(child, 1) || needLineBreakInStatement()) {
childIndent = Indent.getNormalIndent();
}
}
else if (childType == PyElementTypes.IMPORT_ELEMENT) {
if (parentType == PyElementTypes.FROM_IMPORT_STATEMENT) {
childWrap = myFromImportWrapping;
}
else {
childWrap = Wrap.createWrap(WrapType.NORMAL, true);
}
childIndent = Indent.getNormalIndent();
}
if (childType == PyTokenTypes.END_OF_LINE_COMMENT && parentType == PyElementTypes.FROM_IMPORT_STATEMENT) {
childIndent = Indent.getNormalIndent();
}
// TODO merge it with the following check of needListAlignment()
if (ourListElementTypes.contains(parentType)) {
// wrapping in non-parenthesized tuple expression is not allowed (PY-1792)
if ((parentType != PyElementTypes.TUPLE_EXPRESSION || grandparentType == PyElementTypes.PARENTHESIZED_EXPRESSION) &&
!ourBrackets.contains(childType) &&
childType != PyTokenTypes.COMMA &&
!isSliceOperand(child) /*&& !isSubscriptionOperand(child)*/) {
childWrap = Wrap.createWrap(WrapType.NORMAL, true);
}
if (needListAlignment(child) && !myEmptySequence) {
childAlignment = getAlignmentForChildren();
}
if (childType == PyTokenTypes.END_OF_LINE_COMMENT) {
childIndent = Indent.getNormalIndent();
}
}
if (parentType == PyElementTypes.BINARY_EXPRESSION) {
if (childType != PyElementTypes.BINARY_EXPRESSION) {
final PyBlock topmostBinary = findTopmostBinaryExpressionBlock(child);
assert topmostBinary != null;
final PyBlock binaryParentBlock = topmostBinary.myParent;
final ASTNode binaryParentNode = binaryParentBlock.myNode;
final IElementType binaryParentType = binaryParentNode.getElementType();
// TODO check for comprehensions explicitly here
if (ourListElementTypes.contains(binaryParentType) && needListAlignment(child) && !myEmptySequence) {
childAlignment = binaryParentBlock.getChildAlignment();
}
final boolean parenthesised = binaryParentType == PyElementTypes.PARENTHESIZED_EXPRESSION;
if (childAlignment == null && topmostBinary != null &&
!(parenthesised && isIfCondition(binaryParentNode)) &&
!(isCondition(topmostBinary.myNode) && !ALIGN_CONDITIONS_WITHOUT_PARENTHESES)) {
childAlignment = topmostBinary.getAlignmentForChildren();
}
// We omit indentation for the binary expression itself in this case (similarly to PyTupleExpression inside
// PyParenthesisedExpression) because we indent individual operands and operators inside rather than
// the whole contained expression.
childIndent = parenthesised ? Indent.getContinuationIndent() : Indent.getContinuationWithoutFirstIndent();
}
}
else if (parentType == PyElementTypes.LIST_LITERAL_EXPRESSION || parentType == PyElementTypes.LIST_COMP_EXPRESSION) {
if ((childType == PyTokenTypes.RBRACKET && !settings.HANG_CLOSING_BRACKETS) || childType == PyTokenTypes.LBRACKET) {
childIndent = Indent.getNoneIndent();
}
else {
childIndent = settings.USE_CONTINUATION_INDENT_FOR_COLLECTION_AND_COMPREHENSIONS ? Indent.getContinuationIndent() : Indent.getNormalIndent();
}
}
else if (parentType == PyElementTypes.DICT_LITERAL_EXPRESSION || parentType == PyElementTypes.SET_LITERAL_EXPRESSION ||
parentType == PyElementTypes.SET_COMP_EXPRESSION || parentType == PyElementTypes.DICT_COMP_EXPRESSION) {
if ((childType == PyTokenTypes.RBRACE && !settings.HANG_CLOSING_BRACKETS) || childType == PyTokenTypes.LBRACE) {
childIndent = Indent.getNoneIndent();
}
else {
childIndent = settings.USE_CONTINUATION_INDENT_FOR_COLLECTION_AND_COMPREHENSIONS ? Indent.getContinuationIndent() : Indent.getNormalIndent();
}
}
else if (parentType == PyElementTypes.STRING_LITERAL_EXPRESSION) {
if (PyTokenTypes.STRING_NODES.contains(childType)) {
childAlignment = getAlignmentForChildren();
}
}
else if (parentType == PyElementTypes.FROM_IMPORT_STATEMENT) {
if (myNode.findChildByType(PyTokenTypes.LPAR) != null) {
if (childType == PyElementTypes.IMPORT_ELEMENT) {
if (settings.ALIGN_MULTILINE_IMPORTS) {
childAlignment = getAlignmentForChildren();
}
else {
childIndent = Indent.getNormalIndent();
}
}
if (childType == PyTokenTypes.RPAR) {
childIndent = Indent.getNoneIndent();
// Don't have hanging indent and is not going to have it due to the setting about opening parenthesis
if (!hasHangingIndent(myNode.getPsi()) && !settings.FROM_IMPORT_NEW_LINE_AFTER_LEFT_PARENTHESIS) {
childAlignment = getAlignmentForChildren();
}
else if (settings.HANG_CLOSING_BRACKETS) {
childIndent = Indent.getNormalIndent();
}
}
}
}
else if (isValueOfKeyValuePair(child)) {
childIndent = Indent.getNormalIndent();
}
// TODO: merge with needChildAlignment()
//Align elements vertically if there is an argument in the first line of parenthesized expression
else if (!hasHangingIndent(myNode.getPsi()) &&
(parentType == PyElementTypes.PARENTHESIZED_EXPRESSION ||
(parentType == PyElementTypes.ARGUMENT_LIST && myContext.getSettings().ALIGN_MULTILINE_PARAMETERS_IN_CALLS) ||
(parentType == PyElementTypes.PARAMETER_LIST && myContext.getSettings().ALIGN_MULTILINE_PARAMETERS)) &&
!isIndentNext(child) &&
!hasLineBreaksBeforeInSameParent(myNode.getFirstChildNode(), 1) &&
!ourListElementTypes.contains(childType)) {
if (!ourBrackets.contains(childType)) {
childAlignment = getAlignmentForChildren();
if (parentType != PyElementTypes.CALL_EXPRESSION) {
childIndent = Indent.getNormalIndent();
}
}
else if (childType == PyTokenTypes.RPAR) {
childIndent = Indent.getNoneIndent();
}
}
// Note that colons are aligned together with bounds and stride
else if (myNode.getElementType() == PyElementTypes.SLICE_ITEM) {
childAlignment = getChildAlignment();
}
else if (parentType == PyElementTypes.GENERATOR_EXPRESSION || parentType == PyElementTypes.PARENTHESIZED_EXPRESSION) {
final boolean tupleOrGenerator = parentType == PyElementTypes.GENERATOR_EXPRESSION ||
myNode.getPsi(PyParenthesizedExpression.class).getContainedExpression() instanceof PyTupleExpression;
if ((childType == PyTokenTypes.RPAR && !(tupleOrGenerator && settings.HANG_CLOSING_BRACKETS)) ||
!hasLineBreaksBeforeInSameParent(child, 1)) {
childIndent = Indent.getNoneIndent();
}
// Operands and operators of a binary expression have their own indent, no need to increase it by indenting the expression itself
else if (childType == PyElementTypes.BINARY_EXPRESSION && parentType == PyElementTypes.PARENTHESIZED_EXPRESSION) {
childIndent = Indent.getNoneIndent();
}
else {
final boolean useWiderIndent = isIndentNext(child) || settings.USE_CONTINUATION_INDENT_FOR_COLLECTION_AND_COMPREHENSIONS;
childIndent = useWiderIndent ? Indent.getContinuationIndent() : Indent.getNormalIndent();
}
}
else if (parentType == PyElementTypes.ARGUMENT_LIST || parentType == PyElementTypes.PARAMETER_LIST) {
if (childType == PyTokenTypes.RPAR && !settings.HANG_CLOSING_BRACKETS) {
childIndent = Indent.getNoneIndent();
}
else if (parentType == PyElementTypes.PARAMETER_LIST ||
settings.USE_CONTINUATION_INDENT_FOR_ARGUMENTS ||
argumentMayHaveSameIndentAsFollowingStatementList()) {
childIndent = Indent.getContinuationIndent();
}
else {
childIndent = Indent.getNormalIndent();
}
}
else if (parentType == PyElementTypes.SUBSCRIPTION_EXPRESSION) {
final PyExpression indexExpression = ((PySubscriptionExpression)myNode.getPsi()).getIndexExpression();
if (indexExpression != null && child == indexExpression.getNode()) {
childIndent = Indent.getNormalIndent();
}
}
else if (parentType == PyElementTypes.REFERENCE_EXPRESSION) {
if (child != myNode.getFirstChildNode()) {
childIndent = Indent.getNormalIndent();
if (hasLineBreaksBeforeInSameParent(child, 1)) {
if (isInControlStatement()) {
childIndent = Indent.getContinuationIndent();
}
else {
PyBlock b = myParent;
while (b != null) {
if (b.getNode().getPsi() instanceof PyParenthesizedExpression ||
b.getNode().getPsi() instanceof PyArgumentList ||
b.getNode().getPsi() instanceof PyParameterList) {
childAlignment = getAlignmentOfChild(b, 1);
break;
}
b = b.myParent;
}
}
}
}
}
if (childType == PyElementTypes.KEY_VALUE_EXPRESSION && isChildOfDictLiteral(child)) {
childWrap = myDictWrapping;
}
if (isAfterStatementList(child) &&
!hasLineBreaksBeforeInSameParent(child, 2) &&
child.getElementType() != PyTokenTypes.END_OF_LINE_COMMENT) {
// maybe enter was pressed and cut us from a previous (nested) statement list
childIndent = Indent.getNormalIndent();
}
if (settings.DICT_ALIGNMENT == DICT_ALIGNMENT_ON_VALUE) {
// Align not the whole value but its left bracket if it starts with it
if (isValueOfKeyValuePairOfDictLiteral(child) && !isOpeningBracket(child.getFirstChildNode())) {
childAlignment = myParent.myDictAlignment;
}
else if (isValueOfKeyValuePairOfDictLiteral(myNode) && isOpeningBracket(child)) {
childAlignment = myParent.myParent.myDictAlignment;
}
}
else if (myContext.getPySettings().DICT_ALIGNMENT == DICT_ALIGNMENT_ON_COLON) {
if (isChildOfKeyValuePairOfDictLiteral(child) && childType == PyTokenTypes.COLON) {
childAlignment = myParent.myDictAlignment;
}
}
ASTNode prev = child.getTreePrev();
while (prev != null && prev.getElementType() == TokenType.WHITE_SPACE) {
if (prev.textContains('\\') &&
!childIndent.equals(Indent.getContinuationIndent(false)) &&
!childIndent.equals(Indent.getContinuationIndent(true))) {
childIndent = isIndentNext(child) ? Indent.getContinuationIndent() : Indent.getNormalIndent();
break;
}
prev = prev.getTreePrev();
}
return new PyBlock(this, child, childAlignment, childIndent, childWrap, myContext);
}
private static boolean isIfCondition(@NotNull ASTNode node) {
@NotNull PsiElement element = node.getPsi();
final PyIfPart ifPart = as(element.getParent(), PyIfPart.class);
return ifPart != null && ifPart.getCondition() == element && !ifPart.isElif();
}
private static boolean isCondition(@NotNull ASTNode node) {
final PsiElement element = node.getPsi();
final PyConditionalStatementPart conditionalStatement = as(element.getParent(), PyConditionalStatementPart.class);
return conditionalStatement != null && conditionalStatement.getCondition() == element;
}
@Nullable
private PyBlock findTopmostBinaryExpressionBlock(@NotNull ASTNode child) {
assert child.getElementType() != PyElementTypes.BINARY_EXPRESSION;
PyBlock parentBlock = this;
PyBlock alignmentOwner = null;
while (parentBlock != null && parentBlock.myNode.getElementType() == PyElementTypes.BINARY_EXPRESSION) {
alignmentOwner = parentBlock;
parentBlock = parentBlock.myParent;
}
return alignmentOwner;
}
private static boolean isOpeningBracket(@Nullable ASTNode node) {
return node != null && PyTokenTypes.OPEN_BRACES.contains(node.getElementType()) && node == node.getTreeParent().getFirstChildNode();
}
private static boolean isValueOfKeyValuePairOfDictLiteral(@NotNull ASTNode node) {
return isValueOfKeyValuePair(node) && isChildOfDictLiteral(node.getTreeParent());
}
private static boolean isChildOfKeyValuePairOfDictLiteral(@NotNull ASTNode node) {
return isChildOfKeyValuePair(node) && isChildOfDictLiteral(node.getTreeParent());
}
private static boolean isChildOfDictLiteral(@NotNull ASTNode node) {
final ASTNode nodeParent = node.getTreeParent();
return nodeParent != null && nodeParent.getElementType() == PyElementTypes.DICT_LITERAL_EXPRESSION;
}
private static boolean isChildOfKeyValuePair(@NotNull ASTNode node) {
final ASTNode nodeParent = node.getTreeParent();
return nodeParent != null && nodeParent.getElementType() == PyElementTypes.KEY_VALUE_EXPRESSION;
}
private static boolean isValueOfKeyValuePair(@NotNull ASTNode node) {
return isChildOfKeyValuePair(node) && node.getTreeParent().getPsi(PyKeyValueExpression.class).getValue() == node.getPsi();
}
private static boolean isEmptySequence(@NotNull ASTNode node) {
return node.getPsi() instanceof PySequenceExpression && ((PySequenceExpression)node.getPsi()).isEmpty();
}
private boolean argumentMayHaveSameIndentAsFollowingStatementList() {
if (myNode.getElementType() != PyElementTypes.ARGUMENT_LIST) {
return false;
}
// This check is supposed to prevent PEP8's error: Continuation line with the same indent as next logical line
final PsiElement header = getControlStatementHeader(myNode);
if (header instanceof PyStatementListContainer) {
final PyStatementList statementList = ((PyStatementListContainer)header).getStatementList();
return PyUtil.onSameLine(header, myNode.getPsi()) && !PyUtil.onSameLine(header, statementList);
}
return false;
}
// Check https://www.python.org/dev/peps/pep-0008/#indentation
private static boolean hasHangingIndent(@NotNull PsiElement elem) {
if (elem instanceof PyCallExpression) {
final PyArgumentList argumentList = ((PyCallExpression)elem).getArgumentList();
return argumentList != null && hasHangingIndent(argumentList);
}
else if (elem instanceof PyFunction) {
return hasHangingIndent(((PyFunction)elem).getParameterList());
}
final PsiElement firstChild;
if (elem instanceof PyFromImportStatement) {
firstChild = ((PyFromImportStatement)elem).getLeftParen();
}
else {
firstChild = elem.getFirstChild();
}
if (firstChild == null) {
return false;
}
final IElementType elementType = elem.getNode().getElementType();
final ASTNode firstChildNode = firstChild.getNode();
if (ourHangingIndentOwners.contains(elementType) && PyTokenTypes.OPEN_BRACES.contains(firstChildNode.getElementType())) {
if (hasLineBreakAfterIgnoringComments(firstChildNode)) {
return true;
}
final PsiElement firstItem = getFirstItem(elem);
if (firstItem == null) {
return !PyTokenTypes.CLOSE_BRACES.contains(elem.getLastChild().getNode().getElementType());
}
else {
if (firstItem instanceof PyNamedParameter) {
final PyExpression defaultValue = ((PyNamedParameter)firstItem).getDefaultValue();
return defaultValue != null && hasHangingIndent(defaultValue);
}
else if (firstItem instanceof PyKeywordArgument) {
final PyExpression valueExpression = ((PyKeywordArgument)firstItem).getValueExpression();
return valueExpression != null && hasHangingIndent(valueExpression);
}
else if (firstItem instanceof PyKeyValueExpression) {
final PyExpression value = ((PyKeyValueExpression)firstItem).getValue();
return value != null && hasHangingIndent(value);
}
return hasHangingIndent(firstItem);
}
}
else {
return false;
}
}
@Nullable
private static PsiElement getFirstItem(@NotNull PsiElement elem) {
PsiElement[] items = PsiElement.EMPTY_ARRAY;
if (elem instanceof PySequenceExpression) {
items = ((PySequenceExpression)elem).getElements();
}
else if (elem instanceof PyParameterList) {
items = ((PyParameterList)elem).getParameters();
}
else if (elem instanceof PyArgumentList) {
items = ((PyArgumentList)elem).getArguments();
}
else if (elem instanceof PyFromImportStatement) {
items = ((PyFromImportStatement)elem).getImportElements();
}
else if (elem instanceof PyParenthesizedExpression) {
final PyExpression containedExpression = ((PyParenthesizedExpression)elem).getContainedExpression();
if (containedExpression instanceof PyTupleExpression) {
items = ((PyTupleExpression)containedExpression).getElements();
}
else if (containedExpression != null) {
return containedExpression;
}
}
else if (elem instanceof PyComprehensionElement) {
return ((PyComprehensionElement)elem).getResultExpression();
}
return ArrayUtil.getFirstElement(items);
}
private static boolean breaksAlignment(IElementType type) {
return type != PyElementTypes.BINARY_EXPRESSION;
}
private static Alignment getAlignmentOfChild(@NotNull PyBlock b, int childNum) {
if (b.getSubBlocks().size() > childNum) {
final ChildAttributes attributes = b.getChildAttributes(childNum);
return attributes.getAlignment();
}
return null;
}
private static boolean isIndentNext(@NotNull ASTNode child) {
final PsiElement psi = PsiTreeUtil.getParentOfType(child.getPsi(), PyStatement.class);
return psi instanceof PyIfStatement ||
psi instanceof PyForStatement ||
psi instanceof PyWithStatement ||
psi instanceof PyClass ||
psi instanceof PyFunction ||
psi instanceof PyTryExceptStatement ||
psi instanceof PyElsePart ||
psi instanceof PyIfPart ||
psi instanceof PyWhileStatement;
}
private static boolean isSubscriptionOperand(@NotNull ASTNode child) {
return child.getTreeParent().getElementType() == PyElementTypes.SUBSCRIPTION_EXPRESSION &&
child.getPsi() == ((PySubscriptionExpression)child.getTreeParent().getPsi()).getOperand();
}
private boolean isInControlStatement() {
return getControlStatementHeader(myNode) != null;
}
@Nullable
private static PsiElement getControlStatementHeader(@NotNull ASTNode node) {
final PyStatementPart statementPart = PsiTreeUtil.getParentOfType(node.getPsi(), PyStatementPart.class, false, PyStatementList.class);
if (statementPart != null) {
return statementPart;
}
final PyWithItem withItem = PsiTreeUtil.getParentOfType(node.getPsi(), PyWithItem.class);
if (withItem != null) {
return withItem.getParent();
}
return null;
}
private boolean isSliceOperand(@NotNull ASTNode child) {
if (myNode.getPsi() instanceof PySliceExpression) {
final PySliceExpression sliceExpression = (PySliceExpression)myNode.getPsi();
final PyExpression operand = sliceExpression.getOperand();
return operand.getNode() == child;
}
return false;
}
private static boolean isAfterStatementList(@NotNull ASTNode child) {
final PsiElement prev = child.getPsi().getPrevSibling();
if (!(prev instanceof PyStatement)) {
return false;
}
final PsiElement lastChild = PsiTreeUtil.getDeepestLast(prev);
return lastChild.getParent() instanceof PyStatementList;
}
private boolean needListAlignment(@NotNull ASTNode child) {
final IElementType childType = child.getElementType();
if (PyTokenTypes.OPEN_BRACES.contains(childType)) {
return false;
}
if (PyTokenTypes.CLOSE_BRACES.contains(childType)) {
final ASTNode prevNonSpace = findPrevNonSpaceNode(child);
if (prevNonSpace != null &&
prevNonSpace.getElementType() == PyTokenTypes.COMMA &&
myContext.getMode() == FormattingMode.ADJUST_INDENT) {
return true;
}
return !hasHangingIndent(myNode.getPsi()) && !(myNode.getElementType() == PyElementTypes.DICT_LITERAL_EXPRESSION &&
myContext.getPySettings().DICT_NEW_LINE_AFTER_LEFT_BRACE);
}
if (myNode.getElementType() == PyElementTypes.ARGUMENT_LIST) {
if (!myContext.getSettings().ALIGN_MULTILINE_PARAMETERS_IN_CALLS || hasHangingIndent(myNode.getPsi())) {
return false;
}
if (childType == PyTokenTypes.COMMA) {
return false;
}
return true;
}
if (myNode.getElementType() == PyElementTypes.PARAMETER_LIST) {
return !hasHangingIndent(myNode.getPsi()) && myContext.getSettings().ALIGN_MULTILINE_PARAMETERS;
}
if (myNode.getElementType() == PyElementTypes.SUBSCRIPTION_EXPRESSION) {
return false;
}
if (childType == PyTokenTypes.COMMA) {
return false;
}
if (myNode.getElementType() == PyElementTypes.PARENTHESIZED_EXPRESSION) {
if (childType == PyElementTypes.STRING_LITERAL_EXPRESSION) {
return true;
}
if (childType != PyElementTypes.TUPLE_EXPRESSION && childType != PyElementTypes.GENERATOR_EXPRESSION) {
return false;
}
}
return myContext.getPySettings().ALIGN_COLLECTIONS_AND_COMPREHENSIONS && !hasHangingIndent(myNode.getPsi());
}
@Nullable
private static ASTNode findPrevNonSpaceNode(@NotNull ASTNode node) {
do {
node = node.getTreePrev();
}
while (isWhitespace(node));
return node;
}
private static boolean isWhitespace(@Nullable ASTNode node) {
return node != null && (node.getElementType() == TokenType.WHITE_SPACE || PyTokenTypes.WHITESPACE.contains(node.getElementType()));
}
private static boolean hasLineBreaksBeforeInSameParent(@NotNull ASTNode node, int minCount) {
final ASTNode treePrev = node.getTreePrev();
return (treePrev != null && isWhitespaceWithLineBreaks(TreeUtil.findLastLeaf(treePrev), minCount)) ||
// Can happen, e.g. when you delete a statement from the beginning of a statement list
isWhitespaceWithLineBreaks(node.getFirstChildNode(), minCount);
}
private static boolean hasLineBreakAfterIgnoringComments(@NotNull ASTNode node) {
for (ASTNode next = TreeUtil.nextLeaf(node); next != null; next = TreeUtil.nextLeaf(next)) {
if (isWhitespace(next)) {
if (next.textContains('\n')) {
return true;
}
}
else if (next.getElementType() == PyTokenTypes.END_OF_LINE_COMMENT) {
return true;
}
else {
break;
}
}
return false;
}
private static boolean isWhitespaceWithLineBreaks(@Nullable ASTNode node, int minCount) {
if (isWhitespace(node)) {
if (minCount == 1) {
return node.textContains('\n');
}
final String prevNodeText = node.getText();
int count = 0;
for (int i = 0; i < prevNodeText.length(); i++) {
if (prevNodeText.charAt(i) == '\n') {
count++;
if (count == minCount) {
return true;
}
}
}
}
return false;
}
@Override
@Nullable
public Wrap getWrap() {
return myWrap;
}
@Override
@Nullable
public Indent getIndent() {
assert myIndent != null;
return myIndent;
}
@Override
@Nullable
public Alignment getAlignment() {
return myAlignment;
}
@Override
@Nullable
public Spacing getSpacing(@Nullable Block child1, @NotNull Block child2) {
final CommonCodeStyleSettings settings = myContext.getSettings();
final PyCodeStyleSettings pySettings = myContext.getPySettings();
if (child1 instanceof ASTBlock && child2 instanceof ASTBlock) {
final ASTNode node1 = ((ASTBlock)child1).getNode();
ASTNode node2 = ((ASTBlock)child2).getNode();
final IElementType childType1 = node1.getElementType();
final PsiElement psi1 = node1.getPsi();
PsiElement psi2 = node2.getPsi();
if (psi2 instanceof PyStatementList) {
// Quite odd getSpacing() doesn't get called with child1=null for the first statement
// in the statement list of a class, yet it does get called for the preceding colon and
// the statement list itself. Hence we have to handle blank lines around methods here in
// addition to SpacingBuilder.
if (myNode.getElementType() == PyElementTypes.CLASS_DECLARATION) {
final PyStatement[] statements = ((PyStatementList)psi2).getStatements();
if (statements.length > 0 && statements[0] instanceof PyFunction) {
return getBlankLinesForOption(pySettings.BLANK_LINES_BEFORE_FIRST_METHOD);
}
}
if (childType1 == PyTokenTypes.COLON && needLineBreakInStatement()) {
return Spacing.createSpacing(0, 0, 1, true, settings.KEEP_BLANK_LINES_IN_CODE);
}
}
// pycodestyle.py enforces at most 2 blank lines only between comments directly
// at the top-level of a file, not inside if, try/except, etc.
if (psi1 instanceof PsiComment && myNode.getPsi() instanceof PsiFile) {
return Spacing.createSpacing(0, 0, 1, true, 2);
}
// skip not inline comments to handles blank lines between various declarations
if (psi2 instanceof PsiComment && hasLineBreaksBeforeInSameParent(node2, 1)) {
final PsiElement nonCommentAfter = PyPsiUtils.getNextNonCommentSibling(psi2, true);
if (nonCommentAfter != null) {
psi2 = nonCommentAfter;
}
}
node2 = psi2.getNode();
final IElementType childType2 = psi2.getNode().getElementType();
child2 = getSubBlockByNode(node2);
if ((childType1 == PyTokenTypes.EQ || childType2 == PyTokenTypes.EQ)) {
final PyNamedParameter namedParameter = as(myNode.getPsi(), PyNamedParameter.class);
if (namedParameter != null && namedParameter.getAnnotation() != null) {
return Spacing.createSpacing(1, 1, 0, settings.KEEP_LINE_BREAKS, settings.KEEP_BLANK_LINES_IN_CODE);
}
}
if (psi1 instanceof PyImportStatementBase) {
if (psi2 instanceof PyImportStatementBase) {
final Boolean leftImportIsGroupStart = psi1.getCopyableUserData(IMPORT_GROUP_BEGIN);
final Boolean rightImportIsGroupStart = psi2.getCopyableUserData(IMPORT_GROUP_BEGIN);
// Cleanup user data, it's no longer needed
psi1.putCopyableUserData(IMPORT_GROUP_BEGIN, null);
// Don't remove IMPORT_GROUP_BEGIN from the element psi2 yet, because spacing is constructed pairwise:
// it might be needed on the next iteration.
//psi2.putCopyableUserData(IMPORT_GROUP_BEGIN, null);
if (rightImportIsGroupStart != null) {
return Spacing.createSpacing(0, 0, 2, true, 1);
}
else if (leftImportIsGroupStart != null) {
// It's a trick to keep spacing consistent when new import statement is inserted
// at the beginning of an import group, i.e. if there is a blank line before the next
// import we want to save it, but remove line *after* inserted import.
return Spacing.createSpacing(0, 0, 1, false, 0);
}
}
if (psi2 instanceof PyStatement && !(psi2 instanceof PyImportStatementBase)) {
if (PyUtil.isTopLevel(psi1)) {
// If there is any function or class after a top-level import, it should be top-level as well
if (PyElementTypes.CLASS_OR_FUNCTION.contains(childType2)) {
return getBlankLinesForOption(Math.max(settings.BLANK_LINES_AFTER_IMPORTS,
pySettings.BLANK_LINES_AROUND_TOP_LEVEL_CLASSES_FUNCTIONS));
}
return getBlankLinesForOption(settings.BLANK_LINES_AFTER_IMPORTS);
}
else {
return getBlankLinesForOption(pySettings.BLANK_LINES_AFTER_LOCAL_IMPORTS);
}
}
}
if ((PyElementTypes.CLASS_OR_FUNCTION.contains(childType1) && STATEMENT_OR_DECLARATION.contains(childType2)) ||
STATEMENT_OR_DECLARATION.contains(childType1) && PyElementTypes.CLASS_OR_FUNCTION.contains(childType2)) {
if (PyUtil.isTopLevel(psi1)) {
return getBlankLinesForOption(pySettings.BLANK_LINES_AROUND_TOP_LEVEL_CLASSES_FUNCTIONS);
}
}
}
return myContext.getSpacingBuilder().getSpacing(this, child1, child2);
}
@NotNull
private Spacing getBlankLinesForOption(int minBlankLines) {
final int lineFeeds = minBlankLines + 1;
return Spacing.createSpacing(0, 0, lineFeeds,
myContext.getSettings().KEEP_LINE_BREAKS,
myContext.getSettings().KEEP_BLANK_LINES_IN_DECLARATIONS);
}
private boolean needLineBreakInStatement() {
final PyStatement statement = PsiTreeUtil.getParentOfType(myNode.getPsi(), PyStatement.class);
if (statement != null) {
final Collection<PyStatementPart> parts = PsiTreeUtil.collectElementsOfType(statement, PyStatementPart.class);
return (parts.size() == 1 && myContext.getPySettings().NEW_LINE_AFTER_COLON) ||
(parts.size() > 1 && myContext.getPySettings().NEW_LINE_AFTER_COLON_MULTI_CLAUSE);
}
return false;
}
@Override
@NotNull
public ChildAttributes getChildAttributes(int newChildIndex) {
int statementListsBelow = 0;
if (newChildIndex > 0) {
// always pass decision to a sane block from top level from file or definition
if (myNode.getPsi() instanceof PyFile || myNode.getElementType() == PyTokenTypes.COLON) {
return ChildAttributes.DELEGATE_TO_PREV_CHILD;
}
final PyBlock insertAfterBlock = getSubBlockByIndex(newChildIndex - 1);
final ASTNode prevNode = insertAfterBlock.getNode();
final PsiElement prevElt = prevNode.getPsi();
// stmt lists, parts and definitions should also think for themselves
if (prevElt instanceof PyStatementList) {
if (dedentAfterLastStatement((PyStatementList)prevElt)) {
return new ChildAttributes(Indent.getNoneIndent(), getChildAlignment());
}
return ChildAttributes.DELEGATE_TO_PREV_CHILD;
}
else if (prevElt instanceof PyStatementPart) {
return ChildAttributes.DELEGATE_TO_PREV_CHILD;
}
ASTNode lastChild = insertAfterBlock.getNode();
// HACK? This code fragment is needed to make testClass2() pass,
// but I don't quite understand why it is necessary and why the formatter
// doesn't request childAttributes from the correct block
while (lastChild != null) {
final IElementType lastType = lastChild.getElementType();
if (lastType == PyElementTypes.STATEMENT_LIST && hasLineBreaksBeforeInSameParent(lastChild, 1)) {
if (dedentAfterLastStatement((PyStatementList)lastChild.getPsi())) {
break;
}
statementListsBelow++;
}
else if (statementListsBelow > 0 && lastChild.getPsi() instanceof PsiErrorElement) {
statementListsBelow++;
}
if (myNode.getElementType() == PyElementTypes.STATEMENT_LIST && lastChild.getPsi() instanceof PsiErrorElement) {
return ChildAttributes.DELEGATE_TO_PREV_CHILD;
}
lastChild = getLastNonSpaceChild(lastChild, true);
}
}
// HACKETY-HACK
// If a multi-step dedent follows the cursor position (see testMultiDedent()),
// the whitespace (which must be a single Py:LINE_BREAK token) gets attached
// to the outermost indented block (because we may not consume the DEDENT
// tokens while parsing inner blocks). The policy is to put the indent to
// the innermost block, so we need to resolve the situation here. Nested
// delegation sometimes causes NPEs in formatter core, so we calculate the
// correct indent manually.
if (statementListsBelow > 0) { // was 1... strange
@SuppressWarnings("ConstantConditions") final int indent = myContext.getSettings().getIndentOptions().INDENT_SIZE;
return new ChildAttributes(Indent.getSpaceIndent(indent * statementListsBelow), null);
}
/*
// it might be something like "def foo(): # comment" or "[1, # comment"; jump up to the real thing
if (_node instanceof PsiComment || _node instanceof PsiWhiteSpace) {
get
}
*/
final Indent childIndent = getChildIndent(newChildIndex);
final Alignment childAlignment = getChildAlignment();
return new ChildAttributes(childIndent, childAlignment);
}
private static boolean dedentAfterLastStatement(@NotNull PyStatementList statementList) {
final PyStatement[] statements = statementList.getStatements();
if (statements.length == 0) {
return false;
}
final PyStatement last = statements[statements.length - 1];
return last instanceof PyReturnStatement || last instanceof PyRaiseStatement || last instanceof PyPassStatement || isEllipsis(last);
}
private static boolean isEllipsis(@NotNull PyStatement statement) {
if (statement instanceof PyExpressionStatement) {
final PyExpression expression = ((PyExpressionStatement)statement).getExpression();
if (expression instanceof PyNoneLiteralExpression) {
return ((PyNoneLiteralExpression)expression).isEllipsis();
}
}
return false;
}
@Nullable
private Alignment getChildAlignment() {
// TODO merge it with needListAlignment(ASTNode)
final IElementType nodeType = myNode.getElementType();
if (ourListElementTypes.contains(nodeType) ||
nodeType == PyElementTypes.SLICE_ITEM ||
nodeType == PyElementTypes.STRING_LITERAL_EXPRESSION) {
if (isInControlStatement()) {
return null;
}
final PsiElement elem = myNode.getPsi();
if (elem instanceof PyParameterList && !myContext.getSettings().ALIGN_MULTILINE_PARAMETERS) {
return null;
}
if ((elem instanceof PySequenceExpression || elem instanceof PyComprehensionElement) &&
!myContext.getPySettings().ALIGN_COLLECTIONS_AND_COMPREHENSIONS) {
return null;
}
if (elem instanceof PyParenthesizedExpression) {
final PyExpression parenthesized = ((PyParenthesizedExpression)elem).getContainedExpression();
if (parenthesized instanceof PyTupleExpression && !myContext.getPySettings().ALIGN_COLLECTIONS_AND_COMPREHENSIONS) {
return null;
}
}
if (elem instanceof PyDictLiteralExpression) {
final PyKeyValueExpression lastElement = ArrayUtil.getLastElement(((PyDictLiteralExpression)elem).getElements());
if (lastElement == null || lastElement.getValue() == null /* incomplete */) {
return null;
}
}
return getAlignmentForChildren();
}
return null;
}
@NotNull
private Indent getChildIndent(int newChildIndex) {
final ASTNode afterNode = getAfterNode(newChildIndex);
final ASTNode lastChild = getLastNonSpaceChild(myNode, false);
if (lastChild != null && lastChild.getElementType() == PyElementTypes.STATEMENT_LIST && mySubBlocks.size() >= newChildIndex) {
if (afterNode == null) {
return Indent.getNoneIndent();
}
// handle pressing Enter after colon and before first statement in
// existing statement list
if (afterNode.getElementType() == PyElementTypes.STATEMENT_LIST || afterNode.getElementType() == PyTokenTypes.COLON) {
return Indent.getNormalIndent();
}
// handle pressing Enter after colon when there is nothing in the
// statement list
final ASTNode lastFirstChild = lastChild.getFirstChildNode();
if (lastFirstChild != null && lastFirstChild == lastChild.getLastChildNode() && lastFirstChild.getPsi() instanceof PsiErrorElement) {
return Indent.getNormalIndent();
}
}
if (afterNode != null && afterNode.getElementType() == PyElementTypes.KEY_VALUE_EXPRESSION) {
final PyKeyValueExpression keyValue = (PyKeyValueExpression)afterNode.getPsi();
if (keyValue != null && keyValue.getValue() == null) { // incomplete
return Indent.getContinuationIndent();
}
}
final IElementType parentType = myNode.getElementType();
// constructs that imply indent for their children
final PyCodeStyleSettings settings = myContext.getPySettings();
if (parentType == PyElementTypes.PARAMETER_LIST ||
(parentType == PyElementTypes.ARGUMENT_LIST && settings.USE_CONTINUATION_INDENT_FOR_ARGUMENTS)) {
return Indent.getContinuationIndent();
}
if (ourCollectionLiteralTypes.contains(parentType) || parentType == PyElementTypes.TUPLE_EXPRESSION) {
return settings.USE_CONTINUATION_INDENT_FOR_COLLECTION_AND_COMPREHENSIONS ? Indent.getContinuationIndent() : Indent.getNormalIndent();
}
else if (ourListElementTypes.contains(parentType) || myNode.getPsi() instanceof PyStatementPart) {
return Indent.getNormalIndent();
}
if (afterNode != null) {
ASTNode wsAfter = afterNode.getTreeNext();
while (wsAfter != null && wsAfter.getElementType() == TokenType.WHITE_SPACE) {
if (wsAfter.getText().indexOf('\\') >= 0) {
return Indent.getNormalIndent();
}
wsAfter = wsAfter.getTreeNext();
}
}
return Indent.getNoneIndent();
}
@Nullable
private ASTNode getAfterNode(int newChildIndex) {
if (newChildIndex == 0) { // block text contains backslash line wrappings, child block list not built
return null;
}
int prevIndex = newChildIndex - 1;
while (prevIndex > 0 && getSubBlockByIndex(prevIndex).getNode().getElementType() == PyTokenTypes.END_OF_LINE_COMMENT) {
prevIndex--;
}
return getSubBlockByIndex(prevIndex).getNode();
}
private static ASTNode getLastNonSpaceChild(@NotNull ASTNode node, boolean acceptError) {
ASTNode lastChild = node.getLastChildNode();
while (lastChild != null &&
(lastChild.getElementType() == TokenType.WHITE_SPACE || (!acceptError && lastChild.getPsi() instanceof PsiErrorElement))) {
lastChild = lastChild.getTreePrev();
}
return lastChild;
}
@Override
public boolean isIncomplete() {
// if there's something following us, we're not incomplete
if (!PsiTreeUtil.hasErrorElements(myNode.getPsi())) {
PsiElement element = myNode.getPsi().getNextSibling();
while (element instanceof PsiWhiteSpace) {
element = element.getNextSibling();
}
if (element != null) {
return false;
}
}
final ASTNode lastChild = getLastNonSpaceChild(myNode, false);
if (lastChild != null) {
if (lastChild.getElementType() == PyElementTypes.STATEMENT_LIST) {
// only multiline statement lists are considered incomplete
final ASTNode statementListPrev = lastChild.getTreePrev();
if (statementListPrev != null && statementListPrev.getText().indexOf('\n') >= 0) {
return true;
}
}
if (lastChild.getElementType() == PyElementTypes.BINARY_EXPRESSION) {
final PyBinaryExpression binaryExpression = (PyBinaryExpression)lastChild.getPsi();
if (binaryExpression.getRightExpression() == null) {
return true;
}
}
if (isIncompleteCall(lastChild)) return true;
}
if (myNode.getPsi() instanceof PyArgumentList) {
final PyArgumentList argumentList = (PyArgumentList)myNode.getPsi();
return argumentList.getClosingParen() == null;
}
if (isIncompleteCall(myNode) || isIncompleteExpressionWithBrackets(myNode.getPsi())) {
return true;
}
return false;
}
private static boolean isIncompleteCall(@NotNull ASTNode node) {
if (node.getElementType() == PyElementTypes.CALL_EXPRESSION) {
final PyCallExpression callExpression = (PyCallExpression)node.getPsi();
final PyArgumentList argumentList = callExpression.getArgumentList();
if (argumentList == null || argumentList.getClosingParen() == null) {
return true;
}
}
return false;
}
private static boolean isIncompleteExpressionWithBrackets(@NotNull PsiElement elem) {
if (elem instanceof PySequenceExpression || elem instanceof PyComprehensionElement || elem instanceof PyParenthesizedExpression) {
return PyTokenTypes.OPEN_BRACES.contains(elem.getFirstChild().getNode().getElementType()) &&
!PyTokenTypes.CLOSE_BRACES.contains(elem.getLastChild().getNode().getElementType());
}
return false;
}
@Override
public boolean isLeaf() {
return myNode.getFirstChildNode() == null;
}
}
| python/src/com/jetbrains/python/formatter/PyBlock.java | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.formatter;
import com.intellij.formatting.*;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CommonCodeStyleSettings;
import com.intellij.psi.impl.source.tree.TreeUtil;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.ArrayUtil;
import com.jetbrains.python.PyElementTypes;
import com.jetbrains.python.PyTokenTypes;
import com.jetbrains.python.psi.*;
import com.jetbrains.python.psi.impl.PyPsiUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import static com.jetbrains.python.formatter.PyCodeStyleSettings.DICT_ALIGNMENT_ON_COLON;
import static com.jetbrains.python.formatter.PyCodeStyleSettings.DICT_ALIGNMENT_ON_VALUE;
import static com.jetbrains.python.formatter.PythonFormattingModelBuilder.STATEMENT_OR_DECLARATION;
import static com.jetbrains.python.psi.PyUtil.as;
/**
* @author yole
*/
public class PyBlock implements ASTBlock {
private static final TokenSet ourListElementTypes = TokenSet.create(PyElementTypes.LIST_LITERAL_EXPRESSION,
PyElementTypes.LIST_COMP_EXPRESSION,
PyElementTypes.DICT_LITERAL_EXPRESSION,
PyElementTypes.DICT_COMP_EXPRESSION,
PyElementTypes.SET_LITERAL_EXPRESSION,
PyElementTypes.SET_COMP_EXPRESSION,
PyElementTypes.ARGUMENT_LIST,
PyElementTypes.PARAMETER_LIST,
PyElementTypes.TUPLE_EXPRESSION,
PyElementTypes.PARENTHESIZED_EXPRESSION,
PyElementTypes.SLICE_EXPRESSION,
PyElementTypes.SUBSCRIPTION_EXPRESSION,
PyElementTypes.GENERATOR_EXPRESSION);
private static final TokenSet ourCollectionLiteralTypes = TokenSet.create(PyElementTypes.LIST_LITERAL_EXPRESSION,
PyElementTypes.LIST_COMP_EXPRESSION,
PyElementTypes.DICT_LITERAL_EXPRESSION,
PyElementTypes.DICT_COMP_EXPRESSION,
PyElementTypes.SET_LITERAL_EXPRESSION,
PyElementTypes.SET_COMP_EXPRESSION);
private static final TokenSet ourBrackets = TokenSet.create(PyTokenTypes.LPAR, PyTokenTypes.RPAR,
PyTokenTypes.LBRACE, PyTokenTypes.RBRACE,
PyTokenTypes.LBRACKET, PyTokenTypes.RBRACKET);
private static final TokenSet ourHangingIndentOwners = TokenSet.create(PyElementTypes.LIST_LITERAL_EXPRESSION,
PyElementTypes.LIST_COMP_EXPRESSION,
PyElementTypes.DICT_LITERAL_EXPRESSION,
PyElementTypes.DICT_COMP_EXPRESSION,
PyElementTypes.SET_LITERAL_EXPRESSION,
PyElementTypes.SET_COMP_EXPRESSION,
PyElementTypes.ARGUMENT_LIST,
PyElementTypes.PARAMETER_LIST,
PyElementTypes.TUPLE_EXPRESSION,
PyElementTypes.PARENTHESIZED_EXPRESSION,
PyElementTypes.GENERATOR_EXPRESSION,
PyElementTypes.FUNCTION_DECLARATION,
PyElementTypes.CALL_EXPRESSION,
PyElementTypes.FROM_IMPORT_STATEMENT);
public static final Key<Boolean> IMPORT_GROUP_BEGIN = Key.create("com.jetbrains.python.formatter.importGroupBegin");
private static final boolean ALIGN_CONDITIONS_WITHOUT_PARENTHESES = false;
private final PyBlock myParent;
private final Alignment myAlignment;
private final Indent myIndent;
private final ASTNode myNode;
private final Wrap myWrap;
private final PyBlockContext myContext;
private List<PyBlock> mySubBlocks = null;
private Map<ASTNode, PyBlock> mySubBlockByNode = null;
private final boolean myEmptySequence;
// Shared among multiple children sub-blocks
private Alignment myChildAlignment = null;
private Alignment myDictAlignment = null;
private Wrap myDictWrapping = null;
private Wrap myFromImportWrapping = null;
public PyBlock(@Nullable PyBlock parent,
@NotNull ASTNode node,
@Nullable Alignment alignment,
@NotNull Indent indent,
@Nullable Wrap wrap,
@NotNull PyBlockContext context) {
myParent = parent;
myAlignment = alignment;
myIndent = indent;
myNode = node;
myWrap = wrap;
myContext = context;
myEmptySequence = isEmptySequence(node);
final PyCodeStyleSettings pySettings = myContext.getPySettings();
if (node.getElementType() == PyElementTypes.DICT_LITERAL_EXPRESSION) {
myDictAlignment = Alignment.createAlignment(true);
myDictWrapping = Wrap.createWrap(pySettings.DICT_WRAPPING, true);
}
else if (node.getElementType() == PyElementTypes.FROM_IMPORT_STATEMENT) {
myFromImportWrapping = Wrap.createWrap(pySettings.FROM_IMPORT_WRAPPING, false);
}
}
@Override
@NotNull
public ASTNode getNode() {
return myNode;
}
@Override
@NotNull
public TextRange getTextRange() {
return myNode.getTextRange();
}
private Alignment getAlignmentForChildren() {
if (myChildAlignment == null) {
myChildAlignment = Alignment.createAlignment();
}
return myChildAlignment;
}
@Override
@NotNull
public List<Block> getSubBlocks() {
if (mySubBlocks == null) {
mySubBlockByNode = buildSubBlocks();
mySubBlocks = new ArrayList<>(mySubBlockByNode.values());
}
return Collections.unmodifiableList(mySubBlocks);
}
@Nullable
private PyBlock getSubBlockByNode(@NotNull ASTNode node) {
return mySubBlockByNode.get(node);
}
@Nullable
private PyBlock getSubBlockByIndex(int index) {
return mySubBlocks.get(index);
}
@NotNull
private Map<ASTNode, PyBlock> buildSubBlocks() {
final Map<ASTNode, PyBlock> blocks = new LinkedHashMap<>();
for (ASTNode child: getSubBlockNodes()) {
final IElementType childType = child.getElementType();
if (child.getTextRange().isEmpty()) continue;
if (childType == TokenType.WHITE_SPACE) {
continue;
}
blocks.put(child, buildSubBlock(child));
}
return Collections.unmodifiableMap(blocks);
}
@NotNull
protected Iterable<ASTNode> getSubBlockNodes() {
if (myNode.getElementType() == PyElementTypes.BINARY_EXPRESSION) {
final ArrayList<ASTNode> result = new ArrayList<>();
collectChildrenOperatorAndOperandNodes(myNode, result);
return result;
}
return Arrays.asList(myNode.getChildren(null));
}
private static void collectChildrenOperatorAndOperandNodes(@NotNull ASTNode node, @NotNull List<ASTNode> result) {
if (node.getElementType() == PyElementTypes.BINARY_EXPRESSION) {
for (ASTNode child : node.getChildren(null)) {
collectChildrenOperatorAndOperandNodes(child, result);
}
}
else {
result.add(node);
}
}
@NotNull
private PyBlock buildSubBlock(@NotNull ASTNode child) {
final IElementType parentType = myNode.getElementType();
final ASTNode grandParentNode = myNode.getTreeParent();
final IElementType grandparentType = grandParentNode == null ? null : grandParentNode.getElementType();
final IElementType childType = child.getElementType();
Wrap childWrap = null;
Indent childIndent = Indent.getNoneIndent();
Alignment childAlignment = null;
final PyCodeStyleSettings settings = myContext.getPySettings();
if (childType == PyElementTypes.STATEMENT_LIST) {
if (hasLineBreaksBeforeInSameParent(child, 1) || needLineBreakInStatement()) {
childIndent = Indent.getNormalIndent();
}
}
else if (childType == PyElementTypes.IMPORT_ELEMENT) {
if (parentType == PyElementTypes.FROM_IMPORT_STATEMENT) {
childWrap = myFromImportWrapping;
}
else {
childWrap = Wrap.createWrap(WrapType.NORMAL, true);
}
childIndent = Indent.getNormalIndent();
}
if (childType == PyTokenTypes.END_OF_LINE_COMMENT && parentType == PyElementTypes.FROM_IMPORT_STATEMENT) {
childIndent = Indent.getNormalIndent();
}
// TODO merge it with the following check of needListAlignment()
if (ourListElementTypes.contains(parentType)) {
// wrapping in non-parenthesized tuple expression is not allowed (PY-1792)
if ((parentType != PyElementTypes.TUPLE_EXPRESSION || grandparentType == PyElementTypes.PARENTHESIZED_EXPRESSION) &&
!ourBrackets.contains(childType) &&
childType != PyTokenTypes.COMMA &&
!isSliceOperand(child) /*&& !isSubscriptionOperand(child)*/) {
childWrap = Wrap.createWrap(WrapType.NORMAL, true);
}
if (needListAlignment(child) && !myEmptySequence) {
childAlignment = getAlignmentForChildren();
}
if (childType == PyTokenTypes.END_OF_LINE_COMMENT) {
childIndent = Indent.getNormalIndent();
}
}
if (parentType == PyElementTypes.BINARY_EXPRESSION) {
if (childType != PyElementTypes.BINARY_EXPRESSION) {
final PyBlock topmostBinary = findTopmostBinaryExpressionBlock(child);
assert topmostBinary != null;
final PyBlock binaryParentBlock = topmostBinary.myParent;
final ASTNode binaryParentNode = binaryParentBlock.myNode;
final IElementType binaryParentType = binaryParentNode.getElementType();
// TODO check for comprehensions explicitly here
if (ourListElementTypes.contains(binaryParentType) && needListAlignment(child) && !myEmptySequence) {
childAlignment = binaryParentBlock.getChildAlignment();
}
final boolean parenthesised = binaryParentType == PyElementTypes.PARENTHESIZED_EXPRESSION;
if (childAlignment == null && topmostBinary != null &&
!(parenthesised && isIfCondition(binaryParentNode)) &&
!(isCondition(topmostBinary.myNode) && !ALIGN_CONDITIONS_WITHOUT_PARENTHESES)) {
childAlignment = topmostBinary.getAlignmentForChildren();
}
// We omit indentation for the binary expression itself in this case (similarly to PyTupleExpression inside
// PyParenthesisedExpression) because we indent individual operands and operators inside rather than
// the whole contained expression.
childIndent = parenthesised ? Indent.getContinuationIndent() : Indent.getContinuationWithoutFirstIndent();
}
}
else if (parentType == PyElementTypes.LIST_LITERAL_EXPRESSION || parentType == PyElementTypes.LIST_COMP_EXPRESSION) {
if ((childType == PyTokenTypes.RBRACKET && !settings.HANG_CLOSING_BRACKETS) || childType == PyTokenTypes.LBRACKET) {
childIndent = Indent.getNoneIndent();
}
else {
childIndent = settings.USE_CONTINUATION_INDENT_FOR_COLLECTION_AND_COMPREHENSIONS ? Indent.getContinuationIndent() : Indent.getNormalIndent();
}
}
else if (parentType == PyElementTypes.DICT_LITERAL_EXPRESSION || parentType == PyElementTypes.SET_LITERAL_EXPRESSION ||
parentType == PyElementTypes.SET_COMP_EXPRESSION || parentType == PyElementTypes.DICT_COMP_EXPRESSION) {
if ((childType == PyTokenTypes.RBRACE && !settings.HANG_CLOSING_BRACKETS) || !hasLineBreaksBeforeInSameParent(child, 1)) {
childIndent = Indent.getNoneIndent();
}
else {
childIndent = settings.USE_CONTINUATION_INDENT_FOR_COLLECTION_AND_COMPREHENSIONS ? Indent.getContinuationIndent() : Indent.getNormalIndent();
}
}
else if (parentType == PyElementTypes.STRING_LITERAL_EXPRESSION) {
if (PyTokenTypes.STRING_NODES.contains(childType)) {
childAlignment = getAlignmentForChildren();
}
}
else if (parentType == PyElementTypes.FROM_IMPORT_STATEMENT) {
if (myNode.findChildByType(PyTokenTypes.LPAR) != null) {
if (childType == PyElementTypes.IMPORT_ELEMENT) {
if (settings.ALIGN_MULTILINE_IMPORTS) {
childAlignment = getAlignmentForChildren();
}
else {
childIndent = Indent.getNormalIndent();
}
}
if (childType == PyTokenTypes.RPAR) {
childIndent = Indent.getNoneIndent();
// Don't have hanging indent and is not going to have it due to the setting about opening parenthesis
if (!hasHangingIndent(myNode.getPsi()) && !settings.FROM_IMPORT_NEW_LINE_AFTER_LEFT_PARENTHESIS) {
childAlignment = getAlignmentForChildren();
}
else if (settings.HANG_CLOSING_BRACKETS) {
childIndent = Indent.getNormalIndent();
}
}
}
}
else if (isValueOfKeyValuePair(child)) {
childIndent = Indent.getNormalIndent();
}
// TODO: merge with needChildAlignment()
//Align elements vertically if there is an argument in the first line of parenthesized expression
else if (!hasHangingIndent(myNode.getPsi()) &&
(parentType == PyElementTypes.PARENTHESIZED_EXPRESSION ||
(parentType == PyElementTypes.ARGUMENT_LIST && myContext.getSettings().ALIGN_MULTILINE_PARAMETERS_IN_CALLS) ||
(parentType == PyElementTypes.PARAMETER_LIST && myContext.getSettings().ALIGN_MULTILINE_PARAMETERS)) &&
!isIndentNext(child) &&
!hasLineBreaksBeforeInSameParent(myNode.getFirstChildNode(), 1) &&
!ourListElementTypes.contains(childType)) {
if (!ourBrackets.contains(childType)) {
childAlignment = getAlignmentForChildren();
if (parentType != PyElementTypes.CALL_EXPRESSION) {
childIndent = Indent.getNormalIndent();
}
}
else if (childType == PyTokenTypes.RPAR) {
childIndent = Indent.getNoneIndent();
}
}
// Note that colons are aligned together with bounds and stride
else if (myNode.getElementType() == PyElementTypes.SLICE_ITEM) {
childAlignment = getChildAlignment();
}
else if (parentType == PyElementTypes.GENERATOR_EXPRESSION || parentType == PyElementTypes.PARENTHESIZED_EXPRESSION) {
final boolean tupleOrGenerator = parentType == PyElementTypes.GENERATOR_EXPRESSION ||
myNode.getPsi(PyParenthesizedExpression.class).getContainedExpression() instanceof PyTupleExpression;
if ((childType == PyTokenTypes.RPAR && !(tupleOrGenerator && settings.HANG_CLOSING_BRACKETS)) ||
!hasLineBreaksBeforeInSameParent(child, 1)) {
childIndent = Indent.getNoneIndent();
}
// Operands and operators of a binary expression have their own indent, no need to increase it by indenting the expression itself
else if (childType == PyElementTypes.BINARY_EXPRESSION && parentType == PyElementTypes.PARENTHESIZED_EXPRESSION) {
childIndent = Indent.getNoneIndent();
}
else {
final boolean useWiderIndent = isIndentNext(child) || settings.USE_CONTINUATION_INDENT_FOR_COLLECTION_AND_COMPREHENSIONS;
childIndent = useWiderIndent ? Indent.getContinuationIndent() : Indent.getNormalIndent();
}
}
else if (parentType == PyElementTypes.ARGUMENT_LIST || parentType == PyElementTypes.PARAMETER_LIST) {
if (childType == PyTokenTypes.RPAR && !settings.HANG_CLOSING_BRACKETS) {
childIndent = Indent.getNoneIndent();
}
else if (parentType == PyElementTypes.PARAMETER_LIST ||
settings.USE_CONTINUATION_INDENT_FOR_ARGUMENTS ||
argumentMayHaveSameIndentAsFollowingStatementList()) {
childIndent = Indent.getContinuationIndent();
}
else {
childIndent = Indent.getNormalIndent();
}
}
else if (parentType == PyElementTypes.SUBSCRIPTION_EXPRESSION) {
final PyExpression indexExpression = ((PySubscriptionExpression)myNode.getPsi()).getIndexExpression();
if (indexExpression != null && child == indexExpression.getNode()) {
childIndent = Indent.getNormalIndent();
}
}
else if (parentType == PyElementTypes.REFERENCE_EXPRESSION) {
if (child != myNode.getFirstChildNode()) {
childIndent = Indent.getNormalIndent();
if (hasLineBreaksBeforeInSameParent(child, 1)) {
if (isInControlStatement()) {
childIndent = Indent.getContinuationIndent();
}
else {
PyBlock b = myParent;
while (b != null) {
if (b.getNode().getPsi() instanceof PyParenthesizedExpression ||
b.getNode().getPsi() instanceof PyArgumentList ||
b.getNode().getPsi() instanceof PyParameterList) {
childAlignment = getAlignmentOfChild(b, 1);
break;
}
b = b.myParent;
}
}
}
}
}
if (childType == PyElementTypes.KEY_VALUE_EXPRESSION && isChildOfDictLiteral(child)) {
childWrap = myDictWrapping;
childIndent = settings.USE_CONTINUATION_INDENT_FOR_COLLECTION_AND_COMPREHENSIONS ? Indent.getContinuationIndent() : Indent.getNormalIndent();
}
if (isAfterStatementList(child) &&
!hasLineBreaksBeforeInSameParent(child, 2) &&
child.getElementType() != PyTokenTypes.END_OF_LINE_COMMENT) {
// maybe enter was pressed and cut us from a previous (nested) statement list
childIndent = Indent.getNormalIndent();
}
if (settings.DICT_ALIGNMENT == DICT_ALIGNMENT_ON_VALUE) {
// Align not the whole value but its left bracket if it starts with it
if (isValueOfKeyValuePairOfDictLiteral(child) && !isOpeningBracket(child.getFirstChildNode())) {
childAlignment = myParent.myDictAlignment;
}
else if (isValueOfKeyValuePairOfDictLiteral(myNode) && isOpeningBracket(child)) {
childAlignment = myParent.myParent.myDictAlignment;
}
}
else if (myContext.getPySettings().DICT_ALIGNMENT == DICT_ALIGNMENT_ON_COLON) {
if (isChildOfKeyValuePairOfDictLiteral(child) && childType == PyTokenTypes.COLON) {
childAlignment = myParent.myDictAlignment;
}
}
ASTNode prev = child.getTreePrev();
while (prev != null && prev.getElementType() == TokenType.WHITE_SPACE) {
if (prev.textContains('\\') &&
!childIndent.equals(Indent.getContinuationIndent(false)) &&
!childIndent.equals(Indent.getContinuationIndent(true))) {
childIndent = isIndentNext(child) ? Indent.getContinuationIndent() : Indent.getNormalIndent();
break;
}
prev = prev.getTreePrev();
}
return new PyBlock(this, child, childAlignment, childIndent, childWrap, myContext);
}
private static boolean isIfCondition(@NotNull ASTNode node) {
@NotNull PsiElement element = node.getPsi();
final PyIfPart ifPart = as(element.getParent(), PyIfPart.class);
return ifPart != null && ifPart.getCondition() == element && !ifPart.isElif();
}
private static boolean isCondition(@NotNull ASTNode node) {
final PsiElement element = node.getPsi();
final PyConditionalStatementPart conditionalStatement = as(element.getParent(), PyConditionalStatementPart.class);
return conditionalStatement != null && conditionalStatement.getCondition() == element;
}
@Nullable
private PyBlock findTopmostBinaryExpressionBlock(@NotNull ASTNode child) {
assert child.getElementType() != PyElementTypes.BINARY_EXPRESSION;
PyBlock parentBlock = this;
PyBlock alignmentOwner = null;
while (parentBlock != null && parentBlock.myNode.getElementType() == PyElementTypes.BINARY_EXPRESSION) {
alignmentOwner = parentBlock;
parentBlock = parentBlock.myParent;
}
return alignmentOwner;
}
private static boolean isOpeningBracket(@Nullable ASTNode node) {
return node != null && PyTokenTypes.OPEN_BRACES.contains(node.getElementType()) && node == node.getTreeParent().getFirstChildNode();
}
private static boolean isValueOfKeyValuePairOfDictLiteral(@NotNull ASTNode node) {
return isValueOfKeyValuePair(node) && isChildOfDictLiteral(node.getTreeParent());
}
private static boolean isChildOfKeyValuePairOfDictLiteral(@NotNull ASTNode node) {
return isChildOfKeyValuePair(node) && isChildOfDictLiteral(node.getTreeParent());
}
private static boolean isChildOfDictLiteral(@NotNull ASTNode node) {
final ASTNode nodeParent = node.getTreeParent();
return nodeParent != null && nodeParent.getElementType() == PyElementTypes.DICT_LITERAL_EXPRESSION;
}
private static boolean isChildOfKeyValuePair(@NotNull ASTNode node) {
final ASTNode nodeParent = node.getTreeParent();
return nodeParent != null && nodeParent.getElementType() == PyElementTypes.KEY_VALUE_EXPRESSION;
}
private static boolean isValueOfKeyValuePair(@NotNull ASTNode node) {
return isChildOfKeyValuePair(node) && node.getTreeParent().getPsi(PyKeyValueExpression.class).getValue() == node.getPsi();
}
private static boolean isEmptySequence(@NotNull ASTNode node) {
return node.getPsi() instanceof PySequenceExpression && ((PySequenceExpression)node.getPsi()).isEmpty();
}
private boolean argumentMayHaveSameIndentAsFollowingStatementList() {
if (myNode.getElementType() != PyElementTypes.ARGUMENT_LIST) {
return false;
}
// This check is supposed to prevent PEP8's error: Continuation line with the same indent as next logical line
final PsiElement header = getControlStatementHeader(myNode);
if (header instanceof PyStatementListContainer) {
final PyStatementList statementList = ((PyStatementListContainer)header).getStatementList();
return PyUtil.onSameLine(header, myNode.getPsi()) && !PyUtil.onSameLine(header, statementList);
}
return false;
}
// Check https://www.python.org/dev/peps/pep-0008/#indentation
private static boolean hasHangingIndent(@NotNull PsiElement elem) {
if (elem instanceof PyCallExpression) {
final PyArgumentList argumentList = ((PyCallExpression)elem).getArgumentList();
return argumentList != null && hasHangingIndent(argumentList);
}
else if (elem instanceof PyFunction) {
return hasHangingIndent(((PyFunction)elem).getParameterList());
}
final PsiElement firstChild;
if (elem instanceof PyFromImportStatement) {
firstChild = ((PyFromImportStatement)elem).getLeftParen();
}
else {
firstChild = elem.getFirstChild();
}
if (firstChild == null) {
return false;
}
final IElementType elementType = elem.getNode().getElementType();
final ASTNode firstChildNode = firstChild.getNode();
if (ourHangingIndentOwners.contains(elementType) && PyTokenTypes.OPEN_BRACES.contains(firstChildNode.getElementType())) {
if (hasLineBreakAfterIgnoringComments(firstChildNode)) {
return true;
}
final PsiElement firstItem = getFirstItem(elem);
if (firstItem == null) {
return !PyTokenTypes.CLOSE_BRACES.contains(elem.getLastChild().getNode().getElementType());
}
else {
if (firstItem instanceof PyNamedParameter) {
final PyExpression defaultValue = ((PyNamedParameter)firstItem).getDefaultValue();
return defaultValue != null && hasHangingIndent(defaultValue);
}
else if (firstItem instanceof PyKeywordArgument) {
final PyExpression valueExpression = ((PyKeywordArgument)firstItem).getValueExpression();
return valueExpression != null && hasHangingIndent(valueExpression);
}
else if (firstItem instanceof PyKeyValueExpression) {
final PyExpression value = ((PyKeyValueExpression)firstItem).getValue();
return value != null && hasHangingIndent(value);
}
return hasHangingIndent(firstItem);
}
}
else {
return false;
}
}
@Nullable
private static PsiElement getFirstItem(@NotNull PsiElement elem) {
PsiElement[] items = PsiElement.EMPTY_ARRAY;
if (elem instanceof PySequenceExpression) {
items = ((PySequenceExpression)elem).getElements();
}
else if (elem instanceof PyParameterList) {
items = ((PyParameterList)elem).getParameters();
}
else if (elem instanceof PyArgumentList) {
items = ((PyArgumentList)elem).getArguments();
}
else if (elem instanceof PyFromImportStatement) {
items = ((PyFromImportStatement)elem).getImportElements();
}
else if (elem instanceof PyParenthesizedExpression) {
final PyExpression containedExpression = ((PyParenthesizedExpression)elem).getContainedExpression();
if (containedExpression instanceof PyTupleExpression) {
items = ((PyTupleExpression)containedExpression).getElements();
}
else if (containedExpression != null) {
return containedExpression;
}
}
else if (elem instanceof PyComprehensionElement) {
return ((PyComprehensionElement)elem).getResultExpression();
}
return ArrayUtil.getFirstElement(items);
}
private static boolean breaksAlignment(IElementType type) {
return type != PyElementTypes.BINARY_EXPRESSION;
}
private static Alignment getAlignmentOfChild(@NotNull PyBlock b, int childNum) {
if (b.getSubBlocks().size() > childNum) {
final ChildAttributes attributes = b.getChildAttributes(childNum);
return attributes.getAlignment();
}
return null;
}
private static boolean isIndentNext(@NotNull ASTNode child) {
final PsiElement psi = PsiTreeUtil.getParentOfType(child.getPsi(), PyStatement.class);
return psi instanceof PyIfStatement ||
psi instanceof PyForStatement ||
psi instanceof PyWithStatement ||
psi instanceof PyClass ||
psi instanceof PyFunction ||
psi instanceof PyTryExceptStatement ||
psi instanceof PyElsePart ||
psi instanceof PyIfPart ||
psi instanceof PyWhileStatement;
}
private static boolean isSubscriptionOperand(@NotNull ASTNode child) {
return child.getTreeParent().getElementType() == PyElementTypes.SUBSCRIPTION_EXPRESSION &&
child.getPsi() == ((PySubscriptionExpression)child.getTreeParent().getPsi()).getOperand();
}
private boolean isInControlStatement() {
return getControlStatementHeader(myNode) != null;
}
@Nullable
private static PsiElement getControlStatementHeader(@NotNull ASTNode node) {
final PyStatementPart statementPart = PsiTreeUtil.getParentOfType(node.getPsi(), PyStatementPart.class, false, PyStatementList.class);
if (statementPart != null) {
return statementPart;
}
final PyWithItem withItem = PsiTreeUtil.getParentOfType(node.getPsi(), PyWithItem.class);
if (withItem != null) {
return withItem.getParent();
}
return null;
}
private boolean isSliceOperand(@NotNull ASTNode child) {
if (myNode.getPsi() instanceof PySliceExpression) {
final PySliceExpression sliceExpression = (PySliceExpression)myNode.getPsi();
final PyExpression operand = sliceExpression.getOperand();
return operand.getNode() == child;
}
return false;
}
private static boolean isAfterStatementList(@NotNull ASTNode child) {
final PsiElement prev = child.getPsi().getPrevSibling();
if (!(prev instanceof PyStatement)) {
return false;
}
final PsiElement lastChild = PsiTreeUtil.getDeepestLast(prev);
return lastChild.getParent() instanceof PyStatementList;
}
private boolean needListAlignment(@NotNull ASTNode child) {
final IElementType childType = child.getElementType();
if (PyTokenTypes.OPEN_BRACES.contains(childType)) {
return false;
}
if (PyTokenTypes.CLOSE_BRACES.contains(childType)) {
final ASTNode prevNonSpace = findPrevNonSpaceNode(child);
if (prevNonSpace != null &&
prevNonSpace.getElementType() == PyTokenTypes.COMMA &&
myContext.getMode() == FormattingMode.ADJUST_INDENT) {
return true;
}
return !hasHangingIndent(myNode.getPsi()) && !(myNode.getElementType() == PyElementTypes.DICT_LITERAL_EXPRESSION &&
myContext.getPySettings().DICT_NEW_LINE_AFTER_LEFT_BRACE);
}
if (myNode.getElementType() == PyElementTypes.ARGUMENT_LIST) {
if (!myContext.getSettings().ALIGN_MULTILINE_PARAMETERS_IN_CALLS || hasHangingIndent(myNode.getPsi())) {
return false;
}
if (childType == PyTokenTypes.COMMA) {
return false;
}
return true;
}
if (myNode.getElementType() == PyElementTypes.PARAMETER_LIST) {
return !hasHangingIndent(myNode.getPsi()) && myContext.getSettings().ALIGN_MULTILINE_PARAMETERS;
}
if (myNode.getElementType() == PyElementTypes.SUBSCRIPTION_EXPRESSION) {
return false;
}
if (childType == PyTokenTypes.COMMA) {
return false;
}
if (myNode.getElementType() == PyElementTypes.PARENTHESIZED_EXPRESSION) {
if (childType == PyElementTypes.STRING_LITERAL_EXPRESSION) {
return true;
}
if (childType != PyElementTypes.TUPLE_EXPRESSION && childType != PyElementTypes.GENERATOR_EXPRESSION) {
return false;
}
}
return myContext.getPySettings().ALIGN_COLLECTIONS_AND_COMPREHENSIONS && !hasHangingIndent(myNode.getPsi());
}
@Nullable
private static ASTNode findPrevNonSpaceNode(@NotNull ASTNode node) {
do {
node = node.getTreePrev();
}
while (isWhitespace(node));
return node;
}
private static boolean isWhitespace(@Nullable ASTNode node) {
return node != null && (node.getElementType() == TokenType.WHITE_SPACE || PyTokenTypes.WHITESPACE.contains(node.getElementType()));
}
private static boolean hasLineBreaksBeforeInSameParent(@NotNull ASTNode node, int minCount) {
final ASTNode treePrev = node.getTreePrev();
return (treePrev != null && isWhitespaceWithLineBreaks(TreeUtil.findLastLeaf(treePrev), minCount)) ||
// Can happen, e.g. when you delete a statement from the beginning of a statement list
isWhitespaceWithLineBreaks(node.getFirstChildNode(), minCount);
}
private static boolean hasLineBreakAfterIgnoringComments(@NotNull ASTNode node) {
for (ASTNode next = TreeUtil.nextLeaf(node); next != null; next = TreeUtil.nextLeaf(next)) {
if (isWhitespace(next)) {
if (next.textContains('\n')) {
return true;
}
}
else if (next.getElementType() == PyTokenTypes.END_OF_LINE_COMMENT) {
return true;
}
else {
break;
}
}
return false;
}
private static boolean isWhitespaceWithLineBreaks(@Nullable ASTNode node, int minCount) {
if (isWhitespace(node)) {
if (minCount == 1) {
return node.textContains('\n');
}
final String prevNodeText = node.getText();
int count = 0;
for (int i = 0; i < prevNodeText.length(); i++) {
if (prevNodeText.charAt(i) == '\n') {
count++;
if (count == minCount) {
return true;
}
}
}
}
return false;
}
@Override
@Nullable
public Wrap getWrap() {
return myWrap;
}
@Override
@Nullable
public Indent getIndent() {
assert myIndent != null;
return myIndent;
}
@Override
@Nullable
public Alignment getAlignment() {
return myAlignment;
}
@Override
@Nullable
public Spacing getSpacing(@Nullable Block child1, @NotNull Block child2) {
final CommonCodeStyleSettings settings = myContext.getSettings();
final PyCodeStyleSettings pySettings = myContext.getPySettings();
if (child1 instanceof ASTBlock && child2 instanceof ASTBlock) {
final ASTNode node1 = ((ASTBlock)child1).getNode();
ASTNode node2 = ((ASTBlock)child2).getNode();
final IElementType childType1 = node1.getElementType();
final PsiElement psi1 = node1.getPsi();
PsiElement psi2 = node2.getPsi();
if (psi2 instanceof PyStatementList) {
// Quite odd getSpacing() doesn't get called with child1=null for the first statement
// in the statement list of a class, yet it does get called for the preceding colon and
// the statement list itself. Hence we have to handle blank lines around methods here in
// addition to SpacingBuilder.
if (myNode.getElementType() == PyElementTypes.CLASS_DECLARATION) {
final PyStatement[] statements = ((PyStatementList)psi2).getStatements();
if (statements.length > 0 && statements[0] instanceof PyFunction) {
return getBlankLinesForOption(pySettings.BLANK_LINES_BEFORE_FIRST_METHOD);
}
}
if (childType1 == PyTokenTypes.COLON && needLineBreakInStatement()) {
return Spacing.createSpacing(0, 0, 1, true, settings.KEEP_BLANK_LINES_IN_CODE);
}
}
// pycodestyle.py enforces at most 2 blank lines only between comments directly
// at the top-level of a file, not inside if, try/except, etc.
if (psi1 instanceof PsiComment && myNode.getPsi() instanceof PsiFile) {
return Spacing.createSpacing(0, 0, 1, true, 2);
}
// skip not inline comments to handles blank lines between various declarations
if (psi2 instanceof PsiComment && hasLineBreaksBeforeInSameParent(node2, 1)) {
final PsiElement nonCommentAfter = PyPsiUtils.getNextNonCommentSibling(psi2, true);
if (nonCommentAfter != null) {
psi2 = nonCommentAfter;
}
}
node2 = psi2.getNode();
final IElementType childType2 = psi2.getNode().getElementType();
child2 = getSubBlockByNode(node2);
if ((childType1 == PyTokenTypes.EQ || childType2 == PyTokenTypes.EQ)) {
final PyNamedParameter namedParameter = as(myNode.getPsi(), PyNamedParameter.class);
if (namedParameter != null && namedParameter.getAnnotation() != null) {
return Spacing.createSpacing(1, 1, 0, settings.KEEP_LINE_BREAKS, settings.KEEP_BLANK_LINES_IN_CODE);
}
}
if (psi1 instanceof PyImportStatementBase) {
if (psi2 instanceof PyImportStatementBase) {
final Boolean leftImportIsGroupStart = psi1.getCopyableUserData(IMPORT_GROUP_BEGIN);
final Boolean rightImportIsGroupStart = psi2.getCopyableUserData(IMPORT_GROUP_BEGIN);
// Cleanup user data, it's no longer needed
psi1.putCopyableUserData(IMPORT_GROUP_BEGIN, null);
// Don't remove IMPORT_GROUP_BEGIN from the element psi2 yet, because spacing is constructed pairwise:
// it might be needed on the next iteration.
//psi2.putCopyableUserData(IMPORT_GROUP_BEGIN, null);
if (rightImportIsGroupStart != null) {
return Spacing.createSpacing(0, 0, 2, true, 1);
}
else if (leftImportIsGroupStart != null) {
// It's a trick to keep spacing consistent when new import statement is inserted
// at the beginning of an import group, i.e. if there is a blank line before the next
// import we want to save it, but remove line *after* inserted import.
return Spacing.createSpacing(0, 0, 1, false, 0);
}
}
if (psi2 instanceof PyStatement && !(psi2 instanceof PyImportStatementBase)) {
if (PyUtil.isTopLevel(psi1)) {
// If there is any function or class after a top-level import, it should be top-level as well
if (PyElementTypes.CLASS_OR_FUNCTION.contains(childType2)) {
return getBlankLinesForOption(Math.max(settings.BLANK_LINES_AFTER_IMPORTS,
pySettings.BLANK_LINES_AROUND_TOP_LEVEL_CLASSES_FUNCTIONS));
}
return getBlankLinesForOption(settings.BLANK_LINES_AFTER_IMPORTS);
}
else {
return getBlankLinesForOption(pySettings.BLANK_LINES_AFTER_LOCAL_IMPORTS);
}
}
}
if ((PyElementTypes.CLASS_OR_FUNCTION.contains(childType1) && STATEMENT_OR_DECLARATION.contains(childType2)) ||
STATEMENT_OR_DECLARATION.contains(childType1) && PyElementTypes.CLASS_OR_FUNCTION.contains(childType2)) {
if (PyUtil.isTopLevel(psi1)) {
return getBlankLinesForOption(pySettings.BLANK_LINES_AROUND_TOP_LEVEL_CLASSES_FUNCTIONS);
}
}
}
return myContext.getSpacingBuilder().getSpacing(this, child1, child2);
}
@NotNull
private Spacing getBlankLinesForOption(int minBlankLines) {
final int lineFeeds = minBlankLines + 1;
return Spacing.createSpacing(0, 0, lineFeeds,
myContext.getSettings().KEEP_LINE_BREAKS,
myContext.getSettings().KEEP_BLANK_LINES_IN_DECLARATIONS);
}
private boolean needLineBreakInStatement() {
final PyStatement statement = PsiTreeUtil.getParentOfType(myNode.getPsi(), PyStatement.class);
if (statement != null) {
final Collection<PyStatementPart> parts = PsiTreeUtil.collectElementsOfType(statement, PyStatementPart.class);
return (parts.size() == 1 && myContext.getPySettings().NEW_LINE_AFTER_COLON) ||
(parts.size() > 1 && myContext.getPySettings().NEW_LINE_AFTER_COLON_MULTI_CLAUSE);
}
return false;
}
@Override
@NotNull
public ChildAttributes getChildAttributes(int newChildIndex) {
int statementListsBelow = 0;
if (newChildIndex > 0) {
// always pass decision to a sane block from top level from file or definition
if (myNode.getPsi() instanceof PyFile || myNode.getElementType() == PyTokenTypes.COLON) {
return ChildAttributes.DELEGATE_TO_PREV_CHILD;
}
final PyBlock insertAfterBlock = getSubBlockByIndex(newChildIndex - 1);
final ASTNode prevNode = insertAfterBlock.getNode();
final PsiElement prevElt = prevNode.getPsi();
// stmt lists, parts and definitions should also think for themselves
if (prevElt instanceof PyStatementList) {
if (dedentAfterLastStatement((PyStatementList)prevElt)) {
return new ChildAttributes(Indent.getNoneIndent(), getChildAlignment());
}
return ChildAttributes.DELEGATE_TO_PREV_CHILD;
}
else if (prevElt instanceof PyStatementPart) {
return ChildAttributes.DELEGATE_TO_PREV_CHILD;
}
ASTNode lastChild = insertAfterBlock.getNode();
// HACK? This code fragment is needed to make testClass2() pass,
// but I don't quite understand why it is necessary and why the formatter
// doesn't request childAttributes from the correct block
while (lastChild != null) {
final IElementType lastType = lastChild.getElementType();
if (lastType == PyElementTypes.STATEMENT_LIST && hasLineBreaksBeforeInSameParent(lastChild, 1)) {
if (dedentAfterLastStatement((PyStatementList)lastChild.getPsi())) {
break;
}
statementListsBelow++;
}
else if (statementListsBelow > 0 && lastChild.getPsi() instanceof PsiErrorElement) {
statementListsBelow++;
}
if (myNode.getElementType() == PyElementTypes.STATEMENT_LIST && lastChild.getPsi() instanceof PsiErrorElement) {
return ChildAttributes.DELEGATE_TO_PREV_CHILD;
}
lastChild = getLastNonSpaceChild(lastChild, true);
}
}
// HACKETY-HACK
// If a multi-step dedent follows the cursor position (see testMultiDedent()),
// the whitespace (which must be a single Py:LINE_BREAK token) gets attached
// to the outermost indented block (because we may not consume the DEDENT
// tokens while parsing inner blocks). The policy is to put the indent to
// the innermost block, so we need to resolve the situation here. Nested
// delegation sometimes causes NPEs in formatter core, so we calculate the
// correct indent manually.
if (statementListsBelow > 0) { // was 1... strange
@SuppressWarnings("ConstantConditions") final int indent = myContext.getSettings().getIndentOptions().INDENT_SIZE;
return new ChildAttributes(Indent.getSpaceIndent(indent * statementListsBelow), null);
}
/*
// it might be something like "def foo(): # comment" or "[1, # comment"; jump up to the real thing
if (_node instanceof PsiComment || _node instanceof PsiWhiteSpace) {
get
}
*/
final Indent childIndent = getChildIndent(newChildIndex);
final Alignment childAlignment = getChildAlignment();
return new ChildAttributes(childIndent, childAlignment);
}
private static boolean dedentAfterLastStatement(@NotNull PyStatementList statementList) {
final PyStatement[] statements = statementList.getStatements();
if (statements.length == 0) {
return false;
}
final PyStatement last = statements[statements.length - 1];
return last instanceof PyReturnStatement || last instanceof PyRaiseStatement || last instanceof PyPassStatement || isEllipsis(last);
}
private static boolean isEllipsis(@NotNull PyStatement statement) {
if (statement instanceof PyExpressionStatement) {
final PyExpression expression = ((PyExpressionStatement)statement).getExpression();
if (expression instanceof PyNoneLiteralExpression) {
return ((PyNoneLiteralExpression)expression).isEllipsis();
}
}
return false;
}
@Nullable
private Alignment getChildAlignment() {
// TODO merge it with needListAlignment(ASTNode)
final IElementType nodeType = myNode.getElementType();
if (ourListElementTypes.contains(nodeType) ||
nodeType == PyElementTypes.SLICE_ITEM ||
nodeType == PyElementTypes.STRING_LITERAL_EXPRESSION) {
if (isInControlStatement()) {
return null;
}
final PsiElement elem = myNode.getPsi();
if (elem instanceof PyParameterList && !myContext.getSettings().ALIGN_MULTILINE_PARAMETERS) {
return null;
}
if ((elem instanceof PySequenceExpression || elem instanceof PyComprehensionElement) &&
!myContext.getPySettings().ALIGN_COLLECTIONS_AND_COMPREHENSIONS) {
return null;
}
if (elem instanceof PyParenthesizedExpression) {
final PyExpression parenthesized = ((PyParenthesizedExpression)elem).getContainedExpression();
if (parenthesized instanceof PyTupleExpression && !myContext.getPySettings().ALIGN_COLLECTIONS_AND_COMPREHENSIONS) {
return null;
}
}
if (elem instanceof PyDictLiteralExpression) {
final PyKeyValueExpression lastElement = ArrayUtil.getLastElement(((PyDictLiteralExpression)elem).getElements());
if (lastElement == null || lastElement.getValue() == null /* incomplete */) {
return null;
}
}
return getAlignmentForChildren();
}
return null;
}
@NotNull
private Indent getChildIndent(int newChildIndex) {
final ASTNode afterNode = getAfterNode(newChildIndex);
final ASTNode lastChild = getLastNonSpaceChild(myNode, false);
if (lastChild != null && lastChild.getElementType() == PyElementTypes.STATEMENT_LIST && mySubBlocks.size() >= newChildIndex) {
if (afterNode == null) {
return Indent.getNoneIndent();
}
// handle pressing Enter after colon and before first statement in
// existing statement list
if (afterNode.getElementType() == PyElementTypes.STATEMENT_LIST || afterNode.getElementType() == PyTokenTypes.COLON) {
return Indent.getNormalIndent();
}
// handle pressing Enter after colon when there is nothing in the
// statement list
final ASTNode lastFirstChild = lastChild.getFirstChildNode();
if (lastFirstChild != null && lastFirstChild == lastChild.getLastChildNode() && lastFirstChild.getPsi() instanceof PsiErrorElement) {
return Indent.getNormalIndent();
}
}
if (afterNode != null && afterNode.getElementType() == PyElementTypes.KEY_VALUE_EXPRESSION) {
final PyKeyValueExpression keyValue = (PyKeyValueExpression)afterNode.getPsi();
if (keyValue != null && keyValue.getValue() == null) { // incomplete
return Indent.getContinuationIndent();
}
}
final IElementType parentType = myNode.getElementType();
// constructs that imply indent for their children
final PyCodeStyleSettings settings = myContext.getPySettings();
if (parentType == PyElementTypes.PARAMETER_LIST ||
(parentType == PyElementTypes.ARGUMENT_LIST && settings.USE_CONTINUATION_INDENT_FOR_ARGUMENTS)) {
return Indent.getContinuationIndent();
}
if (ourCollectionLiteralTypes.contains(parentType) || parentType == PyElementTypes.TUPLE_EXPRESSION) {
return settings.USE_CONTINUATION_INDENT_FOR_COLLECTION_AND_COMPREHENSIONS ? Indent.getContinuationIndent() : Indent.getNormalIndent();
}
else if (ourListElementTypes.contains(parentType) || myNode.getPsi() instanceof PyStatementPart) {
return Indent.getNormalIndent();
}
if (afterNode != null) {
ASTNode wsAfter = afterNode.getTreeNext();
while (wsAfter != null && wsAfter.getElementType() == TokenType.WHITE_SPACE) {
if (wsAfter.getText().indexOf('\\') >= 0) {
return Indent.getNormalIndent();
}
wsAfter = wsAfter.getTreeNext();
}
}
return Indent.getNoneIndent();
}
@Nullable
private ASTNode getAfterNode(int newChildIndex) {
if (newChildIndex == 0) { // block text contains backslash line wrappings, child block list not built
return null;
}
int prevIndex = newChildIndex - 1;
while (prevIndex > 0 && getSubBlockByIndex(prevIndex).getNode().getElementType() == PyTokenTypes.END_OF_LINE_COMMENT) {
prevIndex--;
}
return getSubBlockByIndex(prevIndex).getNode();
}
private static ASTNode getLastNonSpaceChild(@NotNull ASTNode node, boolean acceptError) {
ASTNode lastChild = node.getLastChildNode();
while (lastChild != null &&
(lastChild.getElementType() == TokenType.WHITE_SPACE || (!acceptError && lastChild.getPsi() instanceof PsiErrorElement))) {
lastChild = lastChild.getTreePrev();
}
return lastChild;
}
@Override
public boolean isIncomplete() {
// if there's something following us, we're not incomplete
if (!PsiTreeUtil.hasErrorElements(myNode.getPsi())) {
PsiElement element = myNode.getPsi().getNextSibling();
while (element instanceof PsiWhiteSpace) {
element = element.getNextSibling();
}
if (element != null) {
return false;
}
}
final ASTNode lastChild = getLastNonSpaceChild(myNode, false);
if (lastChild != null) {
if (lastChild.getElementType() == PyElementTypes.STATEMENT_LIST) {
// only multiline statement lists are considered incomplete
final ASTNode statementListPrev = lastChild.getTreePrev();
if (statementListPrev != null && statementListPrev.getText().indexOf('\n') >= 0) {
return true;
}
}
if (lastChild.getElementType() == PyElementTypes.BINARY_EXPRESSION) {
final PyBinaryExpression binaryExpression = (PyBinaryExpression)lastChild.getPsi();
if (binaryExpression.getRightExpression() == null) {
return true;
}
}
if (isIncompleteCall(lastChild)) return true;
}
if (myNode.getPsi() instanceof PyArgumentList) {
final PyArgumentList argumentList = (PyArgumentList)myNode.getPsi();
return argumentList.getClosingParen() == null;
}
if (isIncompleteCall(myNode) || isIncompleteExpressionWithBrackets(myNode.getPsi())) {
return true;
}
return false;
}
private static boolean isIncompleteCall(@NotNull ASTNode node) {
if (node.getElementType() == PyElementTypes.CALL_EXPRESSION) {
final PyCallExpression callExpression = (PyCallExpression)node.getPsi();
final PyArgumentList argumentList = callExpression.getArgumentList();
if (argumentList == null || argumentList.getClosingParen() == null) {
return true;
}
}
return false;
}
private static boolean isIncompleteExpressionWithBrackets(@NotNull PsiElement elem) {
if (elem instanceof PySequenceExpression || elem instanceof PyComprehensionElement || elem instanceof PyParenthesizedExpression) {
return PyTokenTypes.OPEN_BRACES.contains(elem.getFirstChild().getNode().getElementType()) &&
!PyTokenTypes.CLOSE_BRACES.contains(elem.getLastChild().getNode().getElementType());
}
return false;
}
@Override
public boolean isLeaf() {
return myNode.getFirstChildNode() == null;
}
}
| Unify processing of dict/set and list literals and comprehensions indent in formatter
| python/src/com/jetbrains/python/formatter/PyBlock.java | Unify processing of dict/set and list literals and comprehensions indent in formatter |
|
Java | apache-2.0 | 62b2d31b9e8ecb35f98611c49a515e13c8e8fb1c | 0 | johnzeringue/guice,hazendaz/guice,WilliamRen/guice,mybatis/guice | /*
* Copyright 2010 The myBatis Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mybatis.guice.transactional;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.TransactionIsolationLevel;
/**
* Any method or class marked with this annotation will be considered for
* transactionality.
*
* @version $Id$
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Transactional {
/**
* Returns the constant indicating the myBatis executor type.
*
* @return the constant indicating the myBatis executor type.
*/
ExecutorType executorType() default ExecutorType.SIMPLE;
/**
* Returns the constant indicating the transaction isolation level.
*
* @return the constant indicating the transaction isolation level.
*/
TransactionIsolationLevel isolationLevel() default TransactionIsolationLevel.NONE;
/**
* Flag to indicate that myBatis has to force the transaction {@code commit().}
*
* @return false by default, user defined otherwise.
*/
boolean force() default false;
/**
* Flag to indicate the auto commit policy on the {@link Connection}.
*
* @return false by default, user defined otherwise.
*/
boolean autoCommit() default false;
/**
* The exception re-thrown when an error occurs during the transaction.
*
* @return the exception re-thrown when an error occurs during the
* transaction.
*/
Class<? extends Throwable> rethrowExceptionsAs() default Exception.class;
/**
* A custom error message when throwing the custom exception.
*
* It supports java.text.MessageFormat place holders, intercepted method
* arguments will be used as message format arguments.
*
* @return a custom error message when throwing the custom exception.
* @see java.text.MessageFormat#format(String, Object...)
*/
String exceptionMessage() default "";
}
| src/main/java/org/mybatis/guice/transactional/Transactional.java | /*
* Copyright 2010 The myBatis Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mybatis.guice.transactional;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.sql.Connection;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.TransactionIsolationLevel;
/**
* Any method or class marked with this annotation will be considered for
* transactionality.
*
* @version $Id$
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Transactional {
/**
* Returns the constant indicating the myBatis executor type.
*
* @return the constant indicating the myBatis executor type.
*/
ExecutorType executorType() default ExecutorType.SIMPLE;
/**
* Returns the constant indicating the transaction isolation level.
*
* @return the constant indicating the transaction isolation level.
*/
TransactionIsolationLevel isolationLevel() default TransactionIsolationLevel.NONE;
/**
* Flag to indicate that myBatis has to force the transaction {@code commit().}
*
* @return false by default, user defined otherwise.
*/
boolean force() default false;
/**
* Flag to indicate the auto commit policy on the {@link Connection}.
*
* @return false by default, user defined otherwise.
*/
boolean autoCommit() default false;
/**
* The exception re-thrown when an error occurs during the transaction.
*
* @return the exception re-thrown when an error occurs during the
* transaction.
*/
Class<? extends Throwable> rethrowExceptionsAs() default Exception.class;
/**
* A custom error message when throwing the custom exception.
*
* It supports java.text.MessageFormat place holders, intercepted method
* arguments will be used as message format arguments.
*
* @return a custom error message when throwing the custom exception.
* @see java.text.MessageFormat#format(String, Object...)
*/
String exceptionMessage() default "";
}
| removed unused import
| src/main/java/org/mybatis/guice/transactional/Transactional.java | removed unused import |
|
Java | bsd-2-clause | fb7053d4361dc6bab3fb46305395e62436d24826 | 0 | scifio/scifio | //
// MetadataPane.java
//
package loci.ome.notebook;
import java.awt.*;
import java.io.*;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import loci.formats.RandomAccessStream;
import loci.formats.TiffTools;
import loci.formats.ReflectedUniverse;
import org.openmicroscopy.xml.*;
import org.w3c.dom.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.table.*;
/** MetadataPane is a panel that displays OME-XML metadata. */
public class MetadataPane extends JPanel
implements Runnable
{
// -- Constants --
protected static final String[] TREE_COLUMNS = {"Attribute", "Value"};
// -- Fields --
/** Table model for attributes table*/
DefaultTableModel myTableModel;
/** Pane containing XML tree. */
protected JTabbedPane tabPane;
/** TemplateParser object*/
protected TemplateParser tParse;
/** Keeps track of the OMENode being operated on currently*/
protected OMENode thisOmeNode;
/** A list of all TablePanel objects */
protected Vector panelList;
/** A list of TablePanel objects that have ID */
protected Vector panelsWithID;
// -- Fields - raw panel --
/** Panel containing raw XML dump. */
protected JPanel rawPanel;
/** Text area displaying raw XML. */
protected JTextArea rawText;
/** Whether XML is being displayed in raw form. */
protected boolean raw;
// -- Constructor --
/** Constructs widget for displaying OME-XML metadata. */
public MetadataPane(TemplateParser tp) {
panelList = new Vector();
panelsWithID = new Vector();
tParse = tp;
thisOmeNode = null;
// -- Tabbed Pane Initialization --
tabPane = new JTabbedPane(JTabbedPane.TOP, JTabbedPane.WRAP_TAB_LAYOUT);
setupTabs();
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
add(tabPane);
tabPane.setVisible(true);
// -- Raw panel --
raw = false;
rawPanel = new JPanel();
rawPanel.setLayout(new BorderLayout());
// label explaining what happened
JLabel rawLabel = new JLabel("Metadata parsing failed. " +
"Here is the raw info. Good luck!");
rawLabel.setBorder(new EmptyBorder(5, 0, 5, 0));
rawPanel.add(rawLabel, BorderLayout.NORTH);
// text area for displaying raw XML
rawText = new JTextArea();
rawText.setLineWrap(true);
rawText.setColumns(50);
rawText.setRows(30);
rawText.setEditable(false);
rawPanel.add(new JScrollPane(rawText), BorderLayout.CENTER);
rawPanel.setVisible(false);
add(rawPanel);
}
// -- MetadataPane API methods --
/**
* retrieves the current document object describing the whole OMEXMLNode tree
*/
public Document getDoc() {
Document doc = null;
try {
doc = thisOmeNode.getOMEDocument(false);
}
catch (Exception e) { }
return doc;
}
/**
* Sets the displayed OME-XML metadata to correspond
* to the given character string of XML.
*/
public void setOMEXML(String xml) {
OMENode ome = null;
try { ome = new OMENode(xml); }
catch (Exception exc) { }
raw = ome == null;
if (raw) rawText.setText(xml);
else setOMEXML(ome);
SwingUtilities.invokeLater(this);
}
/**
* Sets the displayed OME-XML metadata to correspond
* to the given OME-XML or OME-TIFF file.
* @return true if the operation was successful
*/
public boolean setOMEXML(File file) {
try {
DataInputStream in = new DataInputStream(new FileInputStream(file));
byte[] header = new byte[8];
in.readFully(header);
if (TiffTools.isValidHeader(header)) {
// TIFF file
in.close();
RandomAccessStream ras = new RandomAccessStream(file.getPath());
Hashtable ifd = TiffTools.getFirstIFD(ras);
ras.close();
if (ifd == null) return false;
Object value = TiffTools.getIFDValue(ifd, TiffTools.IMAGE_DESCRIPTION);
String xml = null;
if (value instanceof String) xml = (String) value;
else if (value instanceof String[]) {
String[] s = (String[]) value;
StringBuffer sb = new StringBuffer();
for (int i=0; i<s.length; i++) sb.append(s[i]);
xml = sb.toString();
}
if (xml == null) return false;
setOMEXML(xml);
}
else {
String s = new String(header).trim();
if (s.startsWith("<?xml") || s.startsWith("<OME")) {
// raw OME-XML
byte[] data = new byte[(int) file.length()];
System.arraycopy(header, 0, data, 0, 8);
in.readFully(data, 8, data.length - 8);
in.close();
setOMEXML(new String(data));
}
else return false;
}
return true;
}
catch (IOException exc) { return false; }
}
/** Sets the displayed OME-XML metadata. */
public void setOMEXML(OMENode ome) {
// populate OME-XML tree
Document doc = null;
try { doc = ome == null ? null : ome.getOMEDocument(false); }
catch (Exception exc) { }
if (doc != null) {
thisOmeNode = ome;
setupTabs(ome);
}
}
/** Sets up the JTabbedPane based on a template, assumes that no OMEXML
* file is being compared to the template, so no data will be displayed.
* should be used to initialize the application and to create new OMEXML
* documents based on the template
*/
public void setupTabs() {
panelList = new Vector();
panelsWithID = new Vector();
tabPane.removeAll();
Element[] tabList = tParse.getTabs();
for(int i = 0;i< tabList.length;i++) {
String thisName = tabList[i].getAttribute("Name");
if(thisName.length() == 0) thisName = tabList[i].getAttribute("XMLName");
TabPanel tPanel = new TabPanel(tabList[i]);
OMEXMLNode n = null;
try {
//reflect api gets around large switch statements
thisOmeNode = new OMENode();
ReflectedUniverse r = new ReflectedUniverse();
String unknownName = tabList[i].getAttribute("XMLName");
if (unknownName.equals("Project") || unknownName.equals("Feature") || unknownName.equals("CustomAttributes") || unknownName.equals("Dataset") || unknownName.equals("Image")) {
r.exec("import org.openmicroscopy.xml." + unknownName + "Node");
}
else r.exec("import org.openmicroscopy.xml.st." + unknownName + "Node");
r.setVar("parent", thisOmeNode);
r.exec("result = new " + unknownName + "Node(parent)");
n = (OMEXMLNode) r.getVar("result");
}
catch (Exception exc) {
System.out.println(exc.toString());
}
tPanel.oNode = n;
renderTab(tPanel);
JScrollPane scrollPane = new JScrollPane(tPanel);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
String desc = tabList[i].getAttribute("Description");
if (desc.length() == 0) tabPane.addTab(thisName, null, scrollPane, null);
else tabPane.addTab(thisName, null, scrollPane, desc);
int keyNumber = getKey(i+1);
if(keyNumber !=0 ) tabPane.setMnemonicAt(i, keyNumber);
}
JComboBox box = new JComboBox();
for (int i = 0;i<panelsWithID.size();i++) {
TablePanel p = (TablePanel) panelsWithID.get(i);
box.addItem(p.name);
}
for (int i = 0;i<panelList.size();i++) {
TablePanel p = (TablePanel) panelList.get(i);
p.setEditor(box);
}
}
/** sets up the JTabbedPane given an OMENode from an OMEXML file.
* the template will set which parts of the file are displayed.
*/
public void setupTabs(OMENode ome) {
tabPane.removeAll();
panelList = new Vector();
panelsWithID = new Vector();
Element[] tabList = tParse.getTabs();
Vector actualTabs = new Vector(2 * tabList.length);
for(int i = 0;i< tabList.length;i++) {
Vector inOmeList = null;
String aName = tabList[i].getAttribute("XMLName");
if( aName.equals("Image") || aName.equals("Feature") || aName.equals("Dataset") || aName.equals("Project") ) inOmeList = ome.getChildren(aName);
else inOmeList = ome.getChild("CustomAttributes").getChildren(aName);
int vSize = inOmeList.size();
if(vSize >0) {
for(int j = 0;j<vSize;j++) {
String thisName = tabList[i].getAttribute("Name");
if(thisName.length() == 0) thisName = tabList[i].getAttribute("XMLName");
TabPanel tPanel = new TabPanel(tabList[i]);
tPanel.oNode = (OMEXMLNode) inOmeList.get(j);
renderTab(tPanel);
JScrollPane scrollPane = new JScrollPane(tPanel);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
String desc = tabList[i].getAttribute("Description");
if (vSize > 1) {
Integer jInt = new Integer(j+1);
thisName = thisName + " (" + jInt.toString() + ")";
tPanel.name = thisName;
tPanel.copyNumber = j + 1;
}
if (desc.length() == 0) tabPane.addTab(thisName, null, scrollPane, null);
else tabPane.addTab(thisName, null, scrollPane, desc);
actualTabs.add(tabList[i]);
}
}
else {
String thisName = tabList[i].getAttribute("Name");
if(thisName.length() == 0) thisName = tabList[i].getAttribute("XMLName");
TabPanel tPanel = new TabPanel(tabList[i]);
renderTab(tPanel);
JScrollPane scrollPane = new JScrollPane(tPanel);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
String desc = tabList[i].getAttribute("Description");
if (desc.length() == 0) tabPane.addTab(thisName, null, scrollPane, null);
else tabPane.addTab(thisName, null, scrollPane, desc);
actualTabs.add(tabList[i]);
}
}
for(int i = 0;i<actualTabs.size();i++) {
int keyNumber = getKey(i+1);
if(keyNumber !=0 ) tabPane.setMnemonicAt(i, keyNumber);
}
MetadataNotebook mn = (MetadataNotebook) getParent().getParent().getParent();
mn.changeTabMenu(actualTabs.toArray());
JComboBox box = new JComboBox();
for (int i = 0;i<panelsWithID.size();i++) {
TablePanel p = (TablePanel) panelsWithID.get(i);
box.addItem(p.name);
}
for (int i = 0;i<panelList.size();i++) {
TablePanel p = (TablePanel) panelList.get(i);
p.setEditor(box);
}
}
/** fleshes out the GUI of a given TabPanel
*/
public void renderTab(TabPanel tp) {
if(!tp.isRendered) {
tp.isRendered = true;
tp.removeAll();
//Set up the GridBagLayout
JPanel dataPanel = new JPanel();
dataPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.NORTHWEST;
Insets ins = new Insets(10,10,10,10);
gbc.insets = ins;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.gridheight = 1;
//placeY will hold info on which position to add a new component to the layout
int placeY = 0;
//add a title label to show which element
JPanel titlePanel = new JPanel();
titlePanel.setLayout(new GridLayout(2,1));
JLabel title = new JLabel();
Font thisFont = title.getFont();
Font newFont = new Font(thisFont.getFontName(),Font.BOLD,18);
title.setFont(newFont);
title.setText(" " + tp.name + ":");
titlePanel.add(title);
//if title has a description, add it in italics
if (tp.el.hasAttribute("Description")) {
if(tp.el.getAttribute("Description").length() != 0) {
JLabel descrip = new JLabel();
newFont = new Font(thisFont.getFontName(),Font.ITALIC,thisFont.getSize());
descrip.setFont(newFont);
descrip.setText( " " + tp.el.getAttribute("Description"));
ins = new Insets(10,30,10,10);
titlePanel.add(descrip);
}
}
tp.setLayout(new BorderLayout());
tp.add(titlePanel,BorderLayout.NORTH);
tp.add(dataPanel,BorderLayout.CENTER);
gbc.gridy = placeY;
TablePanel pan = new TablePanel(tp.el, tp, tp.oNode);
dataPanel.add(pan,gbc);
placeY++;
ins = new Insets(10,30,10,10);
gbc.insets = ins;
Vector theseElements = DOMUtil.getChildElements("OMEElement",tp.el);
Vector branchElements = new Vector(theseElements.size());
for(int i = 0;i<theseElements.size();i++) {
Element e = null;
if (theseElements.get(i) instanceof Element) e = (Element) theseElements.get(i);
if (DOMUtil.getChildElements("OMEElement",e).size() != 0) {
branchElements.add(e);
}
else {
if(tp.oNode != null) {
Vector v = new Vector();
String aName = e.getAttribute("XMLName");
if( aName.equals("Image") || aName.equals("Feature") || aName.equals("Dataset") || aName.equals("Project") ) v = tp.oNode.getChildren(aName);
else if (tp.oNode.getChild("CustomAttributes") != null) v = tp.oNode.getChild("CustomAttributes").getChildren(aName);
if (v.size() == 0) {
//Use reflect api to avoid large switch statement to handle construction of different nodes
//OMEXMLNode child classes
OMEXMLNode n = null;
try {
ReflectedUniverse r = new ReflectedUniverse();
String unknownName = e.getAttribute("XMLName");
if (unknownName.equals("Project") || unknownName.equals("Feature") || unknownName.equals("CustomAttributes") || unknownName.equals("Dataset") || unknownName.equals("Image")) {
r.exec("import org.openmicroscopy.xml." + unknownName + "Node");
}
else r.exec("import org.openmicroscopy.xml.st." + unknownName + "Node");
r.setVar("parent", tp.oNode);
r.exec("result = new " + unknownName + "Node(parent)");
n = (OMEXMLNode) r.getVar("result");
}
catch (Exception exc) {
System.out.println(exc.toString());
}
gbc.gridy = placeY;
TablePanel p = new TablePanel(e, tp, n);
dataPanel.add(p,gbc);
placeY++;
}
else {
for(int j = 0;j<v.size();j++) {
OMEXMLNode n = (OMEXMLNode) v.get(j);
gbc.gridy = placeY;
TablePanel p = new TablePanel(e, tp, n);
dataPanel.add(p,gbc);
placeY++;
}
}
}
else {
OMEXMLNode n = null;
gbc.gridy = placeY;
TablePanel p = new TablePanel(e, tp, n);
dataPanel.add(p,gbc);
placeY++;
}
}
}
}
}
public String getTreePathName(Element e) {
String thisName = null;
if(e.hasAttribute("Name"))thisName = e.getAttribute("Name");
else thisName = e.getAttribute("XMLName");
Element aParent = DOMUtil.getAncestorElement("OMEElement",e);
while(aParent != null) {
if(aParent.hasAttribute("Name")) thisName = aParent.getAttribute("Name") + thisName;
else thisName = aParent.getAttribute("XMLName") + ": " + thisName;
aParent = DOMUtil.getAncestorElement("OMEElement",aParent);
}
return thisName;
}
public String getTreePathName(Element el, OMEXMLNode on) {
Vector pathList = new Vector();
Element aParent = on.getDOMElement();
Vector pathNames = getTreePathList(el);
pathNames.add("OME");
pathList.add(aParent);
for (int i = 1;i<pathNames.size();i++) {
String s = (String) pathNames.get(i);
aParent = DOMUtil.getAncestorElement(s, aParent);
pathList.add(0,aParent);
}
String result = "";
for (int i = 0;i<pathList.size() - 1;i++) {
aParent = (Element) pathList.get(i);
Element aChild = (Element) pathList.get(i+1);
String thisName = aChild.getTagName();
NodeList nl = aParent.getElementsByTagName(thisName);
if (nl.getLength() == 1) {
Element e = (Element) nl.item(0);
if (i == 0) result = result + e.getTagName();
else result = result + ": " + e.getTagName();
}
else {
for (int j = 0;j<nl.getLength();j++) {
Element e = (Element) nl.item(j);
if (e == aChild) {
Integer aInt = new Integer(j+1);
if (i == 0) result = result + e.getTagName() + " (" + aInt.toString() + ")";
else result = result + ": " + e.getTagName() + " (" + aInt.toString() + ")";
}
}
}
}
return result;
}
/** returns a vector of Strings representing the XMLNames of the
* template's ancestors in ascending order in the list.
*/
public Vector getTreePathList(Element e) {
Vector thisPath = new Vector(10);
thisPath.add(e.getAttribute("XMLName"));
Element aParent = DOMUtil.getAncestorElement("OMEElement",e);
while(aParent != null) {
thisPath.add(aParent.getAttribute("XMLName"));
aParent = DOMUtil.getAncestorElement("OMEElement",aParent);
}
return thisPath;
}
/*changes the selected tab to tab of index i
*/
public void tabChange(int i) {
tabPane.setSelectedIndex(i);
}
/* gets around an annoying GUI layout problem when window is resized.
public void fixTables()
// -- Component API methods --
/** Sets the initial size of the metadata pane to be reasonable. */
public Dimension getPreferredSize() { return new Dimension(700, 500); }
// -- Runnable API methods --
/** Shows or hides the proper subpanes. */
public void run() {
tabPane.setVisible(!raw);
rawPanel.setVisible(raw);
validate();
repaint();
}
// -- Event API methods --
// -- Static methods --
public static int getKey(int i) {
int keyNumber = 0;
switch (i) {
case 1 :
keyNumber = KeyEvent.VK_1;
break;
case 2 :
keyNumber = KeyEvent.VK_2;
break;
case 3 :
keyNumber = KeyEvent.VK_3;
break;
case 4 :
keyNumber = KeyEvent.VK_4;
break;
case 5 :
keyNumber = KeyEvent.VK_5;
break;
case 6 :
keyNumber = KeyEvent.VK_6;
break;
case 7 :
keyNumber = KeyEvent.VK_7;
break;
case 8 :
keyNumber = KeyEvent.VK_8;
break;
case 9 :
keyNumber = KeyEvent.VK_9;
break;
case 10 :
keyNumber = KeyEvent.VK_0;
break;
default:
keyNumber = 0;
}
return keyNumber;
}
// -- Helper classes --
/** Helper class to make my life easier in the creation and use of tabs
* associates a given xml template element and also an optional OMEXMLNode
* with a JPanel that represents the content of a tab.
*/
public class TabPanel extends JPanel {
public Element el;
public String name;
private boolean isRendered;
public OMEXMLNode oNode;
public int copyNumber;
public TabPanel(Element el) {
copyNumber = 0;
isRendered = false;
this.el = el;
oNode = null;
name = getTreePathName(el);
}
public String toString() { return el == null ? "null" : el.getTagName(); }
}
/** Helper class to handle the "GOTO" buttons that take you to a particular
* Element ID's representation in the program.
*/
public class TableButton extends JButton {
public JTable table;
public int whichRow;
public TableButton( JTable jt, int i) {
super("Goto");
table = jt;
whichRow = i;
Integer aInt = new Integer(i);
setActionCommand("goto");
Dimension d = new Dimension(70,15);
setPreferredSize(d);
}
}
/** Helper class to handle the various TablePanels that will be created to
* display the attributes of Elements that have no nested Elements
*/
public class TablePanel extends JPanel
implements TableModelListener, ActionListener
{
public OMEXMLNode oNode;
public TabPanel tPanel;
public String id;
public String name;
public JComboBox comboBox;
public JTable newTable, refTable;
public TablePanel(Element e, TabPanel tp, OMEXMLNode on) {
oNode = on;
tPanel = tp;
id = null;
newTable = null;
refTable = null;
comboBox = null;
name = getTreePathName(e,on);
String thisName = getTreePathName(e, on);
panelList.add(this);
Vector fullList = DOMUtil.getChildElements("OMEAttribute",e);
Vector attrList = new Vector();
Vector refList = new Vector();
for(int i = 0;i<fullList.size();i++) {
Element thisE = (Element) fullList.get(i);
if(thisE.hasAttribute("Type") ) {
if(thisE.getAttribute("Type").equals("Ref") ) refList.add(thisE);
else if(thisE.getAttribute("Type").equals("ID") && oNode != null) {
if (oNode.getDOMElement().hasAttribute("ID")) {
id = oNode.getAttribute("ID");
panelsWithID.add(this);
}
else {
//CODE HERE TO CREATE A UNIQUE ID
}
}
else attrList.add(thisE);
}
else attrList.add(thisE);
}
Element cDataEl = DOMUtil.getChildElement("CData",e);
if (cDataEl != null) attrList.add(0,cDataEl);
JPanel lowPanel = new JPanel();
if (attrList.size() != 0) {
myTableModel = new DefaultTableModel(TREE_COLUMNS, 0) {
public boolean isCellEditable(int row, int col) {
if(col < 1) return false;
else return true;
}
};
myTableModel.addTableModelListener(this);
setLayout(new GridLayout(0,1));
JLabel tableName = new JLabel(thisName);
newTable = new JTable(myTableModel);
newTable.getColumnModel().getColumn(0).setPreferredWidth(150);
newTable.getColumnModel().getColumn(1).setPreferredWidth(475);
JTableHeader tHead = newTable.getTableHeader();
tHead.setResizingAllowed(false);
tHead.setReorderingAllowed(false);
JPanel headerPanel = new JPanel();
headerPanel.setLayout(new BorderLayout());
JPanel aPanel = new JPanel();
aPanel.setLayout(new BorderLayout());
aPanel.add(tableName,BorderLayout.SOUTH);
lowPanel.setLayout(new BorderLayout());
lowPanel.add(newTable,BorderLayout.NORTH);
headerPanel.add(aPanel, BorderLayout.CENTER);
headerPanel.add(tHead, BorderLayout.SOUTH);
add(headerPanel);
add(lowPanel);
// update OME-XML attributes table
myTableModel.setRowCount(attrList.size());
for (int i=0; i<attrList.size(); i++) {
Element thisEle = null;
if (attrList.get(i) instanceof Element) thisEle = (Element) attrList.get(i);
if (thisEle != null) {
String attrName = thisEle.getAttribute("XMLName");
if (thisEle.hasAttribute("Name")) {
myTableModel.setValueAt(thisEle.getAttribute("Name"), i, 0);
if(oNode != null) {
if(oNode.getDOMElement().hasAttribute(attrName)) {
myTableModel.setValueAt(oNode.getAttribute(attrName), i, 1);
}
}
}
else if (thisEle.hasAttribute("XMLName")) {
myTableModel.setValueAt(thisEle.getAttribute("XMLName"), i, 0);
if(oNode != null) {
if(oNode.getDOMElement().hasAttribute(attrName)) {
myTableModel.setValueAt(oNode.getAttribute(attrName), i, 1);
}
}
}
else {
if(e.hasAttribute("Name")) myTableModel.setValueAt(e.getAttribute("Name") + " CharData", i, 0);
else myTableModel.setValueAt(e.getAttribute("XMLName") + " CharData", i, 0);
if(oNode != null && DOMUtil.getCharacterData(oNode.getDOMElement() ) != null) {
myTableModel.setValueAt(DOMUtil.getCharacterData(oNode.getDOMElement() ), i, 1);
}
}
}
}
}
if (refList.size() > 0) {
myTableModel = new DefaultTableModel(TREE_COLUMNS, 0) {
public boolean isCellEditable(int row, int col) {
if(col < 1) return false;
else return true;
}
};
refTable = new JTable(myTableModel);
refTable.getColumnModel().getColumn(0).setPreferredWidth(150);
refTable.getColumnModel().getColumn(1).setPreferredWidth(405);
TableColumn refColumn = refTable.getColumnModel().getColumn(1);
comboBox = new JComboBox();
refColumn.setCellEditor(new DefaultCellEditor(comboBox));
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(0,1));
myTableModel.setRowCount(refList.size());
for (int i=0; i<refList.size(); i++) {
Element thisEle = null;
if (refList.get(i) instanceof Element) thisEle = (Element) refList.get(i);
if (thisEle != null) {
if (thisEle.hasAttribute("Name")) myTableModel.setValueAt(thisEle.getAttribute("Name"), i, 0);
else if (thisEle.hasAttribute("XMLName")) myTableModel.setValueAt(thisEle.getAttribute("XMLName"), i, 0);
}
TableButton tb = new TableButton(refTable,i);
tb.addActionListener(this);
buttonPanel.add(tb);
}
Dimension dim = new Dimension(50, buttonPanel.getHeight());
buttonPanel.setSize(dim);
if(attrList.size() == 0) {
setLayout(new GridLayout(0,1));
JLabel tableName = new JLabel(thisName);
JTableHeader tHead = refTable.getTableHeader();
tHead.setResizingAllowed(false);
tHead.setReorderingAllowed(false);
JPanel headerPanel = new JPanel();
headerPanel.setLayout(new BorderLayout());
JPanel aPanel = new JPanel();
aPanel.setLayout(new BorderLayout());
aPanel.add(tableName,BorderLayout.SOUTH);
lowPanel.setLayout(new BorderLayout());
lowPanel.add(refTable,BorderLayout.NORTH);
headerPanel.add(aPanel, BorderLayout.CENTER);
headerPanel.add(tHead, BorderLayout.SOUTH);
add(headerPanel);
add(lowPanel);
JPanel refPanel = new JPanel();
refPanel.setLayout(new BorderLayout());
refPanel.add(refTable, BorderLayout.CENTER);
refPanel.add(buttonPanel, BorderLayout.EAST);
JPanel placePanel = new JPanel();
placePanel.setLayout(new BorderLayout());
placePanel.add(refPanel, BorderLayout.NORTH);
lowPanel.add(placePanel, BorderLayout.CENTER);
}
else {
JPanel refPanel = new JPanel();
refPanel.setLayout(new BorderLayout());
refPanel.add(refTable, BorderLayout.CENTER);
refPanel.add(buttonPanel, BorderLayout.EAST);
JPanel placePanel = new JPanel();
placePanel.setLayout(new BorderLayout());
placePanel.add(refPanel, BorderLayout.NORTH);
lowPanel.add(placePanel, BorderLayout.CENTER);
}
}
}
public void setEditor(JComboBox jcb) {
if(refTable != null) {
TableModel model = refTable.getModel();
TableColumn refColumn = refTable.getColumnModel().getColumn(1);
Vector addItems = new Vector();
for(int i = 0;i < refTable.getRowCount();i++) {
boolean isLocal = false;
String attrName = (String) model.getValueAt(i,0);
String value = oNode.getAttribute(attrName);
for(int j = 0;j < panelsWithID.size();j++) {
TablePanel tp = (TablePanel) panelsWithID.get(j);
if (tp.id != null && value != null) {
if (value.equals(tp.id)) {
isLocal = true;
model.setValueAt(tp.name,i,1);
}
}
}
if(!isLocal && value != null) {
model.setValueAt(value,i,1);
addItems.add(value);
}
}
/*
Vector v = new Vector();
for(int i = 0;i < addItems.size();i++) {
System.out.println("Original: \"" + addItems.get(i).toString());
if (v.indexOf(addItems.get(i)) < 0) v.add(addItems.get(i));
}
for(int i = 0;i < v.size();i++) {
System.out.println("Next: \"" + addItems.get(i).toString());
String name = (String) v.get(i);
jcb.addItem(name);
}
*/
comboBox = jcb;
refColumn.setCellEditor(new DefaultCellEditor(jcb));
}
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof TableButton) {
TableButton tb = (TableButton) e.getSource();
JTable jt = tb.table;
System.out.println("The row being editted: " + tb.whichRow);
TableModel model = jt.getModel();
Object obj = model.getValueAt(tb.whichRow, 1);
String aName = obj.toString();
TablePanel aPanel = null;
int whichNum = -1;
for(int i = 0;i<panelsWithID.size();i++) {
aPanel = (TablePanel) panelsWithID.get(i);
if (aPanel.name.equals(aName)) whichNum = i;
}
if(whichNum < panelsWithID.size()) {
TablePanel tablePan = (TablePanel) panelsWithID.get(whichNum);
TabPanel tp = tablePan.tPanel;
Container anObj = (Container) tp;
while(!(anObj instanceof JScrollPane)) {
anObj = anObj.getParent();
}
JScrollPane jScr = (JScrollPane) anObj;
while(!(anObj instanceof JTabbedPane)) {
anObj = anObj.getParent();
}
JTabbedPane jTabP = (JTabbedPane) anObj;
jTabP.setSelectedComponent(jScr);
System.out.println(jt.getLocation().toString());
System.out.println(tablePan.getAlignmentY());
// tablePan.newTable.grabFocus();
// jScr.getViewport().setViewPosition(tablePan.getLocationOnScreen());
}
}
}
public void tableChanged(TableModelEvent e) {
int column = e.getColumn();
if (e.getType() == TableModelEvent.UPDATE && column == 1 && ((TableModel) e.getSource()) == newTable.getModel()) {
int row = e.getFirstRow();
TableModel model = (TableModel) e.getSource();
String data = (String) model.getValueAt(row, column);
String attr = (String) model.getValueAt(row,0);
if ( data != null && !data.equals("") ) {
if (attr.endsWith("CharData") ) {
DOMUtil.setCharacterData(data, oNode.getDOMElement());
}
if (oNode != null) oNode.setAttribute(attr, data);
}
}
}
}
}
| loci/ome/notebook/MetadataPane.java | //
// MetadataPane.java
//
package loci.ome.notebook;
import java.awt.*;
import java.io.*;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import loci.formats.RandomAccessStream;
import loci.formats.TiffTools;
import loci.formats.ReflectedUniverse;
import org.openmicroscopy.xml.*;
import org.w3c.dom.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.table.*;
/** MetadataPane is a panel that displays OME-XML metadata. */
public class MetadataPane extends JPanel
implements Runnable
{
// -- Constants --
protected static final String[] TREE_COLUMNS = {"Attribute", "Value"};
// -- Fields --
/** Table model for attributes table*/
DefaultTableModel myTableModel;
/** Pane containing XML tree. */
protected JTabbedPane tabPane;
/** TemplateParser object*/
protected TemplateParser tParse;
/** Keeps track of the OMENode being operated on currently*/
protected OMENode thisOmeNode;
/** A list of all TablePanel objects */
protected Vector panelList;
/** A list of TablePanel objects that have ID */
protected Vector panelsWithID;
// -- Fields - raw panel --
/** Panel containing raw XML dump. */
protected JPanel rawPanel;
/** Text area displaying raw XML. */
protected JTextArea rawText;
/** Whether XML is being displayed in raw form. */
protected boolean raw;
// -- Constructor --
/** Constructs widget for displaying OME-XML metadata. */
public MetadataPane(TemplateParser tp) {
panelList = new Vector();
panelsWithID = new Vector();
tParse = tp;
thisOmeNode = null;
// -- Tabbed Pane Initialization --
tabPane = new JTabbedPane(JTabbedPane.TOP, JTabbedPane.WRAP_TAB_LAYOUT);
setupTabs();
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
add(tabPane);
tabPane.setVisible(true);
// -- Raw panel --
raw = false;
rawPanel = new JPanel();
rawPanel.setLayout(new BorderLayout());
// label explaining what happened
JLabel rawLabel = new JLabel("Metadata parsing failed. " +
"Here is the raw info. Good luck!");
rawLabel.setBorder(new EmptyBorder(5, 0, 5, 0));
rawPanel.add(rawLabel, BorderLayout.NORTH);
// text area for displaying raw XML
rawText = new JTextArea();
rawText.setLineWrap(true);
rawText.setColumns(50);
rawText.setRows(30);
rawText.setEditable(false);
rawPanel.add(new JScrollPane(rawText), BorderLayout.CENTER);
rawPanel.setVisible(false);
add(rawPanel);
}
// -- MetadataPane API methods --
/**
* retrieves the current document object describing the whole OMEXMLNode tree
*/
public Document getDoc() {
Document doc = null;
try {
doc = thisOmeNode.getOMEDocument(false);
}
catch (Exception e) { }
return doc;
}
/**
* Sets the displayed OME-XML metadata to correspond
* to the given character string of XML.
*/
public void setOMEXML(String xml) {
OMENode ome = null;
try { ome = new OMENode(xml); }
catch (Exception exc) { }
raw = ome == null;
if (raw) rawText.setText(xml);
else setOMEXML(ome);
SwingUtilities.invokeLater(this);
}
/**
* Sets the displayed OME-XML metadata to correspond
* to the given OME-XML or OME-TIFF file.
* @return true if the operation was successful
*/
public boolean setOMEXML(File file) {
try {
DataInputStream in = new DataInputStream(new FileInputStream(file));
byte[] header = new byte[8];
in.readFully(header);
if (TiffTools.isValidHeader(header)) {
// TIFF file
in.close();
RandomAccessStream ras = new RandomAccessStream(file.getPath());
Hashtable ifd = TiffTools.getFirstIFD(ras);
ras.close();
if (ifd == null) return false;
Object value = TiffTools.getIFDValue(ifd, TiffTools.IMAGE_DESCRIPTION);
String xml = null;
if (value instanceof String) xml = (String) value;
else if (value instanceof String[]) {
String[] s = (String[]) value;
StringBuffer sb = new StringBuffer();
for (int i=0; i<s.length; i++) sb.append(s[i]);
xml = sb.toString();
}
if (xml == null) return false;
setOMEXML(xml);
}
else {
String s = new String(header).trim();
if (s.startsWith("<?xml") || s.startsWith("<OME")) {
// raw OME-XML
byte[] data = new byte[(int) file.length()];
System.arraycopy(header, 0, data, 0, 8);
in.readFully(data, 8, data.length - 8);
in.close();
setOMEXML(new String(data));
}
else return false;
}
return true;
}
catch (IOException exc) { return false; }
}
/** Sets the displayed OME-XML metadata. */
public void setOMEXML(OMENode ome) {
// populate OME-XML tree
Document doc = null;
try { doc = ome == null ? null : ome.getOMEDocument(false); }
catch (Exception exc) { }
if (doc != null) {
thisOmeNode = ome;
setupTabs(ome);
}
}
/** Sets up the JTabbedPane based on a template, assumes that no OMEXML
* file is being compared to the template, so no data will be displayed.
* should be used to initialize the application and to create new OMEXML
* documents based on the template
*/
public void setupTabs() {
panelList = new Vector();
panelsWithID = new Vector();
tabPane.removeAll();
Element[] tabList = tParse.getTabs();
for(int i = 0;i< tabList.length;i++) {
String thisName = tabList[i].getAttribute("Name");
if(thisName.length() == 0) thisName = tabList[i].getAttribute("XMLName");
TabPanel tPanel = new TabPanel(tabList[i]);
OMEXMLNode n = null;
try {
//reflect api gets around large switch statements
thisOmeNode = new OMENode();
ReflectedUniverse r = new ReflectedUniverse();
String unknownName = tabList[i].getAttribute("XMLName");
if (unknownName.equals("Project") || unknownName.equals("Feature") || unknownName.equals("CustomAttributes") || unknownName.equals("Dataset") || unknownName.equals("Image")) {
r.exec("import org.openmicroscopy.xml." + unknownName + "Node");
}
else r.exec("import org.openmicroscopy.xml.st." + unknownName + "Node");
r.setVar("parent", thisOmeNode);
r.exec("result = new " + unknownName + "Node(parent)");
n = (OMEXMLNode) r.getVar("result");
}
catch (Exception exc) {
System.out.println(exc.toString());
}
tPanel.oNode = n;
renderTab(tPanel);
JScrollPane scrollPane = new JScrollPane(tPanel);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
String desc = tabList[i].getAttribute("Description");
if (desc.length() == 0) tabPane.addTab(thisName, null, scrollPane, null);
else tabPane.addTab(thisName, null, scrollPane, desc);
int keyNumber = getKey(i+1);
if(keyNumber !=0 ) tabPane.setMnemonicAt(i, keyNumber);
}
JComboBox box = new JComboBox();
for (int i = 0;i<panelsWithID.size();i++) {
TablePanel p = (TablePanel) panelsWithID.get(i);
box.addItem(p.name);
}
for (int i = 0;i<panelList.size();i++) {
TablePanel p = (TablePanel) panelList.get(i);
p.setEditor(box);
}
}
/** sets up the JTabbedPane given an OMENode from an OMEXML file.
* the template will set which parts of the file are displayed.
*/
public void setupTabs(OMENode ome) {
tabPane.removeAll();
panelList = new Vector();
panelsWithID = new Vector();
Element[] tabList = tParse.getTabs();
Vector actualTabs = new Vector(2 * tabList.length);
for(int i = 0;i< tabList.length;i++) {
Vector inOmeList = null;
String aName = tabList[i].getAttribute("XMLName");
if( aName.equals("Image") || aName.equals("Feature") || aName.equals("Dataset") || aName.equals("Project") ) inOmeList = ome.getChildren(aName);
else inOmeList = ome.getChild("CustomAttributes").getChildren(aName);
int vSize = inOmeList.size();
if(vSize >0) {
for(int j = 0;j<vSize;j++) {
String thisName = tabList[i].getAttribute("Name");
if(thisName.length() == 0) thisName = tabList[i].getAttribute("XMLName");
TabPanel tPanel = new TabPanel(tabList[i]);
tPanel.oNode = (OMEXMLNode) inOmeList.get(j);
renderTab(tPanel);
JScrollPane scrollPane = new JScrollPane(tPanel);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
String desc = tabList[i].getAttribute("Description");
if (vSize > 1) {
Integer jInt = new Integer(j+1);
thisName = thisName + " (" + jInt.toString() + ")";
tPanel.name = thisName;
tPanel.copyNumber = j + 1;
}
if (desc.length() == 0) tabPane.addTab(thisName, null, scrollPane, null);
else tabPane.addTab(thisName, null, scrollPane, desc);
actualTabs.add(tabList[i]);
}
}
else {
String thisName = tabList[i].getAttribute("Name");
if(thisName.length() == 0) thisName = tabList[i].getAttribute("XMLName");
TabPanel tPanel = new TabPanel(tabList[i]);
renderTab(tPanel);
JScrollPane scrollPane = new JScrollPane(tPanel);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
String desc = tabList[i].getAttribute("Description");
if (desc.length() == 0) tabPane.addTab(thisName, null, scrollPane, null);
else tabPane.addTab(thisName, null, scrollPane, desc);
actualTabs.add(tabList[i]);
}
}
for(int i = 0;i<actualTabs.size();i++) {
int keyNumber = getKey(i+1);
if(keyNumber !=0 ) tabPane.setMnemonicAt(i, keyNumber);
}
MetadataNotebook mn = (MetadataNotebook) getParent().getParent().getParent();
mn.changeTabMenu(actualTabs.toArray());
JComboBox box = new JComboBox();
for (int i = 0;i<panelsWithID.size();i++) {
TablePanel p = (TablePanel) panelsWithID.get(i);
box.addItem(p.name);
}
for (int i = 0;i<panelList.size();i++) {
TablePanel p = (TablePanel) panelList.get(i);
p.setEditor(box);
}
}
/** fleshes out the GUI of a given TabPanel
*/
public void renderTab(TabPanel tp) {
if(!tp.isRendered) {
tp.isRendered = true;
tp.removeAll();
//Set up the GridBagLayout
JPanel dataPanel = new JPanel();
dataPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.NORTHWEST;
Insets ins = new Insets(10,10,10,10);
gbc.insets = ins;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.gridheight = 1;
//placeY will hold info on which position to add a new component to the layout
int placeY = 0;
//add a title label to show which element
JPanel titlePanel = new JPanel();
titlePanel.setLayout(new GridLayout(2,1));
JLabel title = new JLabel();
Font thisFont = title.getFont();
Font newFont = new Font(thisFont.getFontName(),Font.BOLD,18);
title.setFont(newFont);
title.setText(" " + tp.name + ":");
titlePanel.add(title);
//if title has a description, add it in italics
if (tp.el.hasAttribute("Description")) {
if(tp.el.getAttribute("Description").length() != 0) {
JLabel descrip = new JLabel();
newFont = new Font(thisFont.getFontName(),Font.ITALIC,thisFont.getSize());
descrip.setFont(newFont);
descrip.setText( " " + tp.el.getAttribute("Description"));
ins = new Insets(10,30,10,10);
titlePanel.add(descrip);
}
}
tp.setLayout(new BorderLayout());
tp.add(titlePanel,BorderLayout.NORTH);
tp.add(dataPanel,BorderLayout.CENTER);
gbc.gridy = placeY;
TablePanel pan = new TablePanel(tp.el, tp, tp.oNode);
dataPanel.add(pan,gbc);
placeY++;
ins = new Insets(10,30,10,10);
gbc.insets = ins;
Vector theseElements = DOMUtil.getChildElements("OMEElement",tp.el);
Vector branchElements = new Vector(theseElements.size());
for(int i = 0;i<theseElements.size();i++) {
Element e = null;
if (theseElements.get(i) instanceof Element) e = (Element) theseElements.get(i);
if (DOMUtil.getChildElements("OMEElement",e).size() != 0) {
branchElements.add(e);
}
else {
if(tp.oNode != null) {
Vector v = new Vector();
String aName = e.getAttribute("XMLName");
if( aName.equals("Image") || aName.equals("Feature") || aName.equals("Dataset") || aName.equals("Project") ) v = tp.oNode.getChildren(aName);
else if (tp.oNode.getChild("CustomAttributes") != null) v = tp.oNode.getChild("CustomAttributes").getChildren(aName);
if (v.size() == 0) {
//Use reflect api to avoid large switch statement to handle construction of different nodes
//OMEXMLNode child classes
OMEXMLNode n = null;
try {
ReflectedUniverse r = new ReflectedUniverse();
String unknownName = e.getAttribute("XMLName");
if (unknownName.equals("Project") || unknownName.equals("Feature") || unknownName.equals("CustomAttributes") || unknownName.equals("Dataset") || unknownName.equals("Image")) {
r.exec("import org.openmicroscopy.xml." + unknownName + "Node");
}
else r.exec("import org.openmicroscopy.xml.st." + unknownName + "Node");
r.setVar("parent", tp.oNode);
r.exec("result = new " + unknownName + "Node(parent)");
n = (OMEXMLNode) r.getVar("result");
}
catch (Exception exc) {
System.out.println(exc.toString());
}
gbc.gridy = placeY;
TablePanel p = new TablePanel(e, tp, n);
dataPanel.add(p,gbc);
placeY++;
}
else {
for(int j = 0;j<v.size();j++) {
OMEXMLNode n = (OMEXMLNode) v.get(j);
gbc.gridy = placeY;
TablePanel p = new TablePanel(e, tp, n);
dataPanel.add(p,gbc);
placeY++;
}
}
}
else {
OMEXMLNode n = null;
gbc.gridy = placeY;
TablePanel p = new TablePanel(e, tp, n);
dataPanel.add(p,gbc);
placeY++;
}
}
}
}
}
public String getTreePathName(Element e) {
String thisName = null;
if(e.hasAttribute("Name"))thisName = e.getAttribute("Name");
else thisName = e.getAttribute("XMLName");
Element aParent = DOMUtil.getAncestorElement("OMEElement",e);
while(aParent != null) {
if(aParent.hasAttribute("Name")) thisName = aParent.getAttribute("Name") + thisName;
else thisName = aParent.getAttribute("XMLName") + ": " + thisName;
aParent = DOMUtil.getAncestorElement("OMEElement",aParent);
}
return thisName;
}
public String getTreePathName(Element el, OMEXMLNode on) {
Vector pathList = new Vector();
Element aParent = on.getDOMElement();
Vector pathNames = getTreePathList(el);
pathNames.add("OME");
pathList.add(aParent);
for (int i = 1;i<pathNames.size();i++) {
String s = (String) pathNames.get(i);
aParent = DOMUtil.getAncestorElement(s, aParent);
pathList.add(0,aParent);
}
String result = "";
for (int i = 0;i<pathList.size() - 1;i++) {
aParent = (Element) pathList.get(i);
Element aChild = (Element) pathList.get(i+1);
String thisName = aChild.getTagName();
NodeList nl = aParent.getElementsByTagName(thisName);
if (nl.getLength() == 1) {
Element e = (Element) nl.item(0);
if (i == 0) result = result + e.getTagName();
else result = result + ": " + e.getTagName();
}
else {
for (int j = 0;j<nl.getLength();j++) {
Element e = (Element) nl.item(j);
if (e == aChild) {
Integer aInt = new Integer(j+1);
if (i == 0) result = result + e.getTagName() + " (" + aInt.toString() + ")";
else result = result + ": " + e.getTagName() + " (" + aInt.toString() + ")";
}
}
}
}
return result;
}
/** returns a vector of Strings representing the XMLNames of the
* template's ancestors in ascending order in the list.
*/
public Vector getTreePathList(Element e) {
Vector thisPath = new Vector(10);
thisPath.add(e.getAttribute("XMLName"));
Element aParent = DOMUtil.getAncestorElement("OMEElement",e);
while(aParent != null) {
thisPath.add(aParent.getAttribute("XMLName"));
aParent = DOMUtil.getAncestorElement("OMEElement",aParent);
}
return thisPath;
}
/*changes the selected tab to tab of index i
*/
public void tabChange(int i) {
tabPane.setSelectedIndex(i);
}
/* gets around an annoying GUI layout problem when window is resized.
public void fixTables()
// -- Component API methods --
/** Sets the initial size of the metadata pane to be reasonable. */
public Dimension getPreferredSize() { return new Dimension(700, 500); }
// -- Runnable API methods --
/** Shows or hides the proper subpanes. */
public void run() {
tabPane.setVisible(!raw);
rawPanel.setVisible(raw);
validate();
repaint();
}
// -- Event API methods --
// -- Static methods --
public static int getKey(int i) {
int keyNumber = 0;
switch (i) {
case 1 :
keyNumber = KeyEvent.VK_1;
break;
case 2 :
keyNumber = KeyEvent.VK_2;
break;
case 3 :
keyNumber = KeyEvent.VK_3;
break;
case 4 :
keyNumber = KeyEvent.VK_4;
break;
case 5 :
keyNumber = KeyEvent.VK_5;
break;
case 6 :
keyNumber = KeyEvent.VK_6;
break;
case 7 :
keyNumber = KeyEvent.VK_7;
break;
case 8 :
keyNumber = KeyEvent.VK_8;
break;
case 9 :
keyNumber = KeyEvent.VK_9;
break;
case 10 :
keyNumber = KeyEvent.VK_0;
break;
default:
keyNumber = 0;
}
return keyNumber;
}
// -- Helper classes --
/** Helper class to make my life easier in the creation and use of tabs
* associates a given xml template element and also an optional OMEXMLNode
* with a JPanel that represents the content of a tab.
*/
public class TabPanel extends JPanel {
public Element el;
public String name;
private boolean isRendered;
public OMEXMLNode oNode;
public int copyNumber;
public TabPanel(Element el) {
copyNumber = 0;
isRendered = false;
this.el = el;
oNode = null;
name = getTreePathName(el);
}
public String toString() { return el == null ? "null" : el.getTagName(); }
}
/** Helper class to handle the "GOTO" buttons that take you to a particular
* Element ID's representation in the program.
*/
public class TableButton extends JButton {
public DefaultTableModel tableModel;
public int whichRow;
public TableButton(DefaultTableModel dtm, int i) {
super("Goto");
tableModel = dtm;
whichRow = i;
Integer aInt = new Integer(i);
setActionCommand("goto");
Dimension d = new Dimension(70,15);
setPreferredSize(d);
}
}
/** Helper class to handle the various TablePanels that will be created to
* display the attributes of Elements that have no nested Elements
*/
public class TablePanel extends JPanel
implements TableModelListener
{
public OMEXMLNode oNode;
public TabPanel tPanel;
public String id;
public String name;
public JComboBox comboBox;
public JTable newTable, refTable;
public TablePanel(Element e, TabPanel tp, OMEXMLNode on) {
oNode = on;
tPanel = tp;
id = null;
newTable = null;
refTable = null;
comboBox = null;
name = getTreePathName(e,on);
String thisName = getTreePathName(e, on);
panelList.add(this);
Vector fullList = DOMUtil.getChildElements("OMEAttribute",e);
Vector attrList = new Vector();
Vector refList = new Vector();
for(int i = 0;i<fullList.size();i++) {
Element thisE = (Element) fullList.get(i);
if(thisE.hasAttribute("Type") ) {
if(thisE.getAttribute("Type").equals("Ref") ) refList.add(thisE);
else if(thisE.getAttribute("Type").equals("ID") && oNode != null) {
if (oNode.getDOMElement().hasAttribute("ID")) {
id = oNode.getAttribute("ID");
panelsWithID.add(this);
}
else {
//CODE HERE TO CREATE A UNIQUE ID
}
}
else attrList.add(thisE);
}
else attrList.add(thisE);
}
Element cDataEl = DOMUtil.getChildElement("CData",e);
if (cDataEl != null) attrList.add(0,cDataEl);
JPanel lowPanel = new JPanel();
if (attrList.size() != 0) {
myTableModel = new DefaultTableModel(TREE_COLUMNS, 0) {
public boolean isCellEditable(int row, int col) {
if(col < 1) return false;
else return true;
}
};
myTableModel.addTableModelListener(this);
setLayout(new GridLayout(0,1));
JLabel tableName = new JLabel(thisName);
newTable = new JTable(myTableModel);
newTable.getColumnModel().getColumn(0).setPreferredWidth(150);
newTable.getColumnModel().getColumn(1).setPreferredWidth(475);
JTableHeader tHead = newTable.getTableHeader();
tHead.setResizingAllowed(false);
tHead.setReorderingAllowed(false);
JPanel headerPanel = new JPanel();
headerPanel.setLayout(new BorderLayout());
JPanel aPanel = new JPanel();
aPanel.setLayout(new BorderLayout());
aPanel.add(tableName,BorderLayout.SOUTH);
lowPanel.setLayout(new BorderLayout());
lowPanel.add(newTable,BorderLayout.NORTH);
headerPanel.add(aPanel, BorderLayout.CENTER);
headerPanel.add(tHead, BorderLayout.SOUTH);
add(headerPanel);
add(lowPanel);
// update OME-XML attributes table
myTableModel.setRowCount(attrList.size());
for (int i=0; i<attrList.size(); i++) {
Element thisEle = null;
if (attrList.get(i) instanceof Element) thisEle = (Element) attrList.get(i);
if (thisEle != null) {
String attrName = thisEle.getAttribute("XMLName");
if (thisEle.hasAttribute("Name")) {
myTableModel.setValueAt(thisEle.getAttribute("Name"), i, 0);
if(oNode != null) {
if(oNode.getDOMElement().hasAttribute(attrName)) {
myTableModel.setValueAt(oNode.getAttribute(attrName), i, 1);
}
}
}
else if (thisEle.hasAttribute("XMLName")) {
myTableModel.setValueAt(thisEle.getAttribute("XMLName"), i, 0);
if(oNode != null) {
if(oNode.getDOMElement().hasAttribute(attrName)) {
myTableModel.setValueAt(oNode.getAttribute(attrName), i, 1);
}
}
}
else {
if(e.hasAttribute("Name")) myTableModel.setValueAt(e.getAttribute("Name") + " CharData", i, 0);
else myTableModel.setValueAt(e.getAttribute("XMLName") + " CharData", i, 0);
if(oNode != null && DOMUtil.getCharacterData(oNode.getDOMElement() ) != null) {
myTableModel.setValueAt(DOMUtil.getCharacterData(oNode.getDOMElement() ), i, 1);
}
}
}
}
}
if (refList.size() > 0) {
myTableModel = new DefaultTableModel(TREE_COLUMNS, 0) {
public boolean isCellEditable(int row, int col) {
if(col < 1) return false;
else return true;
}
};
refTable = new JTable(myTableModel);
refTable.getColumnModel().getColumn(0).setPreferredWidth(150);
refTable.getColumnModel().getColumn(1).setPreferredWidth(405);
TableColumn refColumn = refTable.getColumnModel().getColumn(1);
comboBox = new JComboBox();
refColumn.setCellEditor(new DefaultCellEditor(comboBox));
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(0,1));
myTableModel.setRowCount(refList.size());
for (int i=0; i<refList.size(); i++) {
Element thisEle = null;
if (refList.get(i) instanceof Element) thisEle = (Element) refList.get(i);
if (thisEle != null) {
if (thisEle.hasAttribute("Name")) myTableModel.setValueAt(thisEle.getAttribute("Name"), i, 0);
else if (thisEle.hasAttribute("XMLName")) myTableModel.setValueAt(thisEle.getAttribute("XMLName"), i, 0);
}
TableButton tb = new TableButton(myTableModel,i);
buttonPanel.add(tb);
}
Dimension dim = new Dimension(50, buttonPanel.getHeight());
buttonPanel.setSize(dim);
if(attrList.size() == 0) {
setLayout(new GridLayout(0,1));
JLabel tableName = new JLabel(thisName);
JTableHeader tHead = refTable.getTableHeader();
tHead.setResizingAllowed(false);
tHead.setReorderingAllowed(false);
JPanel headerPanel = new JPanel();
headerPanel.setLayout(new BorderLayout());
JPanel aPanel = new JPanel();
aPanel.setLayout(new BorderLayout());
aPanel.add(tableName,BorderLayout.SOUTH);
lowPanel.setLayout(new BorderLayout());
lowPanel.add(refTable,BorderLayout.NORTH);
headerPanel.add(aPanel, BorderLayout.CENTER);
headerPanel.add(tHead, BorderLayout.SOUTH);
add(headerPanel);
add(lowPanel);
JPanel refPanel = new JPanel();
refPanel.setLayout(new BorderLayout());
refPanel.add(refTable, BorderLayout.CENTER);
refPanel.add(buttonPanel, BorderLayout.EAST);
JPanel placePanel = new JPanel();
placePanel.setLayout(new BorderLayout());
placePanel.add(refPanel, BorderLayout.NORTH);
lowPanel.add(placePanel, BorderLayout.CENTER);
}
else {
JPanel refPanel = new JPanel();
refPanel.setLayout(new BorderLayout());
refPanel.add(refTable, BorderLayout.CENTER);
refPanel.add(buttonPanel, BorderLayout.EAST);
JPanel placePanel = new JPanel();
placePanel.setLayout(new BorderLayout());
placePanel.add(refPanel, BorderLayout.NORTH);
lowPanel.add(placePanel, BorderLayout.CENTER);
}
}
}
public void setEditor(JComboBox jcb) {
if(refTable != null) {
TableModel model = refTable.getModel();
TableColumn refColumn = refTable.getColumnModel().getColumn(1);
Vector addItems = new Vector();
for(int i = 0;i < refTable.getRowCount();i++) {
boolean isLocal = false;
String attrName = (String) model.getValueAt(i,0);
String value = oNode.getAttribute(attrName);
for(int j = 0;j < panelsWithID.size();j++) {
TablePanel tp = (TablePanel) panelsWithID.get(j);
if (tp.id != null && value != null) {
if (value.equals(tp.id)) {
isLocal = true;
model.setValueAt(tp.name,i,1);
}
}
}
if(!isLocal && value != null) {
model.setValueAt(value,i,1);
addItems.add(value);
}
}
/*
Vector v = new Vector();
for(int i = 0;i < addItems.size();i++) {
System.out.println("Original: \"" + addItems.get(i).toString());
if (v.indexOf(addItems.get(i)) < 0) v.add(addItems.get(i));
}
for(int i = 0;i < v.size();i++) {
System.out.println("Next: \"" + addItems.get(i).toString());
String name = (String) v.get(i);
jcb.addItem(name);
}
*/
refColumn.setCellEditor(new DefaultCellEditor(jcb));
}
}
public void tableChanged(TableModelEvent e) {
int column = e.getColumn();
if (e.getType() == TableModelEvent.UPDATE && column == 1) {
int row = e.getFirstRow();
TableModel model = (TableModel) e.getSource();
String data = (String) model.getValueAt(row, column);
String attr = (String) model.getValueAt(row,0);
if ( data != null && !data.equals("") ) {
if (attr.endsWith("CharData") ) {
DOMUtil.setCharacterData(data, oNode.getDOMElement());
}
if (oNode != null) oNode.setAttribute(attr, data);
}
}
}
}
}
|
added:
1) goto buttons work for changing tabs appropriately now, although I still
can't get the sucker to focus on the table it should in the scrollable pane.
| loci/ome/notebook/MetadataPane.java | ||
Java | bsd-3-clause | f522002e6e93b9dbbfd65cf428b0a11dc0eb957f | 0 | geneontology/minerva,geneontology/minerva,geneontology/minerva | /**
*
*/
package org.geneontology.minerva.validation;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.rdf.api.RDF;
import org.apache.commons.rdf.api.RDFTerm;
import org.apache.commons.rdf.jena.JenaGraph;
import org.apache.commons.rdf.jena.JenaRDF;
import org.apache.commons.rdf.simple.SimpleRDF;
import org.apache.jena.query.Query;
import org.apache.jena.query.QueryExecution;
import org.apache.jena.query.QueryExecutionFactory;
import org.apache.jena.query.QueryFactory;
import org.apache.jena.query.QueryParseException;
import org.apache.jena.query.QuerySolution;
import org.apache.jena.query.ResultSet;
import org.apache.jena.rdf.model.Literal;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.Property;
import org.apache.jena.rdf.model.RDFNode;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.StmtIterator;
import org.apache.jena.vocabulary.RDFS;
import org.apache.log4j.Logger;
import org.geneontology.minerva.curie.CurieHandler;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.reasoner.OWLReasoner;
import fr.inria.lille.shexjava.schema.Label;
import fr.inria.lille.shexjava.schema.ShexSchema;
import fr.inria.lille.shexjava.schema.abstrsynt.EachOf;
import fr.inria.lille.shexjava.schema.abstrsynt.NodeConstraint;
import fr.inria.lille.shexjava.schema.abstrsynt.RepeatedTripleExpression;
import fr.inria.lille.shexjava.schema.abstrsynt.Shape;
import fr.inria.lille.shexjava.schema.abstrsynt.ShapeAnd;
import fr.inria.lille.shexjava.schema.abstrsynt.ShapeExpr;
import fr.inria.lille.shexjava.schema.abstrsynt.ShapeExprRef;
import fr.inria.lille.shexjava.schema.abstrsynt.ShapeOr;
import fr.inria.lille.shexjava.schema.abstrsynt.TCProperty;
import fr.inria.lille.shexjava.schema.abstrsynt.TripleConstraint;
import fr.inria.lille.shexjava.schema.abstrsynt.TripleExpr;
import fr.inria.lille.shexjava.schema.parsing.GenParser;
import fr.inria.lille.shexjava.util.Pair;
import fr.inria.lille.shexjava.validation.RecursiveValidation;
import fr.inria.lille.shexjava.validation.Status;
import fr.inria.lille.shexjava.validation.Typing;
/**
* @author bgood
*
*/
public class ShexValidator {
private static final Logger LOGGER = Logger.getLogger(ShexValidator.class);
public ShexSchema schema;
public Map<String, String> GoQueryMap;
public OWLReasoner tbox_reasoner;
public static final String endpoint = "http://rdf.geneontology.org/blazegraph/sparql";
public Map<Label, Map<String, Set<String>>> shape_expected_property_ranges;
public CurieHandler curieHandler;
public RDF rdfFactory;
/**
* @throws Exception
*
*/
public ShexValidator(String shexpath, String goshapemappath, OWLReasoner tbox_reasoner_, CurieHandler curieHandler_) throws Exception {
new ShexValidator(new File(shexpath), new File(goshapemappath), tbox_reasoner_, curieHandler_);
}
public ShexValidator(File shex_schema_file, File shex_map_file, OWLReasoner tbox_reasoner_, CurieHandler curieHandler_) throws Exception {
schema = GenParser.parseSchema(shex_schema_file.toPath());
GoQueryMap = makeGoQueryMap(shex_map_file.getAbsolutePath());
tbox_reasoner = tbox_reasoner_;
shape_expected_property_ranges = new HashMap<Label, Map<String, Set<String>>>();
curieHandler = curieHandler_;
rdfFactory = new SimpleRDF();
for(String shapelabel : GoQueryMap.keySet()) {
if(shapelabel.equals("http://purl.obolibrary.org/obo/go/shapes/AnnotatedEdge")) {
continue;
}
Label shape_label = new Label(rdfFactory.createIRI(shapelabel));
ShapeExpr rule = schema.getRules().get(shape_label);
Map<String, Set<String>> expected_property_ranges = getPropertyRangeMap(rule, null);
shape_expected_property_ranges.put(shape_label, expected_property_ranges);
}
}
public static Map<String, String> makeGoQueryMap(String shapemap_file) throws IOException{
Map<String, String> shapelabel_sparql = new HashMap<String, String>();
BufferedReader reader = new BufferedReader(new FileReader(shapemap_file));
String line = reader.readLine();
String all = line;
while(line!=null) {
all+=line;
line = reader.readLine();
}
reader.close();
String[] maps = all.split(",");
for(String map : maps) {
String sparql = StringUtils.substringBetween(map, "'", "'");
sparql = sparql.replace("a/", "<http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?c . ?c ");
String[] shapemaprow = map.split("@");
String shapelabel = shapemaprow[1];
shapelabel = shapelabel.replace(">", "");
shapelabel = shapelabel.replace("<", "");
shapelabel = shapelabel.trim();
shapelabel_sparql.put(shapelabel, sparql);
}
return shapelabel_sparql;
}
public ShexValidationReport runShapeMapValidation(Model test_model, boolean stream_output) throws Exception {
ShexValidationReport r = new ShexValidationReport(null, test_model);
RDF rdfFactory = new SimpleRDF();
JenaRDF jr = new JenaRDF();
//this shex implementation likes to use the commons JenaRDF interface, nothing exciting here
JenaGraph shexy_graph = jr.asGraph(test_model);
//recursive only checks the focus node against the chosen shape.
RecursiveValidation shex_model_validator = new RecursiveValidation(schema, shexy_graph);
//for each shape in the query map (e.g. MF, BP, CC, etc.)
boolean all_good = true;
Map<Resource, Set<String>> node_shapes = new HashMap<Resource, Set<String>>();
for(String shapelabel : GoQueryMap.keySet()) {
//not quite the same pattern as the other shapes
//TODO needs more work
if(shapelabel.equals("http://purl.obolibrary.org/obo/go/shapes/AnnotatedEdge")) {
continue;
}
//get the nodes in this model that SHOULD match the shape
Set<Resource> focus_nodes = getFocusNodesBySparql(test_model, GoQueryMap.get(shapelabel));
//shape_nodes.put(shapelabel, focus_nodes);
for(Resource focus_node : focus_nodes) {
Set<String> shapes = node_shapes.get(focus_node);
if(shapes==null) {
shapes = new HashSet<String>();
}
shapes.add(shapelabel);
node_shapes.put(focus_node, shapes);
}
}
//prune down evaluation to only consider most specific of matched shapes for a given resource
//TODO - do this once up front.. massively redundant waste in here right now.
Map<Resource, Set<String>> node_s_shapes = new HashMap<Resource, Set<String>>();
for(Resource node : node_shapes.keySet()) {
Set<String> shapes = node_shapes.get(node);
Set<String> shapes_to_remove = new HashSet<String>();
for(String shape1 : shapes) {
Set<Resource> shape1_nodes = getFocusNodesBySparql(test_model, GoQueryMap.get(shape1));
for(String shape2 : shapes) {
if(shape1.equals(shape2)) {
continue;
}
Set<Resource> shape2_nodes = getFocusNodesBySparql(test_model, GoQueryMap.get(shape2));
//if shape1 contains all of shape2 - e.g. mf would contain all transporter activity
if(shape1_nodes.containsAll(shape2_nodes)) {
//then remove shape1 from this resource (as shape2 is more specific).
shapes_to_remove.add(shape1);
}
}
}
shapes.removeAll(shapes_to_remove);
node_s_shapes.put(node, shapes);
}
for(Resource focus_node_resource : node_s_shapes.keySet()) {
Set<String> shape_nodes = node_s_shapes.get(focus_node_resource);
for(String shapelabel : shape_nodes) {
Label shape_label = new Label(rdfFactory.createIRI(shapelabel));
if(focus_node_resource==null) {
System.out.println("null focus node for shape "+shape_label);
continue;
}
//check for use of properties not defined for this shape (okay if OPEN, not if CLOSED)
Set<ShexViolation> extra_prop_violations = checkForExtraProperties(focus_node_resource, test_model, shape_label, shex_model_validator);
if(extra_prop_violations != null && !extra_prop_violations.isEmpty()) {
for(Violation v : extra_prop_violations) {
r.addViolation(v);
}
all_good = false;
}
RDFTerm focus_node = null;
String focus_node_id = "";
if(focus_node_resource.isURIResource()) {
focus_node = rdfFactory.createIRI(focus_node_resource.getURI());
focus_node_id = focus_node_resource.getURI();
}else {
focus_node = rdfFactory.createBlankNode(focus_node_resource.getId().getLabelString());
focus_node_id = focus_node_resource.getId().getLabelString();
}
//deal with curies for output
String node = focus_node_id;
node = getCurie(focus_node_id);
// if(curieHandler!=null) {
// node = curieHandler.getCuri(IRI.create(focus_node_resource.getURI()));
// }
//check the node against the intended shape
shex_model_validator.validate(focus_node, shape_label);
Typing typing = shex_model_validator.getTyping();
//capture the result
Status status = typing.getStatus(focus_node, shape_label);
if(status.equals(Status.CONFORMANT)) {
Set<String> shape_ids = r.node_matched_shapes.get(node);
if(shape_ids==null) {
shape_ids = new HashSet<String>();
}
shape_ids.add(shapelabel);
r.node_matched_shapes.put(node, shape_ids);
}else if(status.equals(Status.NONCONFORMANT)) {
//if any of these tests is invalid, the model is invalid
all_good = false;
//implementing a start on a generic violation report structure here
ShexViolation violation = new ShexViolation(node);
ShexExplanation explanation = new ShexExplanation();
String shape_curie = getCurie(shapelabel);
explanation.setShape(shape_curie);
Set<ShexConstraint> unmet_constraints = getUnmetConstraints(focus_node_resource, shapelabel, test_model);
for(ShexConstraint constraint : unmet_constraints) {
explanation.addConstraint(constraint);
violation.addExplanation(explanation);
}
r.addViolation(violation);
}else if(status.equals(Status.NOTCOMPUTED)) {
//if any of these are not computed, there is a problem
String error = focus_node_id+" was not tested against "+shapelabel;
LOGGER.info(error);
}
}
}
if(all_good) {
r.conformant = true;
}else {
r.conformant = false;
}
return r;
}
public static Set<Resource> getFocusNodesBySparql(Model model, String sparql){
Set<Resource> nodes = new HashSet<Resource>();
QueryExecution qe = QueryExecutionFactory.create(sparql, model);
ResultSet results = qe.execSelect();
while (results.hasNext()) {
QuerySolution qs = results.next();
Resource node = qs.getResource("x");
nodes.add(node);
}
qe.close();
return nodes;
}
/**
* Check each focus node for the use of any properties that don't appear in the shape
* @param focus_nodes
* @param model
* @param shape_label
* @return
*/
public Set<ShexViolation> checkForExtraProperties(Resource node_r, Model model, Label shape_label, RecursiveValidation shex_model_validator){
Set<ShexViolation> violations = new HashSet<ShexViolation>();
Set<String> allowed_properties = this.shape_expected_property_ranges.get(shape_label).keySet();
Set<String> actual_properties = new HashSet<String>();
Map<String, String> prop_value = new HashMap<String, String>(); //don't really care if there are multiple values, one will do.
String sparql = "select distinct ?prop ?value where{ <"+node_r.getURI()+"> ?prop ?value }";
QueryExecution qe = QueryExecutionFactory.create(sparql, model);
ResultSet results = qe.execSelect();
while (results.hasNext()) {
QuerySolution qs = results.next();
Resource prop = qs.getResource("prop");
RDFNode value = qs.get("value");
String v = "value";
if(value.isResource()) {
v = value.asResource().getURI();
}else if(value.isLiteral()) {
v = value.asLiteral().getString();
}
actual_properties.add(prop.getURI());
prop_value.put(prop.getURI(), v);
}
qe.close();
actual_properties.removeAll(allowed_properties);
if(!actual_properties.isEmpty()) {
ShexViolation extra = new ShexViolation(getCurie(node_r.getURI()));
Set<ShexExplanation> explanations = new HashSet<ShexExplanation>();
for(String prop : actual_properties) {
String value = prop_value.get(prop);
ShexExplanation extra_explain = new ShexExplanation();
extra_explain.setShape(getCurie(shape_label.stringValue()));
String object = value;
Set<String> intended_range_shapes = new HashSet<String>();
//For this CLOSED test, no shape fits in intended. Any use of the property here would be incorrect.
intended_range_shapes.add("owl:Nothing");
Set<String> node_types = getNodeTypes(model, node_r.getURI());
Set<String> object_types = getNodeTypes(model, value);
//TODO consider here. extra info but not really meaningful - anything in the range would be wrong.
Set<String> matched_range_shapes = getAllMatchedShapes(value, shex_model_validator);
String report_prop = getCurie(prop);
ShexConstraint c = new ShexConstraint(object, report_prop, intended_range_shapes, node_types, object_types);
c.setMatched_range_shapes(matched_range_shapes);
Set<ShexConstraint> cs = new HashSet<ShexConstraint>();
cs.add(c);
extra_explain.setConstraints(cs);
explanations.add(extra_explain);
}
extra.setExplanations(explanations);
violations.add(extra);
}
return violations;
}
public Model enrichSuperClasses(Model model) {
String getOntTerms =
"PREFIX owl: <http://www.w3.org/2002/07/owl#> "
+ "SELECT DISTINCT ?term " +
" WHERE { " +
" ?ind a owl:NamedIndividual . " +
" ?ind a ?term . " +
" FILTER(?term != owl:NamedIndividual)" +
" FILTER(isIRI(?term)) ." +
" }";
String terms = "";
Set<String> term_set = new HashSet<String>();
try{
QueryExecution qe = QueryExecutionFactory.create(getOntTerms, model);
ResultSet results = qe.execSelect();
while (results.hasNext()) {
QuerySolution qs = results.next();
Resource term = qs.getResource("term");
terms+=("<"+term.getURI()+"> ");
term_set.add(term.getURI());
}
qe.close();
} catch(QueryParseException e){
e.printStackTrace();
}
if(tbox_reasoner!=null) {
for(String term : term_set) {
OWLClass c =
tbox_reasoner.
getRootOntology().
getOWLOntologyManager().
getOWLDataFactory().getOWLClass(IRI.create(term));
Resource child = model.createResource(term);
Set<OWLClass> supers = tbox_reasoner.getSuperClasses(c, false).getFlattened();
for(OWLClass parent_class : supers) {
Resource parent = model.createResource(parent_class.getIRI().toString());
model.add(model.createStatement(child, org.apache.jena.vocabulary.RDFS.subClassOf, child));
model.add(model.createStatement(child, org.apache.jena.vocabulary.RDFS.subClassOf, parent));
model.add(model.createStatement(child, org.apache.jena.vocabulary.RDF.type, org.apache.jena.vocabulary.OWL.Class));
}
}
}else {
String superQuery = ""
+ "PREFIX owl: <http://www.w3.org/2002/07/owl#> "
+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> "
+ "CONSTRUCT { " +
" ?term rdfs:subClassOf ?superclass ." +
" ?term a owl:Class ." +
" }" +
" WHERE {" +
" VALUES ?term { "+terms+" } " +
" ?term rdfs:subClassOf* ?superclass ." +
" FILTER(isIRI(?superclass)) ." +
" }";
Query query = QueryFactory.create(superQuery);
try (
QueryExecution qexec = QueryExecutionFactory.sparqlService(endpoint, query) ) {
qexec.execConstruct(model);
qexec.close();
} catch(QueryParseException e){
e.printStackTrace();
}
}
return model;
}
public Set<String> getNodeTypes(Model model, String node_uri) {
String getOntTerms =
"PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> "
+ "PREFIX owl: <http://www.w3.org/2002/07/owl#> "
+ "SELECT DISTINCT ?type " +
" WHERE { " +
"<"+node_uri+"> rdf:type ?type . " +
"FILTER(?type != owl:NamedIndividual)" +
" }";
Set<String> types = new HashSet<String>();
try{
QueryExecution qe = QueryExecutionFactory.create(getOntTerms, model);
ResultSet results = qe.execSelect();
while (results.hasNext()) {
QuerySolution qs = results.next();
Resource type = qs.getResource("type");
types.add(getCurie(type.getURI()));
OWLClass t = tbox_reasoner.getRootOntology().getOWLOntologyManager().getOWLDataFactory().getOWLClass(IRI.create(type.getURI()));
for(OWLClass p : tbox_reasoner.getSuperClasses(t, false).getFlattened()) {
String type_curie = getCurie(p.getIRI().toString());
types.add(type_curie);
}
}
qe.close();
} catch(QueryParseException e){
e.printStackTrace();
}
return types;
}
private Set<ShexConstraint> getUnmetConstraints(Resource focus_node, String shape_id, Model model) {
Set<String> node_types = getNodeTypes(model, focus_node.getURI());
Set<ShexConstraint> unmet_constraints = new HashSet<ShexConstraint>();
RDF rdfFactory = new SimpleRDF();
Label shape_label = new Label(rdfFactory.createIRI(shape_id));
Map<String, Set<String>> expected_property_ranges = shape_expected_property_ranges.get(shape_label);
//get a map from properties to actual shapes of the asserted objects
JenaRDF jr = new JenaRDF();
JenaGraph shexy_graph = jr.asGraph(model);
RecursiveValidation shex_model_validator = new RecursiveValidation(schema, shexy_graph);
//get the focus node in the rdf model
//check for assertions with properties in the target shape
for(String prop_uri : expected_property_ranges.keySet()) {
Property prop = model.getProperty(prop_uri);
//checking on objects of this property for the problem node.
for (StmtIterator i = focus_node.listProperties(prop); i.hasNext(); ) {
RDFNode obj = i.nextStatement().getObject();
//check the computed shapes for this individual
if(!obj.isResource()) {
continue;
//no checks on literal values at this time
}else if(prop_uri.equals("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")&&obj.asResource().getURI().equals("http://www.w3.org/2002/07/owl#NamedIndividual")) {
continue; //ignore type owl individual
}
RDFTerm range_obj = rdfFactory.createIRI(obj.asResource().getURI());
//does it hit any allowable shapes?
boolean good = false;
//TODO many property ranges are MISSING from previous step
//e.g. any OR will not show up here.
Set<String> expected_ranges = expected_property_ranges.get(prop_uri);
for(String target_shape_uri : expected_ranges) {
if(target_shape_uri.equals(".")) {
//anything is fine
good = true;
break;
}else if(target_shape_uri.trim().equals("<http://www.w3.org/2001/XMLSchema#string>")) {
//ignore syntax type checking for now
good = true;
break;
}
Label target_shape_label = null;
try {
target_shape_label = new Label(rdfFactory.createIRI(target_shape_uri));
shex_model_validator.validate(range_obj, target_shape_label);
//could use refine to get all of the actual shapes - but would want to do this
//once per validation...
//RefineValidation shex_refine_validator = new RefineValidation(schema, shexy_graph);
Typing shape_test = shex_model_validator.getTyping();
Pair<RDFTerm, Label> p = new Pair<RDFTerm, Label>(range_obj, target_shape_label);
Status r = shape_test.getStatusMap().get(p);
if(r.equals(Status.CONFORMANT)) {
good = true;
break;
}
}catch(Exception e) {
System.out.println(e+"\nbroken target shape uri:"+target_shape_uri);
}
}
if(!good) {
String object = obj.toString();
Set<String> object_types = getNodeTypes(model, object);
String property = prop.toString();
object = getCurie(object);
property = getCurie(property);
Set<String> expected = new HashSet<String>();
for(String e : expected_property_ranges.get(prop_uri)) {
String curie_e = getCurie(e);
expected.add(curie_e);
}
ShexConstraint constraint = new ShexConstraint(object, property, expected, node_types, object_types);
//return all shapes that are matched by this node for explanation
Set<String> obj_matched_shapes = getAllMatchedShapes(range_obj, shex_model_validator);
constraint.setMatched_range_shapes(obj_matched_shapes);
unmet_constraints.add(constraint);
}
}
}
return unmet_constraints;
}
public Set<String> getAllMatchedShapes(RDFTerm node, RecursiveValidation shex_model_validator){
Set<Label> all_shapes_in_schema = getAllShapesInSchema();
Set<String> obj_matched_shapes = new HashSet<String>();
for(Label target_shape_label : all_shapes_in_schema) {
shex_model_validator.validate(node, target_shape_label);
Typing shape_test = shex_model_validator.getTyping();
Pair<RDFTerm, Label> p = new Pair<RDFTerm, Label>(node, target_shape_label);
Status r = shape_test.getStatusMap().get(p);
if(r.equals(Status.CONFORMANT)) {
obj_matched_shapes.add(getCurie(target_shape_label.stringValue()));
}
}
return obj_matched_shapes;
}
public Set<String> getAllMatchedShapes(String node_uri, RecursiveValidation shex_model_validator){
RDFTerm range_obj = rdfFactory.createIRI(node_uri);
return getAllMatchedShapes(range_obj, shex_model_validator);
}
private Set<Label> getAllShapesInSchema() {
return schema.getRules().keySet();
}
public String getCurie(String uri) {
String curie = uri;
if(curieHandler!=null) {
curie = curieHandler.getCuri(IRI.create(uri));
}
return curie;
}
public Map<String, Set<String>> getPropertyRangeMap(ShapeExpr expr, Map<String, Set<String>> prop_range){
if(prop_range==null) {
prop_range = new HashMap<String, Set<String>>();
}
String explanation = "";
if(expr instanceof ShapeAnd) {
explanation += "And\n";
ShapeAnd andshape = (ShapeAnd)expr;
for(ShapeExpr subexp : andshape.getSubExpressions()) {
//boolean is_closed = subexp.closed;
prop_range = getPropertyRangeMap(subexp, prop_range);
explanation += subexp+" ";
}
}
else if (expr instanceof ShapeOr) {
explanation += "Or\n";
ShapeOr orshape = (ShapeOr)expr;
for(ShapeExpr subexp : orshape.getSubExpressions()) {
explanation += subexp;
//explainShape(subexp, explanation);
}
}else if(expr instanceof ShapeExprRef) {
ShapeExprRef ref = (ShapeExprRef) expr;
ShapeExpr ref_expr = ref.getShapeDefinition();
prop_range = getPropertyRangeMap(ref_expr, prop_range);
//not in the rdf model - this is a match of this expr on a shape
//e.g. <http://purl.obolibrary.org/obo/go/shapes/GoCamEntity>
explanation += "\t\tis a: "+((ShapeExprRef) expr).getLabel()+"\n";
}else if(expr instanceof Shape) {
Shape shape = (Shape)expr;
TripleExpr texp = shape.getTripleExpression();
prop_range = getPropertyRangeMap(texp, prop_range);
}else if (expr instanceof NodeConstraint) {
NodeConstraint nc = (NodeConstraint)expr;
explanation += "\t\tnode constraint "+nc.toPrettyString();
}
else {
explanation+=" Not sure what is: "+expr;
}
return prop_range;
}
public Map<String, Set<String>> getPropertyRangeMap(TripleExpr texp, Map<String, Set<String>> prop_range) {
if(prop_range==null) {
prop_range = new HashMap<String, Set<String>>();
}
if(texp instanceof TripleConstraint) {
TripleConstraint tcon = (TripleConstraint)texp;
TCProperty tprop = tcon.getProperty();
ShapeExpr range = tcon.getShapeExpr();
String prop_uri = tprop.getIri().toString();
Set<String> ranges = prop_range.get(prop_uri);
if(ranges==null) {
ranges = new HashSet<String>();
}
ranges.addAll(getShapeExprRefs(range,ranges));
prop_range.put(prop_uri, ranges);
}else if(texp instanceof EachOf){
EachOf each = (EachOf)texp;
for(TripleExpr eachtexp : each.getSubExpressions()) {
if(!texp.equals(eachtexp)) {
prop_range = getPropertyRangeMap(eachtexp, prop_range);
}
}
}else if(texp instanceof RepeatedTripleExpression) {
RepeatedTripleExpression rep = (RepeatedTripleExpression)texp;
rep.getCardinality().toString();
TripleExpr t = rep.getSubExpression();
prop_range = getPropertyRangeMap(t, prop_range);
}
else {
System.out.println("\tlost again here on "+texp);
}
return prop_range;
}
private Set<String> getShapeExprRefs(ShapeExpr expr, Set<String> shape_refs) {
if(shape_refs==null) {
shape_refs = new HashSet<String>();
}
if(expr instanceof ShapeExprRef) {
shape_refs.add(((ShapeExprRef) expr).getLabel().stringValue());
}else if(expr instanceof ShapeAnd) {
ShapeAnd andshape = (ShapeAnd)expr;
System.out.println("currently ignoring And shape in range: "+expr);
// for(ShapeExpr subexp : andshape.getSubExpressions()) {
// shape_refs = getShapeExprRefs(subexp, shape_refs);
// }
}else if (expr instanceof ShapeOr) {
ShapeOr orshape = (ShapeOr)expr;
for(ShapeExpr subexp : orshape.getSubExpressions()) {
shape_refs = getShapeExprRefs(subexp, shape_refs);
}
}else if (expr instanceof NodeConstraint){
String reference_string = ((NodeConstraint) expr).toPrettyString();
reference_string = reference_string.replace("<", "");
reference_string = reference_string.replace(">", "");
reference_string = reference_string.replace("[", "");
reference_string = reference_string.replace("]", "");
reference_string = reference_string.trim();
shape_refs.add(reference_string);
}else {
System.out.println("currently ignoring "+expr);
}
return shape_refs;
}
public static String getModelTitle(Model model) {
String model_title = null;
String q = "select ?cam ?title where {"
+ "GRAPH ?cam { "
+ "?cam <http://purl.org/dc/elements/1.1/title> ?title"
+ "}}";
// + "?cam <"+DC.description.getURI()+"> ?title }";
QueryExecution qe = QueryExecutionFactory.create(q, model);
ResultSet results = qe.execSelect();
if (results.hasNext()) {
QuerySolution qs = results.next();
Resource model_id_resource = qs.getResource("cam");
Literal title = qs.getLiteral("title");
model_title = title.getString();
}
qe.close();
return model_title;
}
}
| minerva-core/src/main/java/org/geneontology/minerva/validation/ShexValidator.java | /**
*
*/
package org.geneontology.minerva.validation;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.rdf.api.RDF;
import org.apache.commons.rdf.api.RDFTerm;
import org.apache.commons.rdf.jena.JenaGraph;
import org.apache.commons.rdf.jena.JenaRDF;
import org.apache.commons.rdf.simple.SimpleRDF;
import org.apache.jena.query.Query;
import org.apache.jena.query.QueryExecution;
import org.apache.jena.query.QueryExecutionFactory;
import org.apache.jena.query.QueryFactory;
import org.apache.jena.query.QueryParseException;
import org.apache.jena.query.QuerySolution;
import org.apache.jena.query.ResultSet;
import org.apache.jena.rdf.model.Literal;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.Property;
import org.apache.jena.rdf.model.RDFNode;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.rdf.model.StmtIterator;
import org.apache.jena.vocabulary.RDFS;
import org.apache.log4j.Logger;
import org.geneontology.minerva.curie.CurieHandler;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLClass;
import org.semanticweb.owlapi.reasoner.OWLReasoner;
import fr.inria.lille.shexjava.schema.Label;
import fr.inria.lille.shexjava.schema.ShexSchema;
import fr.inria.lille.shexjava.schema.abstrsynt.EachOf;
import fr.inria.lille.shexjava.schema.abstrsynt.NodeConstraint;
import fr.inria.lille.shexjava.schema.abstrsynt.RepeatedTripleExpression;
import fr.inria.lille.shexjava.schema.abstrsynt.Shape;
import fr.inria.lille.shexjava.schema.abstrsynt.ShapeAnd;
import fr.inria.lille.shexjava.schema.abstrsynt.ShapeExpr;
import fr.inria.lille.shexjava.schema.abstrsynt.ShapeExprRef;
import fr.inria.lille.shexjava.schema.abstrsynt.ShapeOr;
import fr.inria.lille.shexjava.schema.abstrsynt.TCProperty;
import fr.inria.lille.shexjava.schema.abstrsynt.TripleConstraint;
import fr.inria.lille.shexjava.schema.abstrsynt.TripleExpr;
import fr.inria.lille.shexjava.schema.parsing.GenParser;
import fr.inria.lille.shexjava.util.Pair;
import fr.inria.lille.shexjava.validation.RecursiveValidation;
import fr.inria.lille.shexjava.validation.Status;
import fr.inria.lille.shexjava.validation.Typing;
/**
* @author bgood
*
*/
public class ShexValidator {
private static final Logger LOGGER = Logger.getLogger(ShexValidator.class);
public ShexSchema schema;
public Map<String, String> GoQueryMap;
public OWLReasoner tbox_reasoner;
public static final String endpoint = "http://rdf.geneontology.org/blazegraph/sparql";
public Map<Label, Map<String, Set<String>>> shape_expected_property_ranges;
public CurieHandler curieHandler;
public RDF rdfFactory;
/**
* @throws Exception
*
*/
public ShexValidator(String shexpath, String goshapemappath, OWLReasoner tbox_reasoner_, CurieHandler curieHandler_) throws Exception {
new ShexValidator(new File(shexpath), new File(goshapemappath), tbox_reasoner_, curieHandler_);
}
public ShexValidator(File shex_schema_file, File shex_map_file, OWLReasoner tbox_reasoner_, CurieHandler curieHandler_) throws Exception {
schema = GenParser.parseSchema(shex_schema_file.toPath());
GoQueryMap = makeGoQueryMap(shex_map_file.getAbsolutePath());
tbox_reasoner = tbox_reasoner_;
shape_expected_property_ranges = new HashMap<Label, Map<String, Set<String>>>();
curieHandler = curieHandler_;
rdfFactory = new SimpleRDF();
for(String shapelabel : GoQueryMap.keySet()) {
if(shapelabel.equals("http://purl.obolibrary.org/obo/go/shapes/AnnotatedEdge")) {
continue;
}
Label shape_label = new Label(rdfFactory.createIRI(shapelabel));
ShapeExpr rule = schema.getRules().get(shape_label);
Map<String, Set<String>> expected_property_ranges = getPropertyRangeMap(rule, null);
shape_expected_property_ranges.put(shape_label, expected_property_ranges);
}
}
public static Map<String, String> makeGoQueryMap(String shapemap_file) throws IOException{
Map<String, String> shapelabel_sparql = new HashMap<String, String>();
BufferedReader reader = new BufferedReader(new FileReader(shapemap_file));
String line = reader.readLine();
String all = line;
while(line!=null) {
all+=line;
line = reader.readLine();
}
reader.close();
String[] maps = all.split(",");
for(String map : maps) {
String sparql = StringUtils.substringBetween(map, "'", "'");
sparql = sparql.replace("a/", "<http://www.w3.org/1999/02/22-rdf-syntax-ns#type> ?c . ?c ");
String[] shapemaprow = map.split("@");
String shapelabel = shapemaprow[1];
shapelabel = shapelabel.replace(">", "");
shapelabel = shapelabel.replace("<", "");
shapelabel = shapelabel.trim();
shapelabel_sparql.put(shapelabel, sparql);
}
return shapelabel_sparql;
}
public ShexValidationReport runShapeMapValidation(Model test_model, boolean stream_output) throws Exception {
ShexValidationReport r = new ShexValidationReport(null, test_model);
RDF rdfFactory = new SimpleRDF();
JenaRDF jr = new JenaRDF();
//this shex implementation likes to use the commons JenaRDF interface, nothing exciting here
JenaGraph shexy_graph = jr.asGraph(test_model);
//recursive only checks the focus node against the chosen shape.
RecursiveValidation shex_model_validator = new RecursiveValidation(schema, shexy_graph);
//for each shape in the query map (e.g. MF, BP, CC, etc.)
boolean all_good = true;
for(String shapelabel : GoQueryMap.keySet()) {
//not quite the same pattern as the other shapes
//TODO needs more work
if(shapelabel.equals("http://purl.obolibrary.org/obo/go/shapes/AnnotatedEdge")) {
continue;
}
Label shape_label = new Label(rdfFactory.createIRI(shapelabel));
//get the nodes in this model that SHOULD match the shape
Set<Resource> focus_nodes = getFocusNodesBySparql(test_model, GoQueryMap.get(shapelabel));
for(Resource focus_node_resource : focus_nodes) {
if(focus_node_resource==null) {
System.out.println("null focus node for shape "+shape_label);
continue;
}
//check for use of properties not defined for this shape (okay if OPEN, not if CLOSED)
Set<ShexViolation> extra_prop_violations = checkForExtraProperties(focus_node_resource, test_model, shape_label, shex_model_validator);
if(extra_prop_violations != null && !extra_prop_violations.isEmpty()) {
for(Violation v : extra_prop_violations) {
r.addViolation(v);
}
all_good = false;
}
RDFTerm focus_node = null;
String focus_node_id = "";
if(focus_node_resource.isURIResource()) {
focus_node = rdfFactory.createIRI(focus_node_resource.getURI());
focus_node_id = focus_node_resource.getURI();
}else {
focus_node = rdfFactory.createBlankNode(focus_node_resource.getId().getLabelString());
focus_node_id = focus_node_resource.getId().getLabelString();
}
//deal with curies for output
String node = focus_node_id;
node = getCurie(focus_node_id);
// if(curieHandler!=null) {
// node = curieHandler.getCuri(IRI.create(focus_node_resource.getURI()));
// }
//check the node against the intended shape
shex_model_validator.validate(focus_node, shape_label);
Typing typing = shex_model_validator.getTyping();
//capture the result
Status status = typing.getStatus(focus_node, shape_label);
if(status.equals(Status.CONFORMANT)) {
Set<String> shape_ids = r.node_matched_shapes.get(node);
if(shape_ids==null) {
shape_ids = new HashSet<String>();
}
shape_ids.add(shapelabel);
r.node_matched_shapes.put(node, shape_ids);
}else if(status.equals(Status.NONCONFORMANT)) {
//if any of these tests is invalid, the model is invalid
all_good = false;
//implementing a start on a generic violation report structure here
ShexViolation violation = new ShexViolation(node);
ShexExplanation explanation = new ShexExplanation();
String shape_curie = getCurie(shapelabel);
explanation.setShape(shape_curie);
Set<ShexConstraint> unmet_constraints = getUnmetConstraints(focus_node_resource, shapelabel, test_model);
for(ShexConstraint constraint : unmet_constraints) {
explanation.addConstraint(constraint);
violation.addExplanation(explanation);
}
r.addViolation(violation);
}else if(status.equals(Status.NOTCOMPUTED)) {
//if any of these are not computed, there is a problem
String error = focus_node_id+" was not tested against "+shapelabel;
LOGGER.info(error);
}
}
}
if(all_good) {
r.conformant = true;
}else {
r.conformant = false;
}
return r;
}
public static Set<Resource> getFocusNodesBySparql(Model model, String sparql){
Set<Resource> nodes = new HashSet<Resource>();
QueryExecution qe = QueryExecutionFactory.create(sparql, model);
ResultSet results = qe.execSelect();
while (results.hasNext()) {
QuerySolution qs = results.next();
Resource node = qs.getResource("x");
nodes.add(node);
}
qe.close();
return nodes;
}
/**
* Check each focus node for the use of any properties that don't appear in the shape
* @param focus_nodes
* @param model
* @param shape_label
* @return
*/
public Set<ShexViolation> checkForExtraProperties(Resource node_r, Model model, Label shape_label, RecursiveValidation shex_model_validator){
Set<ShexViolation> violations = new HashSet<ShexViolation>();
Set<String> allowed_properties = this.shape_expected_property_ranges.get(shape_label).keySet();
Set<String> actual_properties = new HashSet<String>();
Map<String, String> prop_value = new HashMap<String, String>(); //don't really care if there are multiple values, one will do.
String sparql = "select distinct ?prop ?value where{ <"+node_r.getURI()+"> ?prop ?value }";
QueryExecution qe = QueryExecutionFactory.create(sparql, model);
ResultSet results = qe.execSelect();
while (results.hasNext()) {
QuerySolution qs = results.next();
Resource prop = qs.getResource("prop");
RDFNode value = qs.get("value");
String v = "value";
if(value.isResource()) {
v = value.asResource().getURI();
}else if(value.isLiteral()) {
v = value.asLiteral().getString();
}
actual_properties.add(prop.getURI());
prop_value.put(prop.getURI(), v);
}
qe.close();
actual_properties.removeAll(allowed_properties);
if(!actual_properties.isEmpty()) {
ShexViolation extra = new ShexViolation(getCurie(node_r.getURI()));
Set<ShexExplanation> explanations = new HashSet<ShexExplanation>();
for(String prop : actual_properties) {
String value = prop_value.get(prop);
ShexExplanation extra_explain = new ShexExplanation();
extra_explain.setShape(getCurie(shape_label.stringValue()));
String object = value;
Set<String> intended_range_shapes = new HashSet<String>();
//For this CLOSED test, no shape fits in intended. Any use of the property here would be incorrect.
intended_range_shapes.add("owl:Nothing");
Set<String> node_types = getNodeTypes(model, node_r.getURI());
Set<String> object_types = getNodeTypes(model, value);
//TODO consider here. extra info but not really meaningful - anything in the range would be wrong.
Set<String> matched_range_shapes = getAllMatchedShapes(value, shex_model_validator);
String report_prop = getCurie(prop);
ShexConstraint c = new ShexConstraint(object, report_prop, intended_range_shapes, node_types, object_types);
c.setMatched_range_shapes(matched_range_shapes);
Set<ShexConstraint> cs = new HashSet<ShexConstraint>();
cs.add(c);
extra_explain.setConstraints(cs);
explanations.add(extra_explain);
}
extra.setExplanations(explanations);
violations.add(extra);
}
return violations;
}
public Model enrichSuperClasses(Model model) {
String getOntTerms =
"PREFIX owl: <http://www.w3.org/2002/07/owl#> "
+ "SELECT DISTINCT ?term " +
" WHERE { " +
" ?ind a owl:NamedIndividual . " +
" ?ind a ?term . " +
" FILTER(?term != owl:NamedIndividual)" +
" FILTER(isIRI(?term)) ." +
" }";
String terms = "";
Set<String> term_set = new HashSet<String>();
try{
QueryExecution qe = QueryExecutionFactory.create(getOntTerms, model);
ResultSet results = qe.execSelect();
while (results.hasNext()) {
QuerySolution qs = results.next();
Resource term = qs.getResource("term");
terms+=("<"+term.getURI()+"> ");
term_set.add(term.getURI());
}
qe.close();
} catch(QueryParseException e){
e.printStackTrace();
}
if(tbox_reasoner!=null) {
for(String term : term_set) {
OWLClass c =
tbox_reasoner.
getRootOntology().
getOWLOntologyManager().
getOWLDataFactory().getOWLClass(IRI.create(term));
Resource child = model.createResource(term);
Set<OWLClass> supers = tbox_reasoner.getSuperClasses(c, false).getFlattened();
for(OWLClass parent_class : supers) {
Resource parent = model.createResource(parent_class.getIRI().toString());
model.add(model.createStatement(child, org.apache.jena.vocabulary.RDFS.subClassOf, child));
model.add(model.createStatement(child, org.apache.jena.vocabulary.RDFS.subClassOf, parent));
model.add(model.createStatement(child, org.apache.jena.vocabulary.RDF.type, org.apache.jena.vocabulary.OWL.Class));
}
}
}else {
String superQuery = ""
+ "PREFIX owl: <http://www.w3.org/2002/07/owl#> "
+ "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> "
+ "CONSTRUCT { " +
" ?term rdfs:subClassOf ?superclass ." +
" ?term a owl:Class ." +
" }" +
" WHERE {" +
" VALUES ?term { "+terms+" } " +
" ?term rdfs:subClassOf* ?superclass ." +
" FILTER(isIRI(?superclass)) ." +
" }";
Query query = QueryFactory.create(superQuery);
try (
QueryExecution qexec = QueryExecutionFactory.sparqlService(endpoint, query) ) {
qexec.execConstruct(model);
qexec.close();
} catch(QueryParseException e){
e.printStackTrace();
}
}
return model;
}
public Set<String> getNodeTypes(Model model, String node_uri) {
String getOntTerms =
"PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> "
+ "PREFIX owl: <http://www.w3.org/2002/07/owl#> "
+ "SELECT DISTINCT ?type " +
" WHERE { " +
"<"+node_uri+"> rdf:type ?type . " +
"FILTER(?type != owl:NamedIndividual)" +
" }";
Set<String> types = new HashSet<String>();
try{
QueryExecution qe = QueryExecutionFactory.create(getOntTerms, model);
ResultSet results = qe.execSelect();
while (results.hasNext()) {
QuerySolution qs = results.next();
Resource type = qs.getResource("type");
types.add(getCurie(type.getURI()));
OWLClass t = tbox_reasoner.getRootOntology().getOWLOntologyManager().getOWLDataFactory().getOWLClass(IRI.create(type.getURI()));
for(OWLClass p : tbox_reasoner.getSuperClasses(t, false).getFlattened()) {
String type_curie = getCurie(p.getIRI().toString());
types.add(type_curie);
}
}
qe.close();
} catch(QueryParseException e){
e.printStackTrace();
}
return types;
}
private Set<ShexConstraint> getUnmetConstraints(Resource focus_node, String shape_id, Model model) {
Set<String> node_types = getNodeTypes(model, focus_node.getURI());
Set<ShexConstraint> unmet_constraints = new HashSet<ShexConstraint>();
RDF rdfFactory = new SimpleRDF();
Label shape_label = new Label(rdfFactory.createIRI(shape_id));
Map<String, Set<String>> expected_property_ranges = shape_expected_property_ranges.get(shape_label);
//get a map from properties to actual shapes of the asserted objects
JenaRDF jr = new JenaRDF();
JenaGraph shexy_graph = jr.asGraph(model);
RecursiveValidation shex_model_validator = new RecursiveValidation(schema, shexy_graph);
//get the focus node in the rdf model
//check for assertions with properties in the target shape
for(String prop_uri : expected_property_ranges.keySet()) {
Property prop = model.getProperty(prop_uri);
//checking on objects of this property for the problem node.
for (StmtIterator i = focus_node.listProperties(prop); i.hasNext(); ) {
RDFNode obj = i.nextStatement().getObject();
//check the computed shapes for this individual
if(!obj.isResource()) {
continue;
//no checks on literal values at this time
}else if(prop_uri.equals("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")&&obj.asResource().getURI().equals("http://www.w3.org/2002/07/owl#NamedIndividual")) {
continue; //ignore type owl individual
}
RDFTerm range_obj = rdfFactory.createIRI(obj.asResource().getURI());
//does it hit any allowable shapes?
boolean good = false;
//TODO many property ranges are MISSING from previous step
//e.g. any OR will not show up here.
Set<String> expected_ranges = expected_property_ranges.get(prop_uri);
for(String target_shape_uri : expected_ranges) {
if(target_shape_uri.equals(".")) {
//anything is fine
good = true;
break;
}else if(target_shape_uri.trim().equals("<http://www.w3.org/2001/XMLSchema#string>")) {
//ignore syntax type checking for now
good = true;
break;
}
Label target_shape_label = null;
try {
target_shape_label = new Label(rdfFactory.createIRI(target_shape_uri));
shex_model_validator.validate(range_obj, target_shape_label);
//could use refine to get all of the actual shapes - but would want to do this
//once per validation...
//RefineValidation shex_refine_validator = new RefineValidation(schema, shexy_graph);
Typing shape_test = shex_model_validator.getTyping();
Pair<RDFTerm, Label> p = new Pair<RDFTerm, Label>(range_obj, target_shape_label);
Status r = shape_test.getStatusMap().get(p);
if(r.equals(Status.CONFORMANT)) {
good = true;
break;
}
}catch(Exception e) {
System.out.println(e+"\nbroken target shape uri:"+target_shape_uri);
}
}
if(!good) {
String object = obj.toString();
Set<String> object_types = getNodeTypes(model, object);
String property = prop.toString();
object = getCurie(object);
property = getCurie(property);
Set<String> expected = new HashSet<String>();
for(String e : expected_property_ranges.get(prop_uri)) {
String curie_e = getCurie(e);
expected.add(curie_e);
}
ShexConstraint constraint = new ShexConstraint(object, property, expected, node_types, object_types);
//return all shapes that are matched by this node for explanation
Set<String> obj_matched_shapes = getAllMatchedShapes(range_obj, shex_model_validator);
constraint.setMatched_range_shapes(obj_matched_shapes);
unmet_constraints.add(constraint);
}
}
}
return unmet_constraints;
}
public Set<String> getAllMatchedShapes(RDFTerm node, RecursiveValidation shex_model_validator){
Set<Label> all_shapes_in_schema = getAllShapesInSchema();
Set<String> obj_matched_shapes = new HashSet<String>();
for(Label target_shape_label : all_shapes_in_schema) {
shex_model_validator.validate(node, target_shape_label);
Typing shape_test = shex_model_validator.getTyping();
Pair<RDFTerm, Label> p = new Pair<RDFTerm, Label>(node, target_shape_label);
Status r = shape_test.getStatusMap().get(p);
if(r.equals(Status.CONFORMANT)) {
obj_matched_shapes.add(getCurie(target_shape_label.stringValue()));
}
}
return obj_matched_shapes;
}
public Set<String> getAllMatchedShapes(String node_uri, RecursiveValidation shex_model_validator){
RDFTerm range_obj = rdfFactory.createIRI(node_uri);
return getAllMatchedShapes(range_obj, shex_model_validator);
}
private Set<Label> getAllShapesInSchema() {
return schema.getRules().keySet();
}
public String getCurie(String uri) {
String curie = uri;
if(curieHandler!=null) {
curie = curieHandler.getCuri(IRI.create(uri));
}
return curie;
}
public Map<String, Set<String>> getPropertyRangeMap(ShapeExpr expr, Map<String, Set<String>> prop_range){
if(prop_range==null) {
prop_range = new HashMap<String, Set<String>>();
}
String explanation = "";
if(expr instanceof ShapeAnd) {
explanation += "And\n";
ShapeAnd andshape = (ShapeAnd)expr;
for(ShapeExpr subexp : andshape.getSubExpressions()) {
//boolean is_closed = subexp.closed;
prop_range = getPropertyRangeMap(subexp, prop_range);
explanation += subexp+" ";
}
}
else if (expr instanceof ShapeOr) {
explanation += "Or\n";
ShapeOr orshape = (ShapeOr)expr;
for(ShapeExpr subexp : orshape.getSubExpressions()) {
explanation += subexp;
//explainShape(subexp, explanation);
}
}else if(expr instanceof ShapeExprRef) {
ShapeExprRef ref = (ShapeExprRef) expr;
ShapeExpr ref_expr = ref.getShapeDefinition();
prop_range = getPropertyRangeMap(ref_expr, prop_range);
//not in the rdf model - this is a match of this expr on a shape
//e.g. <http://purl.obolibrary.org/obo/go/shapes/GoCamEntity>
explanation += "\t\tis a: "+((ShapeExprRef) expr).getLabel()+"\n";
}else if(expr instanceof Shape) {
Shape shape = (Shape)expr;
TripleExpr texp = shape.getTripleExpression();
prop_range = getPropertyRangeMap(texp, prop_range);
}else if (expr instanceof NodeConstraint) {
NodeConstraint nc = (NodeConstraint)expr;
explanation += "\t\tnode constraint "+nc.toPrettyString();
}
else {
explanation+=" Not sure what is: "+expr;
}
return prop_range;
}
public Map<String, Set<String>> getPropertyRangeMap(TripleExpr texp, Map<String, Set<String>> prop_range) {
if(prop_range==null) {
prop_range = new HashMap<String, Set<String>>();
}
if(texp instanceof TripleConstraint) {
TripleConstraint tcon = (TripleConstraint)texp;
TCProperty tprop = tcon.getProperty();
ShapeExpr range = tcon.getShapeExpr();
String prop_uri = tprop.getIri().toString();
Set<String> ranges = prop_range.get(prop_uri);
if(ranges==null) {
ranges = new HashSet<String>();
}
ranges.addAll(getShapeExprRefs(range,ranges));
prop_range.put(prop_uri, ranges);
}else if(texp instanceof EachOf){
EachOf each = (EachOf)texp;
for(TripleExpr eachtexp : each.getSubExpressions()) {
if(!texp.equals(eachtexp)) {
prop_range = getPropertyRangeMap(eachtexp, prop_range);
}
}
}else if(texp instanceof RepeatedTripleExpression) {
RepeatedTripleExpression rep = (RepeatedTripleExpression)texp;
rep.getCardinality().toString();
TripleExpr t = rep.getSubExpression();
prop_range = getPropertyRangeMap(t, prop_range);
}
else {
System.out.println("\tlost again here on "+texp);
}
return prop_range;
}
private Set<String> getShapeExprRefs(ShapeExpr expr, Set<String> shape_refs) {
if(shape_refs==null) {
shape_refs = new HashSet<String>();
}
if(expr instanceof ShapeExprRef) {
shape_refs.add(((ShapeExprRef) expr).getLabel().stringValue());
}else if(expr instanceof ShapeAnd) {
ShapeAnd andshape = (ShapeAnd)expr;
System.out.println("currently ignoring And shape in range: "+expr);
// for(ShapeExpr subexp : andshape.getSubExpressions()) {
// shape_refs = getShapeExprRefs(subexp, shape_refs);
// }
}else if (expr instanceof ShapeOr) {
ShapeOr orshape = (ShapeOr)expr;
for(ShapeExpr subexp : orshape.getSubExpressions()) {
shape_refs = getShapeExprRefs(subexp, shape_refs);
}
}else if (expr instanceof NodeConstraint){
String reference_string = ((NodeConstraint) expr).toPrettyString();
reference_string = reference_string.replace("<", "");
reference_string = reference_string.replace(">", "");
reference_string = reference_string.replace("[", "");
reference_string = reference_string.replace("]", "");
reference_string = reference_string.trim();
shape_refs.add(reference_string);
}else {
System.out.println("currently ignoring "+expr);
}
return shape_refs;
}
public static String getModelTitle(Model model) {
String model_title = null;
String q = "select ?cam ?title where {"
+ "GRAPH ?cam { "
+ "?cam <http://purl.org/dc/elements/1.1/title> ?title"
+ "}}";
// + "?cam <"+DC.description.getURI()+"> ?title }";
QueryExecution qe = QueryExecutionFactory.create(q, model);
ResultSet results = qe.execSelect();
if (results.hasNext()) {
QuerySolution qs = results.next();
Resource model_id_resource = qs.getResource("cam");
Literal title = qs.getLiteral("title");
model_title = title.getString();
}
qe.close();
return model_title;
}
}
| addressing shape inheritance issue
https://github.com/geneontology/go-shapes/issues/197#issuecomment-583902491
| minerva-core/src/main/java/org/geneontology/minerva/validation/ShexValidator.java | addressing shape inheritance issue |
|
Java | bsd-3-clause | 9760132c74e4e33b495b2b99e0d36f5177d66afd | 0 | krishagni/openspecimen,krishagni/openspecimen,asamgir/openspecimen,asamgir/openspecimen,asamgir/openspecimen,krishagni/openspecimen | /**
* <p>Title: NewSpecimenAction Class>
* <p>Description: NewSpecimenAction initializes the fields in the New Specimen page.</p>
* Copyright: Copyright (c) year
* Company: Washington University, School of Medicine, St. Louis.
* @author Aniruddha Phadnis
* @version 1.00
*/
package edu.wustl.catissuecore.action;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.Vector;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import edu.wustl.catissuecore.action.annotations.AnnotationConstants;
import edu.wustl.catissuecore.actionForm.NewSpecimenForm;
import edu.wustl.catissuecore.actionForm.SpecimenCollectionGroupForm;
import edu.wustl.catissuecore.bizlogic.AnnotationUtil;
import edu.wustl.catissuecore.bizlogic.BizLogicFactory;
import edu.wustl.catissuecore.bizlogic.NewSpecimenBizLogic;
import edu.wustl.catissuecore.bizlogic.StorageContainerBizLogic;
import edu.wustl.catissuecore.bizlogic.UserBizLogic;
import edu.wustl.catissuecore.client.CaCoreAppServicesDelegator;
import edu.wustl.catissuecore.domain.Biohazard;
import edu.wustl.catissuecore.domain.CollectionEventParameters;
import edu.wustl.catissuecore.domain.CollectionProtocol;
import edu.wustl.catissuecore.domain.CollectionProtocolRegistration;
import edu.wustl.catissuecore.domain.ConsentTier;
import edu.wustl.catissuecore.domain.ConsentTierResponse;
import edu.wustl.catissuecore.domain.ConsentTierStatus;
import edu.wustl.catissuecore.domain.ReceivedEventParameters;
import edu.wustl.catissuecore.domain.Specimen;
import edu.wustl.catissuecore.domain.SpecimenCollectionGroup;
import edu.wustl.catissuecore.domain.StorageContainer;
import edu.wustl.catissuecore.domain.User;
import edu.wustl.catissuecore.util.CatissueCoreCacheManager;
import edu.wustl.catissuecore.util.ConsentUtil;
import edu.wustl.catissuecore.util.EventsUtil;
import edu.wustl.catissuecore.util.StorageContainerUtil;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.catissuecore.util.global.DefaultValueManager;
import edu.wustl.catissuecore.util.global.Utility;
import edu.wustl.catissuecore.util.global.Variables;
import edu.wustl.common.action.SecureAction;
import edu.wustl.common.actionForm.AbstractActionForm;
import edu.wustl.common.beans.NameValueBean;
import edu.wustl.common.beans.SessionDataBean;
import edu.wustl.common.bizlogic.IBizLogic;
import edu.wustl.common.cde.CDE;
import edu.wustl.common.cde.CDEManager;
import edu.wustl.common.cde.PermissibleValue;
import edu.wustl.common.util.MapDataParser;
import edu.wustl.common.util.dbManager.DAOException;
import edu.wustl.common.util.logger.Logger;
/**
* NewSpecimenAction initializes the fields in the New Specimen page.
* @author aniruddha_phadnis
*/
public class NewSpecimenAction extends SecureAction
{
/**
* Overrides the execute method of Action class.
* @param mapping object of ActionMapping
* @param form object of ActionForm
* @param request object of HttpServletRequest
* @param response object of HttpServletResponse
* @throws Exception generic exception
*/
public ActionForward executeSecureAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception
{
//Logger.out.debug("NewSpecimenAction start@@@@@@@@@");
NewSpecimenForm specimenForm = (NewSpecimenForm) form;
List<NameValueBean> storagePositionList = Utility.getStoragePositionTypeList();
request.setAttribute("storageList", storagePositionList);
String pageOf = request.getParameter(Constants.PAGEOF);
String forwardPage=specimenForm.getForwardTo();
if(forwardPage.equals(Constants.PAGEOF_SPECIMEN_COLLECTION_REQUIREMENT_GROUP))
{
pageOf=forwardPage;
request.setAttribute(Constants.STATUS_MESSAGE_KEY, "errors.specimencollectionrequirementgroupedit");
return mapping.findForward(pageOf);
}
IBizLogic bizLogicObj = BizLogicFactory.getInstance().getBizLogic(Constants.DEFAULT_BIZ_LOGIC);
NewSpecimenBizLogic bizLogic = (NewSpecimenBizLogic) BizLogicFactory.getInstance().getBizLogic(Constants.NEW_SPECIMEN_FORM_ID);
String treeRefresh = request.getParameter("refresh");
request.setAttribute("refresh",treeRefresh);
//Gets the value of the operation parameter.
String operation = (String) request.getParameter(Constants.OPERATION);
//boolean to indicate whether the suitable containers to be shown in dropdown
//is exceeding the max limit.
String exceedingMaxLimit = new String();
//Sets the operation attribute to be used in the Edit/View Specimen Page in Advance Search Object View.
request.setAttribute(Constants.OPERATION, operation);
if (operation != null && operation.equalsIgnoreCase(Constants.ADD))
{
specimenForm.setId(0);
}
String virtuallyLocated = request.getParameter("virtualLocated");
if (virtuallyLocated != null && virtuallyLocated.equals("true"))
{
specimenForm.setVirtuallyLocated(true);
}
//Name of button clicked
String button = request.getParameter("button");
Map map = null;
if (button != null)
{
if (button.equals("deleteExId"))
{
List key = new ArrayList();
key.add("ExternalIdentifier:i_name");
key.add("ExternalIdentifier:i_value");
//Gets the map from ActionForm
map = specimenForm.getExternalIdentifier();
MapDataParser.deleteRow(key, map, request.getParameter("status"));
}
else
{
List key = new ArrayList();
key.add("Biohazard:i_type");
key.add("Biohazard:i_id");
//Gets the map from ActionForm
map = specimenForm.getBiohazard();
MapDataParser.deleteRow(key, map, request.getParameter("status"));
}
}
// ************* ForwardTo implementation *************
HashMap forwardToHashMap = (HashMap) request.getAttribute("forwardToHashMap");
String specimenCollectionGroupName = "";
if (forwardToHashMap != null)
{
String specimenCollectionGroupId = (String) forwardToHashMap.get("specimenCollectionGroupId");
/**For Migration Start**/
specimenCollectionGroupName = (String) forwardToHashMap.get("specimenCollectionGroupName");
Logger.out.debug("specimenCollectionGroupName found in forwardToHashMap========>>>>>>" + specimenCollectionGroupName);
specimenForm.setSpecimenCollectionGroupName(specimenCollectionGroupName);
/**For Migration End**/
Logger.out.debug("SpecimenCollectionGroupId found in forwardToHashMap========>>>>>>" + specimenCollectionGroupId);
if (specimenCollectionGroupId != null)
{
/**
* Retaining properties of specimen when more is clicked.
* Bug no -- 2623
*/
//Populating the specimen collection group name in the specimen page
setFormValues(specimenForm, specimenCollectionGroupId,specimenCollectionGroupName);
}
}
//************* ForwardTo implementation *************
//Consent Tracking (Virender Mehta) - Start
//Adding name,value pair in NameValueBean
String tabSelected = request.getParameter(Constants.SELECTED_TAB);
if(tabSelected!=null)
{
request.setAttribute(Constants.SELECTED_TAB,tabSelected);
}
String scg_id=String.valueOf(specimenForm.getSpecimenCollectionGroupId());
SpecimenCollectionGroup specimenCollectionGroup= Utility.getSCGObj(scg_id);
//PHI Data
String initialURLValue="";
String initialWitnessValue="";
String initialSignedConsentDateValue="";
//Lazy - specimenCollectionGroup.getCollectionProtocolRegistration()
CollectionProtocolRegistration collectionProtocolRegistration = specimenCollectionGroup.getCollectionProtocolRegistration();
if(collectionProtocolRegistration ==null || collectionProtocolRegistration.getSignedConsentDocumentURL()==null)
{
initialURLValue=Constants.NULL;
}
User consentWitness=null;
if(collectionProtocolRegistration.getId()!= null)
{
consentWitness = (User)bizLogicObj.retrieveAttribute(CollectionProtocolRegistration.class.getName(),collectionProtocolRegistration.getId(), "consentWitness");
}
//User consentWitness= collectionProtocolRegistration.getConsentWitness();
//Resolved lazy
if(consentWitness==null)
{
initialWitnessValue=Constants.NULL;
}
if(collectionProtocolRegistration.getConsentSignatureDate()==null)
{
initialSignedConsentDateValue=Constants.NULL;
}
List cprObjectList=new ArrayList();
cprObjectList.add(collectionProtocolRegistration);
SessionDataBean sessionDataBean=(SessionDataBean)request.getSession().getAttribute(Constants.SESSION_DATA);
CaCoreAppServicesDelegator caCoreAppServicesDelegator = new CaCoreAppServicesDelegator();
String userName = Utility.toString(sessionDataBean.getUserName());
List collProtObject = caCoreAppServicesDelegator.delegateSearchFilter(userName,cprObjectList);
CollectionProtocolRegistration cprObject =null;
cprObject = collectionProtocolRegistration;//(CollectionProtocolRegistration)collProtObject.get(0);
String witnessName="";
String getConsentDate="";
String getSignedConsentURL="";
User witness = cprObject.getConsentWitness();
if(witness==null)
{
if(initialWitnessValue.equals(Constants.NULL))
{
witnessName="";
}
else
{
witnessName=Constants.HASHED_OUT;
}
specimenForm.setWitnessName(witnessName);
}
else
{
witness = (User)bizLogicObj.retrieveAttribute(CollectionProtocolRegistration.class.getName(),cprObject.getId(), "consentWitness");
String witnessFullName = witness.getLastName()+", "+witness.getFirstName();
specimenForm.setWitnessName(witnessFullName);
}
if(cprObject.getConsentSignatureDate()==null)
{
if(initialSignedConsentDateValue.equals(Constants.NULL))
{
getConsentDate="";
}
else
{
getConsentDate=Constants.HASHED_OUT;
}
}
else
{
getConsentDate=Utility.parseDateToString(cprObject.getConsentSignatureDate(), Variables.dateFormat);
}
if(cprObject.getSignedConsentDocumentURL()==null)
{
if(initialURLValue.equals(Constants.NULL))
{
getSignedConsentURL="";
}
else
{
getSignedConsentURL=Constants.HASHED_OUT;
}
}
else
{
getSignedConsentURL=Utility.toString(cprObject.getSignedConsentDocumentURL());
}
specimenForm.setConsentDate(getConsentDate);
specimenForm.setSignedConsentUrl(getSignedConsentURL);
Collection consentTierRespCollection = (Collection)bizLogicObj.retrieveAttribute(CollectionProtocolRegistration.class.getName(),cprObject.getId(), "elements(consentTierResponseCollection)" );
//Lazy Resolved --- cprObject.getConsentTierResponseCollection()
Set participantResponseSet =(Set)consentTierRespCollection;
List participantResponseList;
if (participantResponseSet != null)
{
participantResponseList = new ArrayList(participantResponseSet);
}
else
{
participantResponseList = new ArrayList();
}
if(operation.equalsIgnoreCase(Constants.ADD))
{
ActionErrors errors = (ActionErrors) request.getAttribute(Globals.ERROR_KEY);
if(errors == null)
{
String scgDropDown = request.getParameter(Constants.SCG_DROPDOWN);
if(scgDropDown==null||scgDropDown.equalsIgnoreCase(Constants.TRUE))
{
Collection consentResponseStatuslevel=(Collection)bizLogicObj.retrieveAttribute(SpecimenCollectionGroup.class.getName(),specimenCollectionGroup.getId(), "elements(consentTierStatusCollection)");
Map tempMap=prepareConsentMap(participantResponseList,consentResponseStatuslevel);
specimenForm.setConsentResponseForSpecimenValues(tempMap);
}
}
specimenForm.setConsentTierCounter(participantResponseList.size());
}
else
{
String specimenID = null;
specimenID = String.valueOf(specimenForm.getId());
//List added for grid
List specimenDetails= new ArrayList();
SessionDataBean sessionData = (SessionDataBean) request.getSession().getAttribute(Constants.SESSION_DATA);
Specimen specimen = bizLogic.getSpecimen(specimenID,specimenDetails, sessionData);
//Added by Falguni=To set Specimen label in Form.
/*Bug id = 11480
*Resolved by : Himanshu Aseeja
*/
List columnList=columnNames();
String consentResponseHql ="select elements(scg.collectionProtocolRegistration.consentTierResponseCollection)"+
" from edu.wustl.catissuecore.domain.SpecimenCollectionGroup as scg," +
" edu.wustl.catissuecore.domain.Specimen as spec " +
" where spec.specimenCollectionGroup.id=scg.id and spec.id="+ specimen.getId();
Collection consentResponse = Utility.executeQuery(consentResponseHql);
Collection consentResponseStatuslevel=(Collection)bizLogicObj.retrieveAttribute(Specimen.class.getName(),specimen.getId(), "elements(consentTierStatusCollection)");
String specimenResponse = "_specimenLevelResponse";
String specimenResponseId = "_specimenLevelResponseID";
Map tempMap=ConsentUtil.prepareSCGResponseMap(consentResponseStatuslevel, consentResponse,specimenResponse,specimenResponseId);
specimenForm.setConsentResponseForSpecimenValues(tempMap);
specimenForm.setConsentTierCounter(participantResponseList.size()) ;
HttpSession session =request.getSession();
request.setAttribute("showContainer", specimen.getCollectionStatus());
session.setAttribute(Constants.SPECIMEN_LIST,specimenDetails);
session.setAttribute(Constants.COLUMNLIST,columnList);
}
List specimenResponseList = new ArrayList();
specimenResponseList=Utility.responceList(operation);
request.setAttribute(Constants.SPECIMEN_RESPONSELIST, specimenResponseList);
//Consent Tracking (Virender Mehta) - Stop
pageOf = request.getParameter(Constants.PAGEOF);
request.setAttribute(Constants.PAGEOF, pageOf);
//Sets the activityStatusList attribute to be used in the Site Add/Edit Page.
request.setAttribute(Constants.ACTIVITYSTATUSLIST, Constants.ACTIVITY_STATUS_VALUES);
//Sets the collectionStatusList attribute to be used in the Site Add/Edit Page.
request.setAttribute(Constants.COLLECTIONSTATUSLIST, Constants.SPECIMEN_COLLECTION_STATUS_VALUES);
//NewSpecimenBizLogic bizLogic = (NewSpecimenBizLogic) BizLogicFactory.getInstance().getBizLogic(Constants.NEW_SPECIMEN_FORM_ID);
if (specimenForm.isParentPresent())//If parent specimen is present then
{
// String[] fields = {Constants.SYSTEM_LABEL};
// List parentSpecimenList = bizLogic.getList(Specimen.class.getName(), fields, Constants.SYSTEM_IDENTIFIER, true);
// request.setAttribute(Constants.PARENT_SPECIMEN_ID_LIST, parentSpecimenList);
}
String[] bhIdArray = {"-1"};
String[] bhTypeArray = {Constants.SELECT_OPTION};
String[] bhNameArray = {Constants.SELECT_OPTION};
String[] selectColNames = {Constants.SYSTEM_IDENTIFIER, "name", "type"};
List biohazardList = bizLogic.retrieve(Biohazard.class.getName(), selectColNames);
Iterator iterator = biohazardList.iterator();
//Creating & setting the biohazard name, id & type list
if (biohazardList != null && !biohazardList.isEmpty())
{
bhIdArray = new String[biohazardList.size() + 1];
bhTypeArray = new String[biohazardList.size() + 1];
bhNameArray = new String[biohazardList.size() + 1];
bhIdArray[0] = "-1";
bhTypeArray[0] = "";
bhNameArray[0] = Constants.SELECT_OPTION;
int i = 1;
while (iterator.hasNext())
{
Object[] hazard = (Object[]) iterator.next();
bhIdArray[i] = String.valueOf(hazard[0]);
bhNameArray[i] = (String) hazard[1];
bhTypeArray[i] = (String) hazard[2];
i++;
}
}
request.setAttribute(Constants.BIOHAZARD_NAME_LIST, bhNameArray);
request.setAttribute(Constants.BIOHAZARD_ID_LIST, bhIdArray);
request.setAttribute(Constants.BIOHAZARD_TYPES_LIST, bhTypeArray);
/**
* Name: Chetan Patil
* Reviewer: Sachin Lale
* Bug ID: Bug#3184
* Patch ID: Bug#3184_1
* Also See: 2-6
* Description: Here the older code has been integrated again inorder to restrict the specimen values based on
* requirements of study calendar event point. Two method are written to separate the code. Method populateAllRestrictedLists()
* will populate the values for the lists form Specimen Requirements whereas, method populateAllLists() will populate the values
* of the list form the system.
*/
//Setting Secimen Collection Group
/**For Migration Start**/
// initializeAndSetSpecimenCollectionGroupIdList(bizLogic,request);
/**For Migration Start**/
/**
* Patch ID: Bug#4245_2
*
*/
List<NameValueBean> specimenClassList = new ArrayList<NameValueBean>();
List<NameValueBean> specimenTypeList = new ArrayList<NameValueBean>();
List<NameValueBean> tissueSiteList = new ArrayList<NameValueBean>();
List<NameValueBean> tissueSideList = new ArrayList<NameValueBean>();
List<NameValueBean> pathologicalStatusList = new ArrayList<NameValueBean>();
Map<String, List<NameValueBean>> subTypeMap = new HashMap<String, List<NameValueBean>>();
String specimenCollectionGroupId = specimenForm.getSpecimenCollectionGroupId();
if (specimenCollectionGroupId != null && !specimenCollectionGroupId.equals(""))
{ // If specimen is being added form specimen collection group page or a specimen is being edited.
if (Constants.ALIQUOT.equals(specimenForm.getLineage()))
{
populateListBoxes(specimenForm, request);
}
populateAllLists(specimenForm, specimenClassList, specimenTypeList, tissueSiteList, tissueSideList,
pathologicalStatusList, subTypeMap);
}
else
{ // On adding a new specimen independently.
populateAllLists(specimenForm, specimenClassList, specimenTypeList, tissueSiteList, tissueSideList,
pathologicalStatusList, subTypeMap);
}
/**
* Name : Virender Mehta
* Reviewer: Sachin Lale
* Bug ID: defaultValueConfiguration_BugID
* Patch ID:defaultValueConfiguration_BugID_10
* See also:defaultValueConfiguration_BugID_9,11
* Description: Configuration of default value for TissueSite, TissueSite, PathologicalStatus
*
* Note by Chetan: Value setting for TissueSite and PathologicalStatus has been moved into the
* method populateAllLists().
*/
// Setting the default values
if (specimenForm.getTissueSide() == null || specimenForm.getTissueSide().equals("-1"))
{
specimenForm.setTissueSide((String)DefaultValueManager.getDefaultValue(Constants.DEFAULT_TISSUE_SIDE));
}
// sets the Specimen Class list
request.setAttribute(Constants.SPECIMEN_CLASS_LIST, specimenClassList);
// sets the Specimen Type list
request.setAttribute(Constants.SPECIMEN_TYPE_LIST, specimenTypeList);
// sets the Tissue Site list
request.setAttribute(Constants.TISSUE_SITE_LIST, tissueSiteList);
// sets the PathologicalStatus list
request.setAttribute(Constants.PATHOLOGICAL_STATUS_LIST, pathologicalStatusList);
// sets the Side list
request.setAttribute(Constants.TISSUE_SIDE_LIST, tissueSideList);
// set the map of subtype
request.setAttribute(Constants.SPECIMEN_TYPE_MAP, subTypeMap);
//Setting biohazard list
biohazardList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_BIOHAZARD, null);
request.setAttribute(Constants.BIOHAZARD_TYPE_LIST, biohazardList);
/**
* Name : Ashish Gupta
* Reviewer Name : Sachin Lale
* Bug ID: 2741
* Patch ID: 2741_12
* Description: Propagating events from scg to multiple specimens
*/
if(operation.equals(Constants.ADD))
populateEventsFromScg(specimenCollectionGroup,specimenForm);
Object scgForm = request.getAttribute("scgForm");
if(scgForm != null)
{
SpecimenCollectionGroupForm specimenCollectionGroupForm = (SpecimenCollectionGroupForm)scgForm;
}
else
{
//Mandar : 10-July-06 AutoEvents : CollectionEvent
setCollectionEventRequestParameters(request, specimenForm);
//Mandar : 11-July-06 AutoEvents : ReceivedEvent
setReceivedEventRequestParameters(request, specimenForm);
//Mandar : set default date and time too event fields
setDateParameters(specimenForm);
}
// ---- chetan 15-06-06 ----
StorageContainerBizLogic scbizLogic = (StorageContainerBizLogic) BizLogicFactory.getInstance().getBizLogic(
Constants.STORAGE_CONTAINER_FORM_ID);
TreeMap containerMap = new TreeMap();
List initialValues = null;
if (operation.equals(Constants.ADD))
{
SessionDataBean sessionData = (SessionDataBean) request.getSession().getAttribute(Constants.SESSION_DATA);
if(specimenForm.getLabel()==null || specimenForm.getLabel().equals(""))
{
//int totalNoOfSpecimen = bizLogic.totalNoOfSpecimen(sessionData)+1;
/**
* Name : Virender Mehta
* Reviewer: Sachin Lale
* Description: By getting instance of AbstractSpecimenGenerator abstract class current label retrived and set.
*/
// SpecimenLabelGenerator spLblGenerator = SpecimenLabelGeneratorFactory.getInstance();
// Map inputMap = new HashMap();
// inputMap.put(Constants.SCG_NAME_KEY, specimenCollectionGroupName);
// String specimenLabel= spLblGenerator.getNextAvailableSpecimenlabel(inputMap);
// specimenForm.setLabel(specimenLabel);
}
if (specimenForm.getSpecimenCollectionGroupName() != null && !specimenForm.getSpecimenCollectionGroupName().equals("")
&& specimenForm.getClassName() != null && !specimenForm.getClassName().equals("") && !specimenForm.getClassName().equals("-1"))
{
//Logger.out.debug("before retrieval of spCollGroupList inside specimen action ^^^^^^^^^^^");
String[] selectColumnName = {"collectionProtocolRegistration.collectionProtocol.id"};
String[] whereColumnName = {"name"};
String[] whereColumnCondition = {"="};
String[] whereColumnValue = {specimenForm.getSpecimenCollectionGroupName()};
List spCollGroupList = bizLogic.retrieve(SpecimenCollectionGroup.class.getName(), selectColumnName, whereColumnName,
whereColumnCondition, whereColumnValue, null);
//Logger.out.debug("after retrieval of spCollGroupList inside specimen action ^^^^^^^^^^^");
if (spCollGroupList!=null && !spCollGroupList.isEmpty())
{
// Object []spCollGroup = (Object[]) spCollGroupList
// .get(0);
long cpId = ((Long) spCollGroupList.get(0)).longValue();
String spClass = specimenForm.getClassName();
Logger.out.info("cpId :" + cpId + "spClass:" + spClass);
request.setAttribute(Constants.COLLECTION_PROTOCOL_ID, cpId + "");
if (virtuallyLocated != null && virtuallyLocated.equals("false"))
{
specimenForm.setVirtuallyLocated(false);
}
if(specimenForm.getStContSelection() == 2)
{
//Logger.out.debug("calling getAllocatedContaienrMapForSpecimen() function from NewSpecimenAction---");
sessionData = (SessionDataBean) request.getSession().getAttribute(Constants.SESSION_DATA);
containerMap = scbizLogic.getAllocatedContaienrMapForSpecimen(cpId, spClass, 0, exceedingMaxLimit, sessionData, true);
//Logger.out.debug("exceedingMaxLimit in action for Boolean:"+exceedingMaxLimit);
Logger.out.debug("finish ---calling getAllocatedContaienrMapForSpecimen() function from NewSpecimenAction---");
ActionErrors errors = (ActionErrors) request.getAttribute(Globals.ERROR_KEY);
if (containerMap.isEmpty())
{
if (errors == null || errors.size() == 0)
{
errors = new ActionErrors();
}
errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("storageposition.not.available"));
saveErrors(request, errors);
}
Logger.out.debug("calling checkForInitialValues() function from NewSpecimenAction---");
if (errors == null || errors.size() == 0)
{
initialValues = StorageContainerUtil.checkForInitialValues(containerMap);
}
else
{
String[] startingPoints = new String[3];
startingPoints[0] = specimenForm.getStorageContainer();
startingPoints[1] = specimenForm.getPositionDimensionOne();
startingPoints[2] = specimenForm.getPositionDimensionTwo() ;
initialValues = new Vector();
initialValues.add(startingPoints);
}
Logger.out.debug("finish ---calling checkForInitialValues() function from NewSpecimenAction---");
}
}
}
}
else
{
containerMap = new TreeMap();
String[] startingPoints = new String[]{"-1", "-1", "-1"};
Logger.out.info("--------------container:" + specimenForm.getStorageContainer());
Logger.out.info("--------------pos1:" + specimenForm.getPositionDimensionOne());
Logger.out.info("--------------pos2:" + specimenForm.getPositionDimensionTwo());
if (specimenForm.getStorageContainer() != null && !specimenForm.getStorageContainer().equals(""))
{
Integer id = new Integer(specimenForm.getStorageContainer());
String parentContainerName = "";
Object object=null ;
if(id>0)
{
object=bizLogic.retrieve(StorageContainer.class.getName(), new Long(specimenForm.getStorageContainer()));
}
if (object != null)
{
StorageContainer container = (StorageContainer) object;
parentContainerName = container.getName();
}
Integer pos1 = new Integer(specimenForm.getPositionDimensionOne());
Integer pos2 = new Integer(specimenForm.getPositionDimensionTwo());
List pos2List = new ArrayList();
pos2List.add(new NameValueBean(pos2, pos2));
Map pos1Map = new TreeMap();
pos1Map.put(new NameValueBean(pos1, pos1), pos2List);
containerMap.put(new NameValueBean(parentContainerName, id), pos1Map);
if (specimenForm.getStorageContainer() != null && !specimenForm.getStorageContainer().equals("-1"))
{
startingPoints[0] = specimenForm.getStorageContainer();
}
if (specimenForm.getPositionDimensionOne() != null && !specimenForm.getPositionDimensionOne().equals("-1"))
{
startingPoints[1] = specimenForm.getPositionDimensionOne();
}
if (specimenForm.getPositionDimensionTwo() != null && !specimenForm.getPositionDimensionTwo().equals("-1"))
{
startingPoints[2] = specimenForm.getPositionDimensionTwo();
}
}
initialValues = new Vector();
Logger.out.info("Starting points[0]" + startingPoints[0]);
Logger.out.info("Starting points[1]" + startingPoints[1]);
Logger.out.info("Starting points[2]" + startingPoints[2]);
initialValues.add(startingPoints);
if((specimenForm.getStContSelection() == Constants.RADIO_BUTTON_FOR_MAP)||specimenForm.getStContSelection()==2)
{
String[] selectColumnName = {"collectionProtocolRegistration.collectionProtocol.id"};
String[] whereColumnName = {"name"};
String[] whereColumnCondition = {"="};
String[] whereColumnValue = {specimenForm.getSpecimenCollectionGroupName()};
List spCollGroupList = bizLogic.retrieve(SpecimenCollectionGroup.class.getName(), selectColumnName, whereColumnName,
whereColumnCondition, whereColumnValue, null);
if (spCollGroupList!=null && !spCollGroupList.isEmpty())
{
long cpId = ((Long) spCollGroupList.get(0)).longValue();
String spClass = specimenForm.getClassName();
Logger.out.info("cpId :" + cpId + "spClass:" + spClass);
request.setAttribute(Constants.COLLECTION_PROTOCOL_ID, cpId + "");
if (virtuallyLocated != null && virtuallyLocated.equals("false"))
{
specimenForm.setVirtuallyLocated(false);
}
SessionDataBean sessionData = (SessionDataBean) request.getSession().getAttribute(Constants.SESSION_DATA);
sessionData = (SessionDataBean) request.getSession().getAttribute(Constants.SESSION_DATA);
containerMap = scbizLogic.getAllocatedContaienrMapForSpecimen(cpId, spClass, 0, exceedingMaxLimit, sessionData, true);
Logger.out.debug("finish ---calling getAllocatedContaienrMapForSpecimen() function from NewSpecimenAction---");
ActionErrors errors = (ActionErrors) request.getAttribute(Globals.ERROR_KEY);
if (containerMap.isEmpty())
{
if(specimenForm.getSelectedContainerName()==null || "".equals(specimenForm.getSelectedContainerName()))
{
if (errors == null || errors.size() == 0)
{
errors = new ActionErrors();
}
errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("storageposition.not.available"));
saveErrors(request, errors);
}
}
Logger.out.debug("calling checkForInitialValues() function from NewSpecimenAction---");
if (errors == null || errors.size() == 0)
{
initialValues = StorageContainerUtil.checkForInitialValues(containerMap);
}
else
{
String[] startingPoints1 = new String[3];
startingPoints1[0] = specimenForm.getStorageContainer();
startingPoints1[1] = specimenForm.getPositionDimensionOne();
startingPoints1[2] = specimenForm.getPositionDimensionTwo() ;
initialValues = new Vector();
initialValues.add(startingPoints1);
}
if(spClass!=null && specimenForm.getStContSelection() == Constants.RADIO_BUTTON_FOR_MAP)
{
String[] startingPoints2 = new String[]{"-1", "-1", "-1"};
initialValues = new ArrayList();
initialValues.add(startingPoints2);
request.setAttribute("initValues", initialValues);
}
}
}
}
request.setAttribute("initValues", initialValues);
request.setAttribute(Constants.EXCEEDS_MAX_LIMIT, exceedingMaxLimit);
request.setAttribute(Constants.AVAILABLE_CONTAINER_MAP, containerMap);
// -------------------------
//Falguni:Performance Enhancement.
Long specimenEntityId = null;
if (CatissueCoreCacheManager.getInstance().getObjectFromCache("specimenEntityId") != null)
{
specimenEntityId = (Long) CatissueCoreCacheManager.getInstance().getObjectFromCache("specimenEntityId");
}
else
{
specimenEntityId = AnnotationUtil.getEntityId(AnnotationConstants.ENTITY_NAME_SPECIMEN);
CatissueCoreCacheManager.getInstance().addObjectToCache("specimenEntityId",specimenEntityId);
}
request.setAttribute("specimenEntityId",specimenEntityId);
if (specimenForm.isVirtuallyLocated())
{
request.setAttribute("disabled", "true");
}
// set associated identified report id
Long reportId=getAssociatedIdentifiedReportId(specimenForm.getId());
if(reportId==null)
{
reportId=new Long(-1);
}
else if(Utility.isQuarantined(reportId))
{
reportId=new Long(-2);
}
HttpSession session =request.getSession();
session.setAttribute(Constants.IDENTIFIED_REPORT_ID, reportId);
//Logger.out.debug("End of specimen action");
request.setAttribute("createdDate", specimenForm.getCreatedDate());
request.setAttribute("specimenActivityStatus",
Constants.SPECIMEN_ACTIVITY_STATUS_VALUES);
return mapping.findForward(pageOf);
}
/**
* This method populates the list boxes for type, tissue site, tissue side
* and pathological status if this specimen is an aliquot.
* @param specimenForm object of NewSpecimenForm
* @param request object of HttpServletRequest
*/
private void populateListBoxes(NewSpecimenForm specimenForm, HttpServletRequest request)
{
//Setting the specimen type list
NameValueBean bean = new NameValueBean(specimenForm.getType(), specimenForm.getType());
List specimenTypeList = new ArrayList();
specimenTypeList.add(bean);
request.setAttribute(Constants.SPECIMEN_TYPE_LIST, specimenTypeList);
//Setting tissue site list
bean = new NameValueBean(specimenForm.getTissueSite(), specimenForm.getTissueSite());
List tissueSiteList = new ArrayList();
tissueSiteList.add(bean);
request.setAttribute(Constants.TISSUE_SITE_LIST, tissueSiteList);
//Setting tissue side list
bean = new NameValueBean(specimenForm.getTissueSide(), specimenForm.getTissueSide());
List tissueSideList = new ArrayList();
tissueSideList.add(bean);
request.setAttribute(Constants.TISSUE_SIDE_LIST, tissueSideList);
//Setting pathological status list
bean = new NameValueBean(specimenForm.getPathologicalStatus(), specimenForm.getPathologicalStatus());
List pathologicalStatusList = new ArrayList();
pathologicalStatusList.add(bean);
request.setAttribute(Constants.PATHOLOGICAL_STATUS_LIST, pathologicalStatusList);
}
// Mandar AutoEvents CollectionEvent start
/**
* This method sets all the collection event parameters for the SpecimenEventParameter pages
* @param request HttpServletRequest instance in which the data will be set.
* @param specimenForm NewSpecimenForm instance
* @throws Exception Throws Exception. Helps in handling exceptions at one common point.
*/
private void setCollectionEventRequestParameters(HttpServletRequest request, NewSpecimenForm specimenForm) throws Exception
{
//Gets the value of the operation parameter.
String operation = request.getParameter(Constants.OPERATION);
//Sets the operation attribute to be used in the Add/Edit FrozenEventParameters Page.
request.setAttribute(Constants.OPERATION, operation);
//Sets the minutesList attribute to be used in the Add/Edit FrozenEventParameters Page.
request.setAttribute(Constants.MINUTES_LIST, Constants.MINUTES_ARRAY);
//Sets the hourList attribute to be used in the Add/Edit FrozenEventParameters Page.
request.setAttribute(Constants.HOUR_LIST, Constants.HOUR_ARRAY);
// //The id of specimen of this event.
// String specimenId = request.getParameter(Constants.SPECIMEN_ID);
// request.setAttribute(Constants.SPECIMEN_ID, specimenId);
// Logger.out.debug("\t\t SpecimenEventParametersAction************************************ : "+specimenId );
//
UserBizLogic userBizLogic = (UserBizLogic) BizLogicFactory.getInstance().getBizLogic(Constants.USER_FORM_ID);
Collection userCollection = userBizLogic.getUsers(operation);
request.setAttribute(Constants.USERLIST, userCollection);
SessionDataBean sessionData = getSessionData(request);
if (sessionData != null)
{
String user = sessionData.getLastName() + ", " + sessionData.getFirstName();
long collectionEventUserId = EventsUtil.getIdFromCollection(userCollection, user);
if(specimenForm.getCollectionEventUserId() == 0)
{
specimenForm.setCollectionEventUserId(collectionEventUserId);
}
if(specimenForm.getReceivedEventUserId() == 0)
{
specimenForm.setReceivedEventUserId(collectionEventUserId);
}
}
/**
* Name : Virender Mehta
* Reviewer: Sachin Lale
* Bug ID: defaultValueConfiguration_BugID
* Patch ID:defaultValueConfiguration_BugID_11
* See also:defaultValueConfiguration_BugID_9,10,11
* Description: Configuration for default value for Collection Procedure, Container and Quality
*/
// set the procedure lists
List procedureList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_COLLECTION_PROCEDURE, null);
request.setAttribute(Constants.PROCEDURE_LIST, procedureList);
//Bug- setting the default collection event procedure
if (specimenForm.getCollectionEventCollectionProcedure() == null)
{
specimenForm.setCollectionEventCollectionProcedure((String)DefaultValueManager.getDefaultValue(Constants.DEFAULT_COLLECTION_PROCEDURE));
}
// set the container lists
List containerList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_CONTAINER, null);
request.setAttribute(Constants.CONTAINER_LIST, containerList);
//Bug- setting the default collection event container
if (specimenForm.getCollectionEventContainer() == null)
{
specimenForm.setCollectionEventContainer((String)DefaultValueManager.getDefaultValue(Constants.DEFAULT_CONTAINER));
}
}
// Mandar AutoEvents CollectionEvent end
// Mandar Autoevents ReceivedEvent start
/**
* This method sets all the received event parameters for the SpecimenEventParameter pages
* @param request HttpServletRequest instance in which the data will be set.
* @param specimenForm NewSpecimenForm instance
* @throws Exception Throws Exception. Helps in handling exceptions at one common point.
*/
private void setReceivedEventRequestParameters(HttpServletRequest request, NewSpecimenForm specimenForm) throws Exception
{
List qualityList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_RECEIVED_QUALITY, null);
request.setAttribute(Constants.RECEIVED_QUALITY_LIST, qualityList);
//Bug- setting the default recieved event quality
if (specimenForm.getReceivedEventReceivedQuality() == null)
{
specimenForm.setReceivedEventReceivedQuality((String)DefaultValueManager.getDefaultValue(Constants.DEFAULT_RECEIVED_QUALITY));
}
}
/**
* @param specimenForm instance of NewSpecimenForm
*/
private void setDateParameters(NewSpecimenForm specimenForm)
{
// set the current Date and Time for the event.
Calendar cal = Calendar.getInstance();
//Collection Event fields
if (specimenForm.getCollectionEventdateOfEvent() == null)
{
specimenForm.setCollectionEventdateOfEvent(Utility.parseDateToString(cal.getTime(), Variables.dateFormat));
}
if (specimenForm.getCollectionEventTimeInHours() == null)
{
specimenForm.setCollectionEventTimeInHours(Integer.toString(cal.get(Calendar.HOUR_OF_DAY)));
}
if (specimenForm.getCollectionEventTimeInMinutes() == null)
{
specimenForm.setCollectionEventTimeInMinutes(Integer.toString(cal.get(Calendar.MINUTE)));
}
//ReceivedEvent Fields
if (specimenForm.getReceivedEventDateOfEvent() == null)
{
specimenForm.setReceivedEventDateOfEvent(Utility.parseDateToString(cal.getTime(), Variables.dateFormat));
}
if (specimenForm.getReceivedEventTimeInHours() == null)
{
specimenForm.setReceivedEventTimeInHours(Integer.toString(cal.get(Calendar.HOUR_OF_DAY)));
}
if (specimenForm.getReceivedEventTimeInMinutes() == null)
{
specimenForm.setReceivedEventTimeInMinutes(Integer.toString(cal.get(Calendar.MINUTE)));
}
}
/**
* @param specimenForm instance of NewSpecimenForm
*/
private void clearCollectionEvent(NewSpecimenForm specimenForm)
{
specimenForm.setCollectionEventCollectionProcedure("");
specimenForm.setCollectionEventComments("");
specimenForm.setCollectionEventContainer("");
specimenForm.setCollectionEventdateOfEvent("");
specimenForm.setCollectionEventTimeInHours("");
specimenForm.setCollectionEventTimeInMinutes("");
specimenForm.setCollectionEventUserId(-1);
}
/**
* @param specimenForm instance of NewSpecimenForm
*/
private void clearReceivedEvent(NewSpecimenForm specimenForm)
{
specimenForm.setReceivedEventComments("");
specimenForm.setReceivedEventDateOfEvent("");
specimenForm.setReceivedEventReceivedQuality("");
specimenForm.setReceivedEventTimeInHours("");
specimenForm.setReceivedEventTimeInMinutes("");
specimenForm.setReceivedEventUserId(-1);
}
//Consent Tracking (Virender Mehta)
/**
* Prepare Map for Consent tiers
* @param participantResponseList This list will be iterated to map to populate participant Response status.
* @return tempMap
*/
private Map prepareConsentMap(List participantResponseList,Collection consentResponse)
{
Map tempMap = new HashMap();
Long consentTierID;
Long consentID;
if(participantResponseList!=null||consentResponse!=null)
{
int i = 0;
Iterator consentResponseCollectionIter = participantResponseList.iterator();
while(consentResponseCollectionIter.hasNext())
{
ConsentTierResponse consentTierResponse = (ConsentTierResponse)consentResponseCollectionIter.next();
Iterator statusCollectionIter = consentResponse.iterator();
consentTierID=consentTierResponse.getConsentTier().getId();
while(statusCollectionIter.hasNext())
{
ConsentTierStatus consentTierstatus=(ConsentTierStatus)statusCollectionIter.next();
consentID=consentTierstatus.getConsentTier().getId();
if(consentTierID.longValue()==consentID.longValue())
{
ConsentTier consent = consentTierResponse.getConsentTier();
String idKey="ConsentBean:"+i+"_consentTierID";
String statementKey="ConsentBean:"+i+"_statement";
String responseKey="ConsentBean:"+i+"_participantResponse";
String participantResponceIdKey="ConsentBean:"+i+"_participantResponseID";
String scgResponsekey = "ConsentBean:"+i+"_specimenCollectionGroupLevelResponse";
String scgResponseIDkey ="ConsentBean:"+i+"_specimenCollectionGroupLevelResponseID";
String specimenResponsekey = "ConsentBean:"+i+"_specimenLevelResponse";
String specimenResponseIDkey ="ConsentBean:"+i+"_specimenLevelResponseID";
tempMap.put(idKey, consent.getId());
tempMap.put(statementKey,consent.getStatement());
tempMap.put(responseKey,consentTierResponse.getResponse());
tempMap.put(participantResponceIdKey,consentTierResponse.getId());
tempMap.put(scgResponsekey, consentTierstatus.getStatus());
tempMap.put(scgResponseIDkey, consentTierstatus.getId());
tempMap.put(specimenResponsekey,consentTierstatus.getStatus());
tempMap.put(specimenResponseIDkey,null);
i++;
break;
}
}
}
return tempMap;
}
else
{
return null;
}
}
//Consent Tracking (Virender Mehta)
/**
* @param specimenForm instance of NewSpecimenForm
* @param specimenCollectionGroupId String containing specimen collection group Id
* @param specimenCollectionGroupName String containing specimen collection group name
*/
private void setFormValues(NewSpecimenForm specimenForm, String specimenCollectionGroupId,
String specimenCollectionGroupName)
{
specimenForm.setSpecimenCollectionGroupId(specimenCollectionGroupId);
specimenForm.setSpecimenCollectionGroupName(specimenCollectionGroupName);
specimenForm.setVirtuallyLocated(true);
specimenForm.setParentSpecimenId("");
specimenForm.setLabel("");
specimenForm.setBarcode("");
specimenForm.setPositionInStorageContainer("");
specimenForm.setPositionDimensionOne("");
specimenForm.setPositionDimensionTwo("");
specimenForm.setStorageContainer("");
}
/**
* Patch ID: Bug#3184_2
*/
/**
* This method initializes the List of SpecimenCollectionGroup in the system and sets the list as an
* attribute in the request.
* @param bizLogic NewSpecimenBizLogic to fetch the SpecimenCollectionGroup list
* @param request HttpServletRequest in which the list is set as an attribute
* @throws DAOException on failure to initialize the list
*/
/**For Migration Start**/
/* private void initializeAndSetSpecimenCollectionGroupIdList(NewSpecimenBizLogic bizLogic, HttpServletRequest request) throws DAOException
{
String sourceObjectName = SpecimenCollectionGroup.class.getName();
String[] displayNameFields = {"name"};
String valueField = Constants.SYSTEM_IDENTIFIER;
List specimenCollectionGroupList = bizLogic.getList(sourceObjectName, displayNameFields, valueField, true);
request.setAttribute(Constants.SPECIMEN_COLLECTION_GROUP_LIST, specimenCollectionGroupList);
}
*/
/**
* This method generates Map of SpecimenClass and the List of the corresponding Types.
* @param tempMap a temporary Map for avoiding duplication of values.
* @param subTypeMap the Map of SpecimenClass and the List of the corresponding Types
* @param specimenClass Class of Speciment
* @param specimenType Type of Specimen
*/
private void populateSpecimenTypeLists(Map<String, String> tempMap, Map<String, List<NameValueBean>> subTypeMap,
String specimenClass, String specimenType)
{
List<NameValueBean> tempList = subTypeMap.get(specimenClass);
if (tempList == null)
{
tempList = new ArrayList<NameValueBean>();
tempList.add(new NameValueBean(Constants.SELECT_OPTION, "-1"));
tempList.add(new NameValueBean(specimenType, specimenType));
subTypeMap.put(specimenClass, tempList);
tempMap.put(specimenClass + specimenType + Constants.SPECIMEN_TYPE, specimenType);
}
else
{
tempList = subTypeMap.get(specimenClass);
tempList.add(new NameValueBean(specimenType, specimenType));
Collections.sort(tempList);
subTypeMap.put(specimenClass, tempList);
tempMap.put(specimenClass + specimenType + Constants.SPECIMEN_TYPE, specimenType);
}
}
/**
* This method populates all the values form the system for the respective lists.
* @param specimenForm NewSpecimenForm to set the List of TissueSite and PathologicalStatus
* @param specimenClassList List of Specimen Class
* @param specimenTypeList List of Specimen Type
* @param tissueSiteList List of Tissue Site
* @param tissueSideList List of Tissue Side
* @param pathologicalStatusList List of Pathological Status
* @param subTypeMap Map of the Class and their corresponding Types
* @throws DAOException on failure to populate values from the system
*/private void populateAllLists(NewSpecimenForm specimenForm, List<NameValueBean> specimenClassList, List<NameValueBean> specimenTypeList,
List<NameValueBean> tissueSiteList, List<NameValueBean> tissueSideList, List<NameValueBean> pathologicalStatusList,
Map<String, List<NameValueBean>> subTypeMap)
throws DAOException
{
// Getting the specimen type list
specimenTypeList = Utility.getListFromCDE(Constants.CDE_NAME_SPECIMEN_TYPE);
/**
* Name : Virender Mehta
* Reviewer: Sachin Lale
* Bug ID: TissueSiteCombo_BugID
* Patch ID:TissueSiteCombo_BugID_1
* See also:TissueSiteCombo_BugID_2
* Description: Getting TissueList with only Leaf node
*/
tissueSiteList.addAll(Utility.tissueSiteList());
//Getting tissue side list
tissueSideList.addAll(Utility.getListFromCDE(Constants.CDE_NAME_TISSUE_SIDE));
//Getting pathological status list
pathologicalStatusList.addAll(Utility.getListFromCDE(Constants.CDE_NAME_PATHOLOGICAL_STATUS));
// get the Specimen class and type from the cde
CDE specimenClassCDE = CDEManager.getCDEManager().getCDE(Constants.CDE_NAME_SPECIMEN_CLASS);
Set<PermissibleValue> setPV = specimenClassCDE.getPermissibleValues();
for (PermissibleValue pv : setPV)
{
String tmpStr = pv.getValue();
Logger.out.debug(tmpStr);
specimenClassList.add(new NameValueBean(tmpStr, tmpStr));
List<NameValueBean> innerList = new ArrayList<NameValueBean>();
innerList.add(new NameValueBean(Constants.SELECT_OPTION, "-1"));
Set<PermissibleValue> list1 = pv.getSubPermissibleValues();
Logger.out.debug("list1 " + list1);
for (PermissibleValue pv1 : list1)
{
// set specimen type
String tmpInnerStr = pv1.getValue();
Logger.out.debug("\t\t" + tmpInnerStr);
innerList.add(new NameValueBean(tmpInnerStr, tmpInnerStr));
}
Collections.sort(innerList);
subTypeMap.put(tmpStr, innerList);
} // class and values set
Logger.out.debug("\n\n\n\n**********MAP DATA************\n");
// Setting the default values
if (specimenForm.getTissueSite() == null)
{
specimenForm.setTissueSite((String)DefaultValueManager.getDefaultValue(Constants.DEFAULT_TISSUE_SITE));
}
if (specimenForm.getPathologicalStatus() == null)
{
specimenForm.setPathologicalStatus((String)DefaultValueManager.getDefaultValue(Constants.DEFAULT_PATHOLOGICAL_STATUS));
}
Utility.setDefaultPrinterTypeLocation(specimenForm);
}
/**
* Name : Ashish Gupta
* Reviewer Name : Sachin Lale
* Bug ID: 2741
* Patch ID: 2741_13
* Description: Method to propagate Events to multiple specimens from scg
*/
/**
* @param specimenCollectionGroupForm instance of SpecimenCollectionGroupForm
* @param specimenForm instance of NewSpecimenForm
*/
/*public static void populateEventsFromScg1(SpecimenCollectionGroupForm specimenCollectionGroupForm,NewSpecimenForm specimenForm)
{
specimenForm.setCollectionEventUserId(specimenCollectionGroupForm.getCollectionEventUserId());
specimenForm.setReceivedEventUserId(specimenCollectionGroupForm.getReceivedEventUserId());
specimenForm.setCollectionEventCollectionProcedure("Not Specified");
specimenForm.setCollectionEventContainer("Not Specified");
specimenForm.setReceivedEventReceivedQuality("Not Specified");
specimenForm.setCollectionEventdateOfEvent(specimenCollectionGroupForm.getCollectionEventdateOfEvent());
specimenForm.setCollectionEventTimeInHours(specimenCollectionGroupForm.getCollectionEventTimeInHours());
specimenForm.setCollectionEventTimeInMinutes(specimenCollectionGroupForm.getCollectionEventTimeInMinutes());
specimenForm.setReceivedEventDateOfEvent(specimenCollectionGroupForm.getReceivedEventDateOfEvent());
specimenForm.setReceivedEventTimeInHours(specimenCollectionGroupForm.getReceivedEventTimeInHours());
specimenForm.setReceivedEventTimeInMinutes(specimenCollectionGroupForm.getReceivedEventTimeInMinutes());
}*/
public static void populateEventsFromScg(SpecimenCollectionGroup specimenCollectionGroup,NewSpecimenForm specimenForm)
{
Calendar calender = Calendar.getInstance();
Collection scgEventColl = specimenCollectionGroup.getSpecimenEventParametersCollection();
if(scgEventColl != null && !scgEventColl.isEmpty())
{
Iterator itr = scgEventColl.iterator();
while(itr.hasNext())
{
Object specimenEventParameter = itr.next();
if(specimenEventParameter instanceof CollectionEventParameters)
{
CollectionEventParameters scgCollEventParam = (CollectionEventParameters) specimenEventParameter;
calender.setTime(scgCollEventParam.getTimestamp());
specimenForm.setCollectionEventUserId(scgCollEventParam.getUser().getId().longValue());
specimenForm.setCollectionEventCollectionProcedure(scgCollEventParam.getCollectionProcedure());
specimenForm.setCollectionEventContainer(scgCollEventParam.getContainer());
specimenForm.setCollectionEventdateOfEvent(Utility.parseDateToString(scgCollEventParam.getTimestamp(),Variables.dateFormat));
specimenForm.setCollectionEventTimeInHours(Utility.toString(Integer.toString(calender.get(Calendar.HOUR_OF_DAY))));
specimenForm.setCollectionEventTimeInMinutes(Utility.toString(Integer.toString(calender.get(Calendar.MINUTE))));
}
if(specimenEventParameter instanceof ReceivedEventParameters)
{
ReceivedEventParameters scgReceivedEventParam = (ReceivedEventParameters) specimenEventParameter;
calender.setTime(scgReceivedEventParam.getTimestamp());
specimenForm.setReceivedEventUserId(scgReceivedEventParam.getUser().getId().longValue());
specimenForm.setReceivedEventReceivedQuality(scgReceivedEventParam.getReceivedQuality());
specimenForm.setReceivedEventDateOfEvent(Utility.parseDateToString(scgReceivedEventParam.getTimestamp(),Variables.dateFormat));
specimenForm.setReceivedEventTimeInHours(Utility.toString(Integer.toString(calender.get(Calendar.HOUR_OF_DAY))));
specimenForm.setReceivedEventTimeInMinutes(Utility.toString(Integer.toString(calender.get(Calendar.MINUTE))));
}
}
}
/* specimenForm.setCollectionEventUserId(specimenCollectionGroupForm.getCollectionEventUserId());
specimenForm.setReceivedEventUserId(specimenCollectionGroupForm.getReceivedEventUserId());
specimenForm.setCollectionEventCollectionProcedure("Not Specified");
specimenForm.setCollectionEventContainer("Not Specified");
specimenForm.setReceivedEventReceivedQuality("Not Specified");
specimenForm.setCollectionEventdateOfEvent(specimenCollectionGroupForm.getCollectionEventdateOfEvent());
specimenForm.setCollectionEventTimeInHours(specimenCollectionGroupForm.getCollectionEventTimeInHours());
specimenForm.setCollectionEventTimeInMinutes(specimenCollectionGroupForm.getCollectionEventTimeInMinutes());
specimenForm.setReceivedEventDateOfEvent(specimenCollectionGroupForm.getReceivedEventDateOfEvent());
specimenForm.setReceivedEventTimeInHours(specimenCollectionGroupForm.getReceivedEventTimeInHours());
specimenForm.setReceivedEventTimeInMinutes(specimenCollectionGroupForm.getReceivedEventTimeInMinutes()); */
}
/**
* This function adds the columns to the List
* @return columnList
*/
public List columnNames()
{
List columnList = new ArrayList();
columnList.add(Constants.LABLE);
columnList.add(Constants.TYPE);
columnList.add(Constants.STORAGE_CONTAINER_LOCATION);
columnList.add(Constants.CLASS_NAME);
return columnList;
}
private Long getAssociatedIdentifiedReportId(Long specimenId) throws DAOException, ClassNotFoundException
{
String hqlString="select scg.identifiedSurgicalPathologyReport.id " +
" from edu.wustl.catissuecore.domain.SpecimenCollectionGroup as scg, " +
" edu.wustl.catissuecore.domain.Specimen as specimen" +
" where specimen.id = " + specimenId +
" and specimen.id in elements(scg.specimenCollection)";
List reportIDList=Utility.executeQuery(hqlString);
if(reportIDList!=null && reportIDList.size()>0)
{
return ((Long)reportIDList.get(0));
}
return null;
}
/* (non-Javadoc)
* @see edu.wustl.common.action.SecureAction#getObjectId(edu.wustl.common.actionForm.AbstractActionForm)
*/
@Override
protected String getObjectId(AbstractActionForm form)
{
NewSpecimenForm specimenForm = (NewSpecimenForm)form;
SpecimenCollectionGroup specimenCollectionGroup = null;
if(specimenForm.getSpecimenCollectionGroupId() != null || specimenForm.getSpecimenCollectionGroupId() != "")
{
try
{
specimenCollectionGroup= Utility.getSCGObj(specimenForm.getSpecimenCollectionGroupId());
CollectionProtocolRegistration cpr = specimenCollectionGroup.getCollectionProtocolRegistration();
if (cpr!= null)
{
CollectionProtocol cp = cpr.getCollectionProtocol();
return Constants.COLLECTION_PROTOCOL_CLASS_NAME +"_"+cp.getId();
}
}
catch (DAOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
} | WEB-INF/src/edu/wustl/catissuecore/action/NewSpecimenAction.java | /**
* <p>Title: NewSpecimenAction Class>
* <p>Description: NewSpecimenAction initializes the fields in the New Specimen page.</p>
* Copyright: Copyright (c) year
* Company: Washington University, School of Medicine, St. Louis.
* @author Aniruddha Phadnis
* @version 1.00
*/
package edu.wustl.catissuecore.action;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.Vector;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import edu.wustl.catissuecore.action.annotations.AnnotationConstants;
import edu.wustl.catissuecore.actionForm.NewSpecimenForm;
import edu.wustl.catissuecore.actionForm.SpecimenCollectionGroupForm;
import edu.wustl.catissuecore.bizlogic.AnnotationUtil;
import edu.wustl.catissuecore.bizlogic.BizLogicFactory;
import edu.wustl.catissuecore.bizlogic.NewSpecimenBizLogic;
import edu.wustl.catissuecore.bizlogic.StorageContainerBizLogic;
import edu.wustl.catissuecore.bizlogic.UserBizLogic;
import edu.wustl.catissuecore.client.CaCoreAppServicesDelegator;
import edu.wustl.catissuecore.domain.Biohazard;
import edu.wustl.catissuecore.domain.CollectionEventParameters;
import edu.wustl.catissuecore.domain.CollectionProtocol;
import edu.wustl.catissuecore.domain.CollectionProtocolRegistration;
import edu.wustl.catissuecore.domain.ConsentTier;
import edu.wustl.catissuecore.domain.ConsentTierResponse;
import edu.wustl.catissuecore.domain.ConsentTierStatus;
import edu.wustl.catissuecore.domain.ReceivedEventParameters;
import edu.wustl.catissuecore.domain.Specimen;
import edu.wustl.catissuecore.domain.SpecimenCollectionGroup;
import edu.wustl.catissuecore.domain.StorageContainer;
import edu.wustl.catissuecore.domain.User;
import edu.wustl.catissuecore.util.CatissueCoreCacheManager;
import edu.wustl.catissuecore.util.ConsentUtil;
import edu.wustl.catissuecore.util.EventsUtil;
import edu.wustl.catissuecore.util.StorageContainerUtil;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.catissuecore.util.global.DefaultValueManager;
import edu.wustl.catissuecore.util.global.Utility;
import edu.wustl.catissuecore.util.global.Variables;
import edu.wustl.common.action.SecureAction;
import edu.wustl.common.actionForm.AbstractActionForm;
import edu.wustl.common.beans.NameValueBean;
import edu.wustl.common.beans.SessionDataBean;
import edu.wustl.common.bizlogic.IBizLogic;
import edu.wustl.common.cde.CDE;
import edu.wustl.common.cde.CDEManager;
import edu.wustl.common.cde.PermissibleValue;
import edu.wustl.common.util.MapDataParser;
import edu.wustl.common.util.dbManager.DAOException;
import edu.wustl.common.util.logger.Logger;
/**
* NewSpecimenAction initializes the fields in the New Specimen page.
* @author aniruddha_phadnis
*/
public class NewSpecimenAction extends SecureAction
{
/**
* Overrides the execute method of Action class.
* @param mapping object of ActionMapping
* @param form object of ActionForm
* @param request object of HttpServletRequest
* @param response object of HttpServletResponse
* @throws Exception generic exception
*/
public ActionForward executeSecureAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception
{
//Logger.out.debug("NewSpecimenAction start@@@@@@@@@");
NewSpecimenForm specimenForm = (NewSpecimenForm) form;
List<NameValueBean> storagePositionList = Utility.getStoragePositionTypeList();
request.setAttribute("storageList", storagePositionList);
String pageOf = request.getParameter(Constants.PAGEOF);
String forwardPage=specimenForm.getForwardTo();
if(forwardPage.equals(Constants.PAGEOF_SPECIMEN_COLLECTION_REQUIREMENT_GROUP))
{
pageOf=forwardPage;
request.setAttribute(Constants.STATUS_MESSAGE_KEY, "errors.specimencollectionrequirementgroupedit");
return mapping.findForward(pageOf);
}
IBizLogic bizLogicObj = BizLogicFactory.getInstance().getBizLogic(Constants.DEFAULT_BIZ_LOGIC);
NewSpecimenBizLogic bizLogic = (NewSpecimenBizLogic) BizLogicFactory.getInstance().getBizLogic(Constants.NEW_SPECIMEN_FORM_ID);
String treeRefresh = request.getParameter("refresh");
request.setAttribute("refresh",treeRefresh);
//Gets the value of the operation parameter.
String operation = (String) request.getParameter(Constants.OPERATION);
//boolean to indicate whether the suitable containers to be shown in dropdown
//is exceeding the max limit.
String exceedingMaxLimit = new String();
//Sets the operation attribute to be used in the Edit/View Specimen Page in Advance Search Object View.
request.setAttribute(Constants.OPERATION, operation);
if (operation != null && operation.equalsIgnoreCase(Constants.ADD))
{
specimenForm.setId(0);
}
String virtuallyLocated = request.getParameter("virtualLocated");
if (virtuallyLocated != null && virtuallyLocated.equals("true"))
{
specimenForm.setVirtuallyLocated(true);
}
//Name of button clicked
String button = request.getParameter("button");
Map map = null;
if (button != null)
{
if (button.equals("deleteExId"))
{
List key = new ArrayList();
key.add("ExternalIdentifier:i_name");
key.add("ExternalIdentifier:i_value");
//Gets the map from ActionForm
map = specimenForm.getExternalIdentifier();
MapDataParser.deleteRow(key, map, request.getParameter("status"));
}
else
{
List key = new ArrayList();
key.add("Biohazard:i_type");
key.add("Biohazard:i_id");
//Gets the map from ActionForm
map = specimenForm.getBiohazard();
MapDataParser.deleteRow(key, map, request.getParameter("status"));
}
}
// ************* ForwardTo implementation *************
HashMap forwardToHashMap = (HashMap) request.getAttribute("forwardToHashMap");
String specimenCollectionGroupName = "";
if (forwardToHashMap != null)
{
String specimenCollectionGroupId = (String) forwardToHashMap.get("specimenCollectionGroupId");
/**For Migration Start**/
specimenCollectionGroupName = (String) forwardToHashMap.get("specimenCollectionGroupName");
Logger.out.debug("specimenCollectionGroupName found in forwardToHashMap========>>>>>>" + specimenCollectionGroupName);
specimenForm.setSpecimenCollectionGroupName(specimenCollectionGroupName);
/**For Migration End**/
Logger.out.debug("SpecimenCollectionGroupId found in forwardToHashMap========>>>>>>" + specimenCollectionGroupId);
if (specimenCollectionGroupId != null)
{
/**
* Retaining properties of specimen when more is clicked.
* Bug no -- 2623
*/
//Populating the specimen collection group name in the specimen page
setFormValues(specimenForm, specimenCollectionGroupId,specimenCollectionGroupName);
}
}
//************* ForwardTo implementation *************
//Consent Tracking (Virender Mehta) - Start
//Adding name,value pair in NameValueBean
String tabSelected = request.getParameter(Constants.SELECTED_TAB);
if(tabSelected!=null)
{
request.setAttribute(Constants.SELECTED_TAB,tabSelected);
}
String scg_id=String.valueOf(specimenForm.getSpecimenCollectionGroupId());
SpecimenCollectionGroup specimenCollectionGroup= Utility.getSCGObj(scg_id);
//PHI Data
String initialURLValue="";
String initialWitnessValue="";
String initialSignedConsentDateValue="";
//Lazy - specimenCollectionGroup.getCollectionProtocolRegistration()
CollectionProtocolRegistration collectionProtocolRegistration = specimenCollectionGroup.getCollectionProtocolRegistration();
if(collectionProtocolRegistration ==null || collectionProtocolRegistration.getSignedConsentDocumentURL()==null)
{
initialURLValue=Constants.NULL;
}
User consentWitness=null;
if(collectionProtocolRegistration.getId()!= null)
{
consentWitness = (User)bizLogicObj.retrieveAttribute(CollectionProtocolRegistration.class.getName(),collectionProtocolRegistration.getId(), "consentWitness");
}
//User consentWitness= collectionProtocolRegistration.getConsentWitness();
//Resolved lazy
if(consentWitness==null)
{
initialWitnessValue=Constants.NULL;
}
if(collectionProtocolRegistration.getConsentSignatureDate()==null)
{
initialSignedConsentDateValue=Constants.NULL;
}
List cprObjectList=new ArrayList();
cprObjectList.add(collectionProtocolRegistration);
SessionDataBean sessionDataBean=(SessionDataBean)request.getSession().getAttribute(Constants.SESSION_DATA);
CaCoreAppServicesDelegator caCoreAppServicesDelegator = new CaCoreAppServicesDelegator();
String userName = Utility.toString(sessionDataBean.getUserName());
List collProtObject = caCoreAppServicesDelegator.delegateSearchFilter(userName,cprObjectList);
CollectionProtocolRegistration cprObject =null;
cprObject = collectionProtocolRegistration;//(CollectionProtocolRegistration)collProtObject.get(0);
String witnessName="";
String getConsentDate="";
String getSignedConsentURL="";
User witness = cprObject.getConsentWitness();
if(witness==null)
{
if(initialWitnessValue.equals(Constants.NULL))
{
witnessName="";
}
else
{
witnessName=Constants.HASHED_OUT;
}
specimenForm.setWitnessName(witnessName);
}
else
{
witness = (User)bizLogicObj.retrieveAttribute(CollectionProtocolRegistration.class.getName(),cprObject.getId(), "consentWitness");
String witnessFullName = witness.getLastName()+", "+witness.getFirstName();
specimenForm.setWitnessName(witnessFullName);
}
if(cprObject.getConsentSignatureDate()==null)
{
if(initialSignedConsentDateValue.equals(Constants.NULL))
{
getConsentDate="";
}
else
{
getConsentDate=Constants.HASHED_OUT;
}
}
else
{
getConsentDate=Utility.parseDateToString(cprObject.getConsentSignatureDate(), Variables.dateFormat);
}
if(cprObject.getSignedConsentDocumentURL()==null)
{
if(initialURLValue.equals(Constants.NULL))
{
getSignedConsentURL="";
}
else
{
getSignedConsentURL=Constants.HASHED_OUT;
}
}
else
{
getSignedConsentURL=Utility.toString(cprObject.getSignedConsentDocumentURL());
}
specimenForm.setConsentDate(getConsentDate);
specimenForm.setSignedConsentUrl(getSignedConsentURL);
Collection consentTierRespCollection = (Collection)bizLogicObj.retrieveAttribute(CollectionProtocolRegistration.class.getName(),cprObject.getId(), "elements(consentTierResponseCollection)" );
//Lazy Resolved --- cprObject.getConsentTierResponseCollection()
Set participantResponseSet =(Set)consentTierRespCollection;
List participantResponseList;
if (participantResponseSet != null)
{
participantResponseList = new ArrayList(participantResponseSet);
}
else
{
participantResponseList = new ArrayList();
}
if(operation.equalsIgnoreCase(Constants.ADD))
{
ActionErrors errors = (ActionErrors) request.getAttribute(Globals.ERROR_KEY);
if(errors == null)
{
String scgDropDown = request.getParameter(Constants.SCG_DROPDOWN);
if(scgDropDown==null||scgDropDown.equalsIgnoreCase(Constants.TRUE))
{
Collection consentResponseStatuslevel=(Collection)bizLogicObj.retrieveAttribute(SpecimenCollectionGroup.class.getName(),specimenCollectionGroup.getId(), "elements(consentTierStatusCollection)");
Map tempMap=prepareConsentMap(participantResponseList,consentResponseStatuslevel);
specimenForm.setConsentResponseForSpecimenValues(tempMap);
}
}
specimenForm.setConsentTierCounter(participantResponseList.size());
}
else
{
String specimenID = null;
specimenID = String.valueOf(specimenForm.getId());
//List added for grid
List specimenDetails= new ArrayList();
SessionDataBean sessionData = (SessionDataBean) request.getSession().getAttribute(Constants.SESSION_DATA);
Specimen specimen = bizLogic.getSpecimen(specimenID,specimenDetails, sessionData);
//Added by Falguni=To set Specimen label in Form.
specimenForm.setCreatedDate(Utility.parseDateToString(specimen.getCreatedOn(), Variables.dateFormat));
specimenForm.setLabel(specimen.getLabel());
specimenForm.setBarcode(specimen.getBarcode());
List columnList=columnNames();
String consentResponseHql ="select elements(scg.collectionProtocolRegistration.consentTierResponseCollection)"+
" from edu.wustl.catissuecore.domain.SpecimenCollectionGroup as scg," +
" edu.wustl.catissuecore.domain.Specimen as spec " +
" where spec.specimenCollectionGroup.id=scg.id and spec.id="+ specimen.getId();
Collection consentResponse = Utility.executeQuery(consentResponseHql);
Collection consentResponseStatuslevel=(Collection)bizLogicObj.retrieveAttribute(Specimen.class.getName(),specimen.getId(), "elements(consentTierStatusCollection)");
String specimenResponse = "_specimenLevelResponse";
String specimenResponseId = "_specimenLevelResponseID";
Map tempMap=ConsentUtil.prepareSCGResponseMap(consentResponseStatuslevel, consentResponse,specimenResponse,specimenResponseId);
specimenForm.setConsentResponseForSpecimenValues(tempMap);
specimenForm.setConsentTierCounter(participantResponseList.size()) ;
HttpSession session =request.getSession();
request.setAttribute("showContainer", specimen.getCollectionStatus());
session.setAttribute(Constants.SPECIMEN_LIST,specimenDetails);
session.setAttribute(Constants.COLUMNLIST,columnList);
}
List specimenResponseList = new ArrayList();
specimenResponseList=Utility.responceList(operation);
request.setAttribute(Constants.SPECIMEN_RESPONSELIST, specimenResponseList);
//Consent Tracking (Virender Mehta) - Stop
pageOf = request.getParameter(Constants.PAGEOF);
request.setAttribute(Constants.PAGEOF, pageOf);
//Sets the activityStatusList attribute to be used in the Site Add/Edit Page.
request.setAttribute(Constants.ACTIVITYSTATUSLIST, Constants.ACTIVITY_STATUS_VALUES);
//Sets the collectionStatusList attribute to be used in the Site Add/Edit Page.
request.setAttribute(Constants.COLLECTIONSTATUSLIST, Constants.SPECIMEN_COLLECTION_STATUS_VALUES);
//NewSpecimenBizLogic bizLogic = (NewSpecimenBizLogic) BizLogicFactory.getInstance().getBizLogic(Constants.NEW_SPECIMEN_FORM_ID);
if (specimenForm.isParentPresent())//If parent specimen is present then
{
// String[] fields = {Constants.SYSTEM_LABEL};
// List parentSpecimenList = bizLogic.getList(Specimen.class.getName(), fields, Constants.SYSTEM_IDENTIFIER, true);
// request.setAttribute(Constants.PARENT_SPECIMEN_ID_LIST, parentSpecimenList);
}
String[] bhIdArray = {"-1"};
String[] bhTypeArray = {Constants.SELECT_OPTION};
String[] bhNameArray = {Constants.SELECT_OPTION};
String[] selectColNames = {Constants.SYSTEM_IDENTIFIER, "name", "type"};
List biohazardList = bizLogic.retrieve(Biohazard.class.getName(), selectColNames);
Iterator iterator = biohazardList.iterator();
//Creating & setting the biohazard name, id & type list
if (biohazardList != null && !biohazardList.isEmpty())
{
bhIdArray = new String[biohazardList.size() + 1];
bhTypeArray = new String[biohazardList.size() + 1];
bhNameArray = new String[biohazardList.size() + 1];
bhIdArray[0] = "-1";
bhTypeArray[0] = "";
bhNameArray[0] = Constants.SELECT_OPTION;
int i = 1;
while (iterator.hasNext())
{
Object[] hazard = (Object[]) iterator.next();
bhIdArray[i] = String.valueOf(hazard[0]);
bhNameArray[i] = (String) hazard[1];
bhTypeArray[i] = (String) hazard[2];
i++;
}
}
request.setAttribute(Constants.BIOHAZARD_NAME_LIST, bhNameArray);
request.setAttribute(Constants.BIOHAZARD_ID_LIST, bhIdArray);
request.setAttribute(Constants.BIOHAZARD_TYPES_LIST, bhTypeArray);
/**
* Name: Chetan Patil
* Reviewer: Sachin Lale
* Bug ID: Bug#3184
* Patch ID: Bug#3184_1
* Also See: 2-6
* Description: Here the older code has been integrated again inorder to restrict the specimen values based on
* requirements of study calendar event point. Two method are written to separate the code. Method populateAllRestrictedLists()
* will populate the values for the lists form Specimen Requirements whereas, method populateAllLists() will populate the values
* of the list form the system.
*/
//Setting Secimen Collection Group
/**For Migration Start**/
// initializeAndSetSpecimenCollectionGroupIdList(bizLogic,request);
/**For Migration Start**/
/**
* Patch ID: Bug#4245_2
*
*/
List<NameValueBean> specimenClassList = new ArrayList<NameValueBean>();
List<NameValueBean> specimenTypeList = new ArrayList<NameValueBean>();
List<NameValueBean> tissueSiteList = new ArrayList<NameValueBean>();
List<NameValueBean> tissueSideList = new ArrayList<NameValueBean>();
List<NameValueBean> pathologicalStatusList = new ArrayList<NameValueBean>();
Map<String, List<NameValueBean>> subTypeMap = new HashMap<String, List<NameValueBean>>();
String specimenCollectionGroupId = specimenForm.getSpecimenCollectionGroupId();
if (specimenCollectionGroupId != null && !specimenCollectionGroupId.equals(""))
{ // If specimen is being added form specimen collection group page or a specimen is being edited.
if (Constants.ALIQUOT.equals(specimenForm.getLineage()))
{
populateListBoxes(specimenForm, request);
}
populateAllLists(specimenForm, specimenClassList, specimenTypeList, tissueSiteList, tissueSideList,
pathologicalStatusList, subTypeMap);
}
else
{ // On adding a new specimen independently.
populateAllLists(specimenForm, specimenClassList, specimenTypeList, tissueSiteList, tissueSideList,
pathologicalStatusList, subTypeMap);
}
/**
* Name : Virender Mehta
* Reviewer: Sachin Lale
* Bug ID: defaultValueConfiguration_BugID
* Patch ID:defaultValueConfiguration_BugID_10
* See also:defaultValueConfiguration_BugID_9,11
* Description: Configuration of default value for TissueSite, TissueSite, PathologicalStatus
*
* Note by Chetan: Value setting for TissueSite and PathologicalStatus has been moved into the
* method populateAllLists().
*/
// Setting the default values
if (specimenForm.getTissueSide() == null || specimenForm.getTissueSide().equals("-1"))
{
specimenForm.setTissueSide((String)DefaultValueManager.getDefaultValue(Constants.DEFAULT_TISSUE_SIDE));
}
// sets the Specimen Class list
request.setAttribute(Constants.SPECIMEN_CLASS_LIST, specimenClassList);
// sets the Specimen Type list
request.setAttribute(Constants.SPECIMEN_TYPE_LIST, specimenTypeList);
// sets the Tissue Site list
request.setAttribute(Constants.TISSUE_SITE_LIST, tissueSiteList);
// sets the PathologicalStatus list
request.setAttribute(Constants.PATHOLOGICAL_STATUS_LIST, pathologicalStatusList);
// sets the Side list
request.setAttribute(Constants.TISSUE_SIDE_LIST, tissueSideList);
// set the map of subtype
request.setAttribute(Constants.SPECIMEN_TYPE_MAP, subTypeMap);
//Setting biohazard list
biohazardList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_BIOHAZARD, null);
request.setAttribute(Constants.BIOHAZARD_TYPE_LIST, biohazardList);
/**
* Name : Ashish Gupta
* Reviewer Name : Sachin Lale
* Bug ID: 2741
* Patch ID: 2741_12
* Description: Propagating events from scg to multiple specimens
*/
if(operation.equals(Constants.ADD))
populateEventsFromScg(specimenCollectionGroup,specimenForm);
Object scgForm = request.getAttribute("scgForm");
if(scgForm != null)
{
SpecimenCollectionGroupForm specimenCollectionGroupForm = (SpecimenCollectionGroupForm)scgForm;
}
else
{
//Mandar : 10-July-06 AutoEvents : CollectionEvent
setCollectionEventRequestParameters(request, specimenForm);
//Mandar : 11-July-06 AutoEvents : ReceivedEvent
setReceivedEventRequestParameters(request, specimenForm);
//Mandar : set default date and time too event fields
setDateParameters(specimenForm);
}
// ---- chetan 15-06-06 ----
StorageContainerBizLogic scbizLogic = (StorageContainerBizLogic) BizLogicFactory.getInstance().getBizLogic(
Constants.STORAGE_CONTAINER_FORM_ID);
TreeMap containerMap = new TreeMap();
List initialValues = null;
if (operation.equals(Constants.ADD))
{
SessionDataBean sessionData = (SessionDataBean) request.getSession().getAttribute(Constants.SESSION_DATA);
if(specimenForm.getLabel()==null || specimenForm.getLabel().equals(""))
{
//int totalNoOfSpecimen = bizLogic.totalNoOfSpecimen(sessionData)+1;
/**
* Name : Virender Mehta
* Reviewer: Sachin Lale
* Description: By getting instance of AbstractSpecimenGenerator abstract class current label retrived and set.
*/
// SpecimenLabelGenerator spLblGenerator = SpecimenLabelGeneratorFactory.getInstance();
// Map inputMap = new HashMap();
// inputMap.put(Constants.SCG_NAME_KEY, specimenCollectionGroupName);
// String specimenLabel= spLblGenerator.getNextAvailableSpecimenlabel(inputMap);
// specimenForm.setLabel(specimenLabel);
}
if (specimenForm.getSpecimenCollectionGroupName() != null && !specimenForm.getSpecimenCollectionGroupName().equals("")
&& specimenForm.getClassName() != null && !specimenForm.getClassName().equals("") && !specimenForm.getClassName().equals("-1"))
{
//Logger.out.debug("before retrieval of spCollGroupList inside specimen action ^^^^^^^^^^^");
String[] selectColumnName = {"collectionProtocolRegistration.collectionProtocol.id"};
String[] whereColumnName = {"name"};
String[] whereColumnCondition = {"="};
String[] whereColumnValue = {specimenForm.getSpecimenCollectionGroupName()};
List spCollGroupList = bizLogic.retrieve(SpecimenCollectionGroup.class.getName(), selectColumnName, whereColumnName,
whereColumnCondition, whereColumnValue, null);
//Logger.out.debug("after retrieval of spCollGroupList inside specimen action ^^^^^^^^^^^");
if (spCollGroupList!=null && !spCollGroupList.isEmpty())
{
// Object []spCollGroup = (Object[]) spCollGroupList
// .get(0);
long cpId = ((Long) spCollGroupList.get(0)).longValue();
String spClass = specimenForm.getClassName();
Logger.out.info("cpId :" + cpId + "spClass:" + spClass);
request.setAttribute(Constants.COLLECTION_PROTOCOL_ID, cpId + "");
if (virtuallyLocated != null && virtuallyLocated.equals("false"))
{
specimenForm.setVirtuallyLocated(false);
}
if(specimenForm.getStContSelection() == 2)
{
//Logger.out.debug("calling getAllocatedContaienrMapForSpecimen() function from NewSpecimenAction---");
sessionData = (SessionDataBean) request.getSession().getAttribute(Constants.SESSION_DATA);
containerMap = scbizLogic.getAllocatedContaienrMapForSpecimen(cpId, spClass, 0, exceedingMaxLimit, sessionData, true);
//Logger.out.debug("exceedingMaxLimit in action for Boolean:"+exceedingMaxLimit);
Logger.out.debug("finish ---calling getAllocatedContaienrMapForSpecimen() function from NewSpecimenAction---");
ActionErrors errors = (ActionErrors) request.getAttribute(Globals.ERROR_KEY);
if (containerMap.isEmpty())
{
if (errors == null || errors.size() == 0)
{
errors = new ActionErrors();
}
errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("storageposition.not.available"));
saveErrors(request, errors);
}
Logger.out.debug("calling checkForInitialValues() function from NewSpecimenAction---");
if (errors == null || errors.size() == 0)
{
initialValues = StorageContainerUtil.checkForInitialValues(containerMap);
}
else
{
String[] startingPoints = new String[3];
startingPoints[0] = specimenForm.getStorageContainer();
startingPoints[1] = specimenForm.getPositionDimensionOne();
startingPoints[2] = specimenForm.getPositionDimensionTwo() ;
initialValues = new Vector();
initialValues.add(startingPoints);
}
Logger.out.debug("finish ---calling checkForInitialValues() function from NewSpecimenAction---");
}
}
}
}
else
{
containerMap = new TreeMap();
String[] startingPoints = new String[]{"-1", "-1", "-1"};
Logger.out.info("--------------container:" + specimenForm.getStorageContainer());
Logger.out.info("--------------pos1:" + specimenForm.getPositionDimensionOne());
Logger.out.info("--------------pos2:" + specimenForm.getPositionDimensionTwo());
if (specimenForm.getStorageContainer() != null && !specimenForm.getStorageContainer().equals(""))
{
Integer id = new Integer(specimenForm.getStorageContainer());
String parentContainerName = "";
Object object=null ;
if(id>0)
{
object=bizLogic.retrieve(StorageContainer.class.getName(), new Long(specimenForm.getStorageContainer()));
}
if (object != null)
{
StorageContainer container = (StorageContainer) object;
parentContainerName = container.getName();
}
Integer pos1 = new Integer(specimenForm.getPositionDimensionOne());
Integer pos2 = new Integer(specimenForm.getPositionDimensionTwo());
List pos2List = new ArrayList();
pos2List.add(new NameValueBean(pos2, pos2));
Map pos1Map = new TreeMap();
pos1Map.put(new NameValueBean(pos1, pos1), pos2List);
containerMap.put(new NameValueBean(parentContainerName, id), pos1Map);
if (specimenForm.getStorageContainer() != null && !specimenForm.getStorageContainer().equals("-1"))
{
startingPoints[0] = specimenForm.getStorageContainer();
}
if (specimenForm.getPositionDimensionOne() != null && !specimenForm.getPositionDimensionOne().equals("-1"))
{
startingPoints[1] = specimenForm.getPositionDimensionOne();
}
if (specimenForm.getPositionDimensionTwo() != null && !specimenForm.getPositionDimensionTwo().equals("-1"))
{
startingPoints[2] = specimenForm.getPositionDimensionTwo();
}
}
initialValues = new Vector();
Logger.out.info("Starting points[0]" + startingPoints[0]);
Logger.out.info("Starting points[1]" + startingPoints[1]);
Logger.out.info("Starting points[2]" + startingPoints[2]);
initialValues.add(startingPoints);
if((specimenForm.getStContSelection() == Constants.RADIO_BUTTON_FOR_MAP)||specimenForm.getStContSelection()==2)
{
String[] selectColumnName = {"collectionProtocolRegistration.collectionProtocol.id"};
String[] whereColumnName = {"name"};
String[] whereColumnCondition = {"="};
String[] whereColumnValue = {specimenForm.getSpecimenCollectionGroupName()};
List spCollGroupList = bizLogic.retrieve(SpecimenCollectionGroup.class.getName(), selectColumnName, whereColumnName,
whereColumnCondition, whereColumnValue, null);
if (spCollGroupList!=null && !spCollGroupList.isEmpty())
{
long cpId = ((Long) spCollGroupList.get(0)).longValue();
String spClass = specimenForm.getClassName();
Logger.out.info("cpId :" + cpId + "spClass:" + spClass);
request.setAttribute(Constants.COLLECTION_PROTOCOL_ID, cpId + "");
if (virtuallyLocated != null && virtuallyLocated.equals("false"))
{
specimenForm.setVirtuallyLocated(false);
}
SessionDataBean sessionData = (SessionDataBean) request.getSession().getAttribute(Constants.SESSION_DATA);
sessionData = (SessionDataBean) request.getSession().getAttribute(Constants.SESSION_DATA);
containerMap = scbizLogic.getAllocatedContaienrMapForSpecimen(cpId, spClass, 0, exceedingMaxLimit, sessionData, true);
Logger.out.debug("finish ---calling getAllocatedContaienrMapForSpecimen() function from NewSpecimenAction---");
ActionErrors errors = (ActionErrors) request.getAttribute(Globals.ERROR_KEY);
if (containerMap.isEmpty())
{
if(specimenForm.getSelectedContainerName()==null || "".equals(specimenForm.getSelectedContainerName()))
{
if (errors == null || errors.size() == 0)
{
errors = new ActionErrors();
}
errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("storageposition.not.available"));
saveErrors(request, errors);
}
}
Logger.out.debug("calling checkForInitialValues() function from NewSpecimenAction---");
if (errors == null || errors.size() == 0)
{
initialValues = StorageContainerUtil.checkForInitialValues(containerMap);
}
else
{
String[] startingPoints1 = new String[3];
startingPoints1[0] = specimenForm.getStorageContainer();
startingPoints1[1] = specimenForm.getPositionDimensionOne();
startingPoints1[2] = specimenForm.getPositionDimensionTwo() ;
initialValues = new Vector();
initialValues.add(startingPoints1);
}
if(spClass!=null && specimenForm.getStContSelection() == Constants.RADIO_BUTTON_FOR_MAP)
{
String[] startingPoints2 = new String[]{"-1", "-1", "-1"};
initialValues = new ArrayList();
initialValues.add(startingPoints2);
request.setAttribute("initValues", initialValues);
}
}
}
}
request.setAttribute("initValues", initialValues);
request.setAttribute(Constants.EXCEEDS_MAX_LIMIT, exceedingMaxLimit);
request.setAttribute(Constants.AVAILABLE_CONTAINER_MAP, containerMap);
// -------------------------
//Falguni:Performance Enhancement.
Long specimenEntityId = null;
if (CatissueCoreCacheManager.getInstance().getObjectFromCache("specimenEntityId") != null)
{
specimenEntityId = (Long) CatissueCoreCacheManager.getInstance().getObjectFromCache("specimenEntityId");
}
else
{
specimenEntityId = AnnotationUtil.getEntityId(AnnotationConstants.ENTITY_NAME_SPECIMEN);
CatissueCoreCacheManager.getInstance().addObjectToCache("specimenEntityId",specimenEntityId);
}
request.setAttribute("specimenEntityId",specimenEntityId);
if (specimenForm.isVirtuallyLocated())
{
request.setAttribute("disabled", "true");
}
// set associated identified report id
Long reportId=getAssociatedIdentifiedReportId(specimenForm.getId());
if(reportId==null)
{
reportId=new Long(-1);
}
else if(Utility.isQuarantined(reportId))
{
reportId=new Long(-2);
}
HttpSession session =request.getSession();
session.setAttribute(Constants.IDENTIFIED_REPORT_ID, reportId);
//Logger.out.debug("End of specimen action");
request.setAttribute("createdDate", specimenForm.getCreatedDate());
request.setAttribute("specimenActivityStatus",
Constants.SPECIMEN_ACTIVITY_STATUS_VALUES);
return mapping.findForward(pageOf);
}
/**
* This method populates the list boxes for type, tissue site, tissue side
* and pathological status if this specimen is an aliquot.
* @param specimenForm object of NewSpecimenForm
* @param request object of HttpServletRequest
*/
private void populateListBoxes(NewSpecimenForm specimenForm, HttpServletRequest request)
{
//Setting the specimen type list
NameValueBean bean = new NameValueBean(specimenForm.getType(), specimenForm.getType());
List specimenTypeList = new ArrayList();
specimenTypeList.add(bean);
request.setAttribute(Constants.SPECIMEN_TYPE_LIST, specimenTypeList);
//Setting tissue site list
bean = new NameValueBean(specimenForm.getTissueSite(), specimenForm.getTissueSite());
List tissueSiteList = new ArrayList();
tissueSiteList.add(bean);
request.setAttribute(Constants.TISSUE_SITE_LIST, tissueSiteList);
//Setting tissue side list
bean = new NameValueBean(specimenForm.getTissueSide(), specimenForm.getTissueSide());
List tissueSideList = new ArrayList();
tissueSideList.add(bean);
request.setAttribute(Constants.TISSUE_SIDE_LIST, tissueSideList);
//Setting pathological status list
bean = new NameValueBean(specimenForm.getPathologicalStatus(), specimenForm.getPathologicalStatus());
List pathologicalStatusList = new ArrayList();
pathologicalStatusList.add(bean);
request.setAttribute(Constants.PATHOLOGICAL_STATUS_LIST, pathologicalStatusList);
}
// Mandar AutoEvents CollectionEvent start
/**
* This method sets all the collection event parameters for the SpecimenEventParameter pages
* @param request HttpServletRequest instance in which the data will be set.
* @param specimenForm NewSpecimenForm instance
* @throws Exception Throws Exception. Helps in handling exceptions at one common point.
*/
private void setCollectionEventRequestParameters(HttpServletRequest request, NewSpecimenForm specimenForm) throws Exception
{
//Gets the value of the operation parameter.
String operation = request.getParameter(Constants.OPERATION);
//Sets the operation attribute to be used in the Add/Edit FrozenEventParameters Page.
request.setAttribute(Constants.OPERATION, operation);
//Sets the minutesList attribute to be used in the Add/Edit FrozenEventParameters Page.
request.setAttribute(Constants.MINUTES_LIST, Constants.MINUTES_ARRAY);
//Sets the hourList attribute to be used in the Add/Edit FrozenEventParameters Page.
request.setAttribute(Constants.HOUR_LIST, Constants.HOUR_ARRAY);
// //The id of specimen of this event.
// String specimenId = request.getParameter(Constants.SPECIMEN_ID);
// request.setAttribute(Constants.SPECIMEN_ID, specimenId);
// Logger.out.debug("\t\t SpecimenEventParametersAction************************************ : "+specimenId );
//
UserBizLogic userBizLogic = (UserBizLogic) BizLogicFactory.getInstance().getBizLogic(Constants.USER_FORM_ID);
Collection userCollection = userBizLogic.getUsers(operation);
request.setAttribute(Constants.USERLIST, userCollection);
SessionDataBean sessionData = getSessionData(request);
if (sessionData != null)
{
String user = sessionData.getLastName() + ", " + sessionData.getFirstName();
long collectionEventUserId = EventsUtil.getIdFromCollection(userCollection, user);
if(specimenForm.getCollectionEventUserId() == 0)
{
specimenForm.setCollectionEventUserId(collectionEventUserId);
}
if(specimenForm.getReceivedEventUserId() == 0)
{
specimenForm.setReceivedEventUserId(collectionEventUserId);
}
}
/**
* Name : Virender Mehta
* Reviewer: Sachin Lale
* Bug ID: defaultValueConfiguration_BugID
* Patch ID:defaultValueConfiguration_BugID_11
* See also:defaultValueConfiguration_BugID_9,10,11
* Description: Configuration for default value for Collection Procedure, Container and Quality
*/
// set the procedure lists
List procedureList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_COLLECTION_PROCEDURE, null);
request.setAttribute(Constants.PROCEDURE_LIST, procedureList);
//Bug- setting the default collection event procedure
if (specimenForm.getCollectionEventCollectionProcedure() == null)
{
specimenForm.setCollectionEventCollectionProcedure((String)DefaultValueManager.getDefaultValue(Constants.DEFAULT_COLLECTION_PROCEDURE));
}
// set the container lists
List containerList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_CONTAINER, null);
request.setAttribute(Constants.CONTAINER_LIST, containerList);
//Bug- setting the default collection event container
if (specimenForm.getCollectionEventContainer() == null)
{
specimenForm.setCollectionEventContainer((String)DefaultValueManager.getDefaultValue(Constants.DEFAULT_CONTAINER));
}
}
// Mandar AutoEvents CollectionEvent end
// Mandar Autoevents ReceivedEvent start
/**
* This method sets all the received event parameters for the SpecimenEventParameter pages
* @param request HttpServletRequest instance in which the data will be set.
* @param specimenForm NewSpecimenForm instance
* @throws Exception Throws Exception. Helps in handling exceptions at one common point.
*/
private void setReceivedEventRequestParameters(HttpServletRequest request, NewSpecimenForm specimenForm) throws Exception
{
List qualityList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_RECEIVED_QUALITY, null);
request.setAttribute(Constants.RECEIVED_QUALITY_LIST, qualityList);
//Bug- setting the default recieved event quality
if (specimenForm.getReceivedEventReceivedQuality() == null)
{
specimenForm.setReceivedEventReceivedQuality((String)DefaultValueManager.getDefaultValue(Constants.DEFAULT_RECEIVED_QUALITY));
}
}
/**
* @param specimenForm instance of NewSpecimenForm
*/
private void setDateParameters(NewSpecimenForm specimenForm)
{
// set the current Date and Time for the event.
Calendar cal = Calendar.getInstance();
//Collection Event fields
if (specimenForm.getCollectionEventdateOfEvent() == null)
{
specimenForm.setCollectionEventdateOfEvent(Utility.parseDateToString(cal.getTime(), Variables.dateFormat));
}
if (specimenForm.getCollectionEventTimeInHours() == null)
{
specimenForm.setCollectionEventTimeInHours(Integer.toString(cal.get(Calendar.HOUR_OF_DAY)));
}
if (specimenForm.getCollectionEventTimeInMinutes() == null)
{
specimenForm.setCollectionEventTimeInMinutes(Integer.toString(cal.get(Calendar.MINUTE)));
}
//ReceivedEvent Fields
if (specimenForm.getReceivedEventDateOfEvent() == null)
{
specimenForm.setReceivedEventDateOfEvent(Utility.parseDateToString(cal.getTime(), Variables.dateFormat));
}
if (specimenForm.getReceivedEventTimeInHours() == null)
{
specimenForm.setReceivedEventTimeInHours(Integer.toString(cal.get(Calendar.HOUR_OF_DAY)));
}
if (specimenForm.getReceivedEventTimeInMinutes() == null)
{
specimenForm.setReceivedEventTimeInMinutes(Integer.toString(cal.get(Calendar.MINUTE)));
}
}
/**
* @param specimenForm instance of NewSpecimenForm
*/
private void clearCollectionEvent(NewSpecimenForm specimenForm)
{
specimenForm.setCollectionEventCollectionProcedure("");
specimenForm.setCollectionEventComments("");
specimenForm.setCollectionEventContainer("");
specimenForm.setCollectionEventdateOfEvent("");
specimenForm.setCollectionEventTimeInHours("");
specimenForm.setCollectionEventTimeInMinutes("");
specimenForm.setCollectionEventUserId(-1);
}
/**
* @param specimenForm instance of NewSpecimenForm
*/
private void clearReceivedEvent(NewSpecimenForm specimenForm)
{
specimenForm.setReceivedEventComments("");
specimenForm.setReceivedEventDateOfEvent("");
specimenForm.setReceivedEventReceivedQuality("");
specimenForm.setReceivedEventTimeInHours("");
specimenForm.setReceivedEventTimeInMinutes("");
specimenForm.setReceivedEventUserId(-1);
}
//Consent Tracking (Virender Mehta)
/**
* Prepare Map for Consent tiers
* @param participantResponseList This list will be iterated to map to populate participant Response status.
* @return tempMap
*/
private Map prepareConsentMap(List participantResponseList,Collection consentResponse)
{
Map tempMap = new HashMap();
Long consentTierID;
Long consentID;
if(participantResponseList!=null||consentResponse!=null)
{
int i = 0;
Iterator consentResponseCollectionIter = participantResponseList.iterator();
while(consentResponseCollectionIter.hasNext())
{
ConsentTierResponse consentTierResponse = (ConsentTierResponse)consentResponseCollectionIter.next();
Iterator statusCollectionIter = consentResponse.iterator();
consentTierID=consentTierResponse.getConsentTier().getId();
while(statusCollectionIter.hasNext())
{
ConsentTierStatus consentTierstatus=(ConsentTierStatus)statusCollectionIter.next();
consentID=consentTierstatus.getConsentTier().getId();
if(consentTierID.longValue()==consentID.longValue())
{
ConsentTier consent = consentTierResponse.getConsentTier();
String idKey="ConsentBean:"+i+"_consentTierID";
String statementKey="ConsentBean:"+i+"_statement";
String responseKey="ConsentBean:"+i+"_participantResponse";
String participantResponceIdKey="ConsentBean:"+i+"_participantResponseID";
String scgResponsekey = "ConsentBean:"+i+"_specimenCollectionGroupLevelResponse";
String scgResponseIDkey ="ConsentBean:"+i+"_specimenCollectionGroupLevelResponseID";
String specimenResponsekey = "ConsentBean:"+i+"_specimenLevelResponse";
String specimenResponseIDkey ="ConsentBean:"+i+"_specimenLevelResponseID";
tempMap.put(idKey, consent.getId());
tempMap.put(statementKey,consent.getStatement());
tempMap.put(responseKey,consentTierResponse.getResponse());
tempMap.put(participantResponceIdKey,consentTierResponse.getId());
tempMap.put(scgResponsekey, consentTierstatus.getStatus());
tempMap.put(scgResponseIDkey, consentTierstatus.getId());
tempMap.put(specimenResponsekey,consentTierstatus.getStatus());
tempMap.put(specimenResponseIDkey,null);
i++;
break;
}
}
}
return tempMap;
}
else
{
return null;
}
}
//Consent Tracking (Virender Mehta)
/**
* @param specimenForm instance of NewSpecimenForm
* @param specimenCollectionGroupId String containing specimen collection group Id
* @param specimenCollectionGroupName String containing specimen collection group name
*/
private void setFormValues(NewSpecimenForm specimenForm, String specimenCollectionGroupId,
String specimenCollectionGroupName)
{
specimenForm.setSpecimenCollectionGroupId(specimenCollectionGroupId);
specimenForm.setSpecimenCollectionGroupName(specimenCollectionGroupName);
specimenForm.setVirtuallyLocated(true);
specimenForm.setParentSpecimenId("");
specimenForm.setLabel("");
specimenForm.setBarcode("");
specimenForm.setPositionInStorageContainer("");
specimenForm.setPositionDimensionOne("");
specimenForm.setPositionDimensionTwo("");
specimenForm.setStorageContainer("");
}
/**
* Patch ID: Bug#3184_2
*/
/**
* This method initializes the List of SpecimenCollectionGroup in the system and sets the list as an
* attribute in the request.
* @param bizLogic NewSpecimenBizLogic to fetch the SpecimenCollectionGroup list
* @param request HttpServletRequest in which the list is set as an attribute
* @throws DAOException on failure to initialize the list
*/
/**For Migration Start**/
/* private void initializeAndSetSpecimenCollectionGroupIdList(NewSpecimenBizLogic bizLogic, HttpServletRequest request) throws DAOException
{
String sourceObjectName = SpecimenCollectionGroup.class.getName();
String[] displayNameFields = {"name"};
String valueField = Constants.SYSTEM_IDENTIFIER;
List specimenCollectionGroupList = bizLogic.getList(sourceObjectName, displayNameFields, valueField, true);
request.setAttribute(Constants.SPECIMEN_COLLECTION_GROUP_LIST, specimenCollectionGroupList);
}
*/
/**
* This method generates Map of SpecimenClass and the List of the corresponding Types.
* @param tempMap a temporary Map for avoiding duplication of values.
* @param subTypeMap the Map of SpecimenClass and the List of the corresponding Types
* @param specimenClass Class of Speciment
* @param specimenType Type of Specimen
*/
private void populateSpecimenTypeLists(Map<String, String> tempMap, Map<String, List<NameValueBean>> subTypeMap,
String specimenClass, String specimenType)
{
List<NameValueBean> tempList = subTypeMap.get(specimenClass);
if (tempList == null)
{
tempList = new ArrayList<NameValueBean>();
tempList.add(new NameValueBean(Constants.SELECT_OPTION, "-1"));
tempList.add(new NameValueBean(specimenType, specimenType));
subTypeMap.put(specimenClass, tempList);
tempMap.put(specimenClass + specimenType + Constants.SPECIMEN_TYPE, specimenType);
}
else
{
tempList = subTypeMap.get(specimenClass);
tempList.add(new NameValueBean(specimenType, specimenType));
Collections.sort(tempList);
subTypeMap.put(specimenClass, tempList);
tempMap.put(specimenClass + specimenType + Constants.SPECIMEN_TYPE, specimenType);
}
}
/**
* This method populates all the values form the system for the respective lists.
* @param specimenForm NewSpecimenForm to set the List of TissueSite and PathologicalStatus
* @param specimenClassList List of Specimen Class
* @param specimenTypeList List of Specimen Type
* @param tissueSiteList List of Tissue Site
* @param tissueSideList List of Tissue Side
* @param pathologicalStatusList List of Pathological Status
* @param subTypeMap Map of the Class and their corresponding Types
* @throws DAOException on failure to populate values from the system
*/private void populateAllLists(NewSpecimenForm specimenForm, List<NameValueBean> specimenClassList, List<NameValueBean> specimenTypeList,
List<NameValueBean> tissueSiteList, List<NameValueBean> tissueSideList, List<NameValueBean> pathologicalStatusList,
Map<String, List<NameValueBean>> subTypeMap)
throws DAOException
{
// Getting the specimen type list
specimenTypeList = Utility.getListFromCDE(Constants.CDE_NAME_SPECIMEN_TYPE);
/**
* Name : Virender Mehta
* Reviewer: Sachin Lale
* Bug ID: TissueSiteCombo_BugID
* Patch ID:TissueSiteCombo_BugID_1
* See also:TissueSiteCombo_BugID_2
* Description: Getting TissueList with only Leaf node
*/
tissueSiteList.addAll(Utility.tissueSiteList());
//Getting tissue side list
tissueSideList.addAll(Utility.getListFromCDE(Constants.CDE_NAME_TISSUE_SIDE));
//Getting pathological status list
pathologicalStatusList.addAll(Utility.getListFromCDE(Constants.CDE_NAME_PATHOLOGICAL_STATUS));
// get the Specimen class and type from the cde
CDE specimenClassCDE = CDEManager.getCDEManager().getCDE(Constants.CDE_NAME_SPECIMEN_CLASS);
Set<PermissibleValue> setPV = specimenClassCDE.getPermissibleValues();
for (PermissibleValue pv : setPV)
{
String tmpStr = pv.getValue();
Logger.out.debug(tmpStr);
specimenClassList.add(new NameValueBean(tmpStr, tmpStr));
List<NameValueBean> innerList = new ArrayList<NameValueBean>();
innerList.add(new NameValueBean(Constants.SELECT_OPTION, "-1"));
Set<PermissibleValue> list1 = pv.getSubPermissibleValues();
Logger.out.debug("list1 " + list1);
for (PermissibleValue pv1 : list1)
{
// set specimen type
String tmpInnerStr = pv1.getValue();
Logger.out.debug("\t\t" + tmpInnerStr);
innerList.add(new NameValueBean(tmpInnerStr, tmpInnerStr));
}
Collections.sort(innerList);
subTypeMap.put(tmpStr, innerList);
} // class and values set
Logger.out.debug("\n\n\n\n**********MAP DATA************\n");
// Setting the default values
if (specimenForm.getTissueSite() == null)
{
specimenForm.setTissueSite((String)DefaultValueManager.getDefaultValue(Constants.DEFAULT_TISSUE_SITE));
}
if (specimenForm.getPathologicalStatus() == null)
{
specimenForm.setPathologicalStatus((String)DefaultValueManager.getDefaultValue(Constants.DEFAULT_PATHOLOGICAL_STATUS));
}
Utility.setDefaultPrinterTypeLocation(specimenForm);
}
/**
* Name : Ashish Gupta
* Reviewer Name : Sachin Lale
* Bug ID: 2741
* Patch ID: 2741_13
* Description: Method to propagate Events to multiple specimens from scg
*/
/**
* @param specimenCollectionGroupForm instance of SpecimenCollectionGroupForm
* @param specimenForm instance of NewSpecimenForm
*/
/*public static void populateEventsFromScg1(SpecimenCollectionGroupForm specimenCollectionGroupForm,NewSpecimenForm specimenForm)
{
specimenForm.setCollectionEventUserId(specimenCollectionGroupForm.getCollectionEventUserId());
specimenForm.setReceivedEventUserId(specimenCollectionGroupForm.getReceivedEventUserId());
specimenForm.setCollectionEventCollectionProcedure("Not Specified");
specimenForm.setCollectionEventContainer("Not Specified");
specimenForm.setReceivedEventReceivedQuality("Not Specified");
specimenForm.setCollectionEventdateOfEvent(specimenCollectionGroupForm.getCollectionEventdateOfEvent());
specimenForm.setCollectionEventTimeInHours(specimenCollectionGroupForm.getCollectionEventTimeInHours());
specimenForm.setCollectionEventTimeInMinutes(specimenCollectionGroupForm.getCollectionEventTimeInMinutes());
specimenForm.setReceivedEventDateOfEvent(specimenCollectionGroupForm.getReceivedEventDateOfEvent());
specimenForm.setReceivedEventTimeInHours(specimenCollectionGroupForm.getReceivedEventTimeInHours());
specimenForm.setReceivedEventTimeInMinutes(specimenCollectionGroupForm.getReceivedEventTimeInMinutes());
}*/
public static void populateEventsFromScg(SpecimenCollectionGroup specimenCollectionGroup,NewSpecimenForm specimenForm)
{
Calendar calender = Calendar.getInstance();
Collection scgEventColl = specimenCollectionGroup.getSpecimenEventParametersCollection();
if(scgEventColl != null && !scgEventColl.isEmpty())
{
Iterator itr = scgEventColl.iterator();
while(itr.hasNext())
{
Object specimenEventParameter = itr.next();
if(specimenEventParameter instanceof CollectionEventParameters)
{
CollectionEventParameters scgCollEventParam = (CollectionEventParameters) specimenEventParameter;
calender.setTime(scgCollEventParam.getTimestamp());
specimenForm.setCollectionEventUserId(scgCollEventParam.getUser().getId().longValue());
specimenForm.setCollectionEventCollectionProcedure(scgCollEventParam.getCollectionProcedure());
specimenForm.setCollectionEventContainer(scgCollEventParam.getContainer());
specimenForm.setCollectionEventdateOfEvent(Utility.parseDateToString(scgCollEventParam.getTimestamp(),Variables.dateFormat));
specimenForm.setCollectionEventTimeInHours(Utility.toString(Integer.toString(calender.get(Calendar.HOUR_OF_DAY))));
specimenForm.setCollectionEventTimeInMinutes(Utility.toString(Integer.toString(calender.get(Calendar.MINUTE))));
}
if(specimenEventParameter instanceof ReceivedEventParameters)
{
ReceivedEventParameters scgReceivedEventParam = (ReceivedEventParameters) specimenEventParameter;
calender.setTime(scgReceivedEventParam.getTimestamp());
specimenForm.setReceivedEventUserId(scgReceivedEventParam.getUser().getId().longValue());
specimenForm.setReceivedEventReceivedQuality(scgReceivedEventParam.getReceivedQuality());
specimenForm.setReceivedEventDateOfEvent(Utility.parseDateToString(scgReceivedEventParam.getTimestamp(),Variables.dateFormat));
specimenForm.setReceivedEventTimeInHours(Utility.toString(Integer.toString(calender.get(Calendar.HOUR_OF_DAY))));
specimenForm.setReceivedEventTimeInMinutes(Utility.toString(Integer.toString(calender.get(Calendar.MINUTE))));
}
}
}
/* specimenForm.setCollectionEventUserId(specimenCollectionGroupForm.getCollectionEventUserId());
specimenForm.setReceivedEventUserId(specimenCollectionGroupForm.getReceivedEventUserId());
specimenForm.setCollectionEventCollectionProcedure("Not Specified");
specimenForm.setCollectionEventContainer("Not Specified");
specimenForm.setReceivedEventReceivedQuality("Not Specified");
specimenForm.setCollectionEventdateOfEvent(specimenCollectionGroupForm.getCollectionEventdateOfEvent());
specimenForm.setCollectionEventTimeInHours(specimenCollectionGroupForm.getCollectionEventTimeInHours());
specimenForm.setCollectionEventTimeInMinutes(specimenCollectionGroupForm.getCollectionEventTimeInMinutes());
specimenForm.setReceivedEventDateOfEvent(specimenCollectionGroupForm.getReceivedEventDateOfEvent());
specimenForm.setReceivedEventTimeInHours(specimenCollectionGroupForm.getReceivedEventTimeInHours());
specimenForm.setReceivedEventTimeInMinutes(specimenCollectionGroupForm.getReceivedEventTimeInMinutes()); */
}
/**
* This function adds the columns to the List
* @return columnList
*/
public List columnNames()
{
List columnList = new ArrayList();
columnList.add(Constants.LABLE);
columnList.add(Constants.TYPE);
columnList.add(Constants.STORAGE_CONTAINER_LOCATION);
columnList.add(Constants.CLASS_NAME);
return columnList;
}
private Long getAssociatedIdentifiedReportId(Long specimenId) throws DAOException, ClassNotFoundException
{
String hqlString="select scg.identifiedSurgicalPathologyReport.id " +
" from edu.wustl.catissuecore.domain.SpecimenCollectionGroup as scg, " +
" edu.wustl.catissuecore.domain.Specimen as specimen" +
" where specimen.id = " + specimenId +
" and specimen.id in elements(scg.specimenCollection)";
List reportIDList=Utility.executeQuery(hqlString);
if(reportIDList!=null && reportIDList.size()>0)
{
return ((Long)reportIDList.get(0));
}
return null;
}
/* (non-Javadoc)
* @see edu.wustl.common.action.SecureAction#getObjectId(edu.wustl.common.actionForm.AbstractActionForm)
*/
@Override
protected String getObjectId(AbstractActionForm form)
{
NewSpecimenForm specimenForm = (NewSpecimenForm)form;
SpecimenCollectionGroup specimenCollectionGroup = null;
if(specimenForm.getSpecimenCollectionGroupId() != null || specimenForm.getSpecimenCollectionGroupId() != "")
{
try
{
specimenCollectionGroup= Utility.getSCGObj(specimenForm.getSpecimenCollectionGroupId());
CollectionProtocolRegistration cpr = specimenCollectionGroup.getCollectionProtocolRegistration();
if (cpr!= null)
{
CollectionProtocol cp = cpr.getCollectionProtocol();
return Constants.COLLECTION_PROTOCOL_CLASS_NAME +"_"+cp.getId();
}
}
catch (DAOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
} |
SVN-Revision: 17987
| WEB-INF/src/edu/wustl/catissuecore/action/NewSpecimenAction.java | ||
Java | mit | 436f4b0d270758b7bfceee0cf7605db638107116 | 0 | nallar/Mixin | package me.nallar.mixin.internal;
import lombok.Data;
import lombok.val;
import me.nallar.javatransformer.api.*;
import java.nio.file.*;
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
@Data
public class MixinApplicator {
private static final Map<String, AnnotationApplier<? extends ClassMember>> consumerMap = new HashMap<>();
static {
addAnnotationHandler(ClassInfo.class, (applicator, annotation, member, target) -> {
System.out.println("Handling class " + member + " with annotation " + annotation);
if (!applicator.makeAccessible)
return;
Object makePublicObject = annotation.values.get("makePublic");
boolean makePublic = makePublicObject != null && (Boolean) makePublicObject;
target.accessFlags((f) -> f.makeAccessible(makePublic).without(AccessFlags.ACC_FINAL));
target.getMembers().forEach((it) -> it.accessFlags((f) -> f.makeAccessible(makePublic).without(AccessFlags.ACC_FINAL)));
}, "Mixin");
addAnnotationHandler((applicator, annotation, member, target) -> target.add(member), "Add");
addAnnotationHandler(MethodInfo.class, (applicator, annotation, member, target) -> {
MethodInfo existing = target.get(member);
if (existing == null) {
throw new MixinError("Can't override method " + member + " as it does not exist in target: " + target);
}
target.remove(existing);
target.add(member);
}, "java.lang.Override", "OverrideStatic");
}
private boolean makeAccessible = true;
private boolean noMixinIsError = false;
@SuppressWarnings({"unchecked"})
private static void addAnnotationHandler(AnnotationApplier<?> methodInfoConsumer, String... names) {
if (names.length == 0)
throw new IllegalArgumentException("Must provide at least one name");
for (String name : names) {
if (!name.contains(".")) {
name = "me.nallar.mixin." + name;
}
consumerMap.put(name, methodInfoConsumer);
}
}
@SuppressWarnings("unchecked")
private static <T extends ClassMember> void addAnnotationHandler(Class<T> clazz, AnnotationApplier<T> methodInfoConsumer, String... names) {
AnnotationApplier<?> applier = (applicator, annotation, annotated, target) -> {
if (clazz.isAssignableFrom(clazz)) {
methodInfoConsumer.apply(applicator, annotation, (T) annotated, target);
}
// TODO else log warning here?
};
addAnnotationHandler(applier, names);
}
private Stream<Consumer<ClassInfo>> handleAnnotation(ClassMember annotated) {
return annotated.getAnnotations().stream().map(annotation -> {
@SuppressWarnings("unchecked")
AnnotationApplier<ClassMember> applier = (AnnotationApplier<ClassMember>) consumerMap.get(annotation.type.getClassName());
if (applier == null)
return null;
return (Consumer<ClassInfo>) (target) -> applier.apply(this, annotation, annotated, target);
}).filter(Objects::nonNull);
}
public JavaTransformer getMixinTransformer(Class<?> mixinSource) {
return getMixinTransformer(JavaTransformer.pathFromClass(mixinSource), mixinSource.getPackage().getName());
}
public JavaTransformer getMixinTransformer(Path mixinSource) {
return getMixinTransformer(mixinSource, null);
}
public JavaTransformer getMixinTransformer(Path mixinSource, String packageName) {
JavaTransformer transformer = new JavaTransformer();
val transformers = new ArrayList<Transformer.TargetedTransformer>();
transformer.addTransformer(classInfo -> {
if (!classInfo.getName().startsWith(packageName))
return;
Optional.ofNullable(MixinApplicator.this.processMixinSource(classInfo)).ifPresent(transformers::add);
});
transformer.parse(mixinSource);
transformer = new JavaTransformer();
transformers.forEach(transformer::addTransformer);
return transformer;
}
private Transformer.TargetedTransformer processMixinSource(ClassInfo clazz) {
List<Annotation> mixins = clazz.getAnnotations("me.nallar.mixin.Mixin");
if (mixins.size() == 0)
if (noMixinIsError) throw new RuntimeException("Class " + clazz.getName() + " is not an @Mixin");
else return null;
if (mixins.size() > 1)
throw new MixinError(clazz.getName() + " can not use @Mixin multiple times");
val mixin = mixins.get(0);
String target = (String) mixin.values.get("target");
if (target == null || target.isEmpty()) {
target = clazz.getSuperType().getClassName();
}
if (!clazz.getAccessFlags().has(AccessFlags.ACC_ABSTRACT)) {
throw new MixinError(clazz.getName() + " must be abstract to use @Mixin");
}
List<Consumer<ClassInfo>> applicators = Stream.concat(Stream.of(clazz), clazz.getMembers().stream())
.flatMap(this::handleAnnotation).collect(Collectors.toList());
logInfo("Found Mixin class '" + clazz.getName() + "' targeting class '" + target + " with " + applicators.size() + " applicators.");
final String finalTarget = target;
return new Transformer.TargetedTransformer() {
@Override
public Collection<String> getTargetClasses() {
return Collections.singletonList(finalTarget);
}
@Override
public void transform(ClassInfo classInfo) {
applicators.forEach(applicator -> applicator.accept(classInfo));
}
};
}
private void logInfo(String s) {
// TODO: 24/01/2016 Proper logging
System.out.println(s);
}
private interface AnnotationApplier<T extends ClassMember> {
void apply(MixinApplicator applicator, Annotation annotation, T annotatedMember, ClassInfo mixinTarget);
}
}
| src/main/java/me/nallar/mixin/internal/MixinApplicator.java | package me.nallar.mixin.internal;
import lombok.Data;
import lombok.val;
import me.nallar.javatransformer.api.*;
import java.nio.file.*;
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
@Data
public class MixinApplicator {
private static final Map<String, AnnotationApplier<? extends ClassMember>> consumerMap = new HashMap<>();
static {
addAnnotationHandler(ClassInfo.class, (applicator, annotation, member, target) -> {
System.out.println("Handling class " + member + " with annotation " + annotation);
if (!applicator.makeAccessible)
return;
Object makePublicObject = annotation.values.get("makePublic");
boolean makePublic = makePublicObject != null && (Boolean) makePublicObject;
member.accessFlags((f) -> f.makeAccessible(makePublic).without(AccessFlags.ACC_FINAL));
member.getMembers().forEach((it) -> it.accessFlags((f) -> f.makeAccessible(makePublic).without(AccessFlags.ACC_FINAL)));
}, "Mixin");
addAnnotationHandler((applicator, annotation, member, target) -> target.add(member), "Add");
addAnnotationHandler(MethodInfo.class, (applicator, annotation, member, target) -> {
MethodInfo existing = target.get(member);
if (existing == null) {
throw new MixinError("Can't override method " + member + " as it does not exist in target: " + target);
}
target.remove(existing);
target.add(member);
}, "java.lang.Override", "OverrideStatic");
}
private boolean makeAccessible = true;
private boolean noMixinIsError = false;
@SuppressWarnings({"unchecked"})
private static void addAnnotationHandler(AnnotationApplier<?> methodInfoConsumer, String... names) {
if (names.length == 0)
throw new IllegalArgumentException("Must provide at least one name");
for (String name : names) {
if (!name.contains(".")) {
name = "me.nallar.mixin." + name;
}
consumerMap.put(name, methodInfoConsumer);
}
}
@SuppressWarnings("unchecked")
private static <T extends ClassMember> void addAnnotationHandler(Class<T> clazz, AnnotationApplier<T> methodInfoConsumer, String... names) {
AnnotationApplier<?> applier = (applicator, annotation, annotated, target) -> {
if (clazz.isAssignableFrom(clazz)) {
methodInfoConsumer.apply(applicator, annotation, (T) annotated, target);
}
// TODO else log warning here?
};
addAnnotationHandler(applier, names);
}
private Stream<Consumer<ClassInfo>> handleAnnotation(ClassMember annotated) {
return annotated.getAnnotations().stream().map(annotation -> {
@SuppressWarnings("unchecked")
AnnotationApplier<ClassMember> applier = (AnnotationApplier<ClassMember>) consumerMap.get(annotation.type.getClassName());
if (applier == null)
return null;
return (Consumer<ClassInfo>) (target) -> applier.apply(this, annotation, annotated, target);
}).filter(Objects::nonNull);
}
public JavaTransformer getMixinTransformer(Class<?> mixinSource) {
return getMixinTransformer(JavaTransformer.pathFromClass(mixinSource), mixinSource.getPackage().getName());
}
public JavaTransformer getMixinTransformer(Path mixinSource) {
return getMixinTransformer(mixinSource, null);
}
public JavaTransformer getMixinTransformer(Path mixinSource, String packageName) {
JavaTransformer transformer = new JavaTransformer();
val transformers = new ArrayList<Transformer.TargetedTransformer>();
transformer.addTransformer(classInfo -> {
if (!classInfo.getName().startsWith(packageName))
return;
Optional.ofNullable(MixinApplicator.this.processMixinSource(classInfo)).ifPresent(transformers::add);
});
transformer.parse(mixinSource);
transformer = new JavaTransformer();
transformers.forEach(transformer::addTransformer);
return transformer;
}
private Transformer.TargetedTransformer processMixinSource(ClassInfo clazz) {
List<Annotation> mixins = clazz.getAnnotations("me.nallar.mixin.Mixin");
if (mixins.size() == 0)
if (noMixinIsError) throw new RuntimeException("Class " + clazz.getName() + " is not an @Mixin");
else return null;
if (mixins.size() > 1)
throw new MixinError(clazz.getName() + " can not use @Mixin multiple times");
val mixin = mixins.get(0);
String target = (String) mixin.values.get("target");
if (target == null || target.isEmpty()) {
target = clazz.getSuperType().getClassName();
}
if (!clazz.getAccessFlags().has(AccessFlags.ACC_ABSTRACT)) {
throw new MixinError(clazz.getName() + " must be abstract to use @Mixin");
}
List<Consumer<ClassInfo>> applicators = Stream.concat(Stream.of(clazz), clazz.getMembers().stream())
.flatMap(this::handleAnnotation).collect(Collectors.toList());
logInfo("Found Mixin class '" + clazz.getName() + "' targeting class '" + target + " with " + applicators.size() + " applicators.");
final String finalTarget = target;
return new Transformer.TargetedTransformer() {
@Override
public Collection<String> getTargetClasses() {
return Collections.singletonList(finalTarget);
}
@Override
public void transform(ClassInfo classInfo) {
applicators.forEach(applicator -> applicator.accept(classInfo));
}
};
}
private void logInfo(String s) {
// TODO: 24/01/2016 Proper logging
System.out.println(s);
}
private interface AnnotationApplier<T extends ClassMember> {
void apply(MixinApplicator applicator, Annotation annotation, T annotatedMember, ClassInfo mixinTarget);
}
}
| Fix applying mixin to source instead of target
| src/main/java/me/nallar/mixin/internal/MixinApplicator.java | Fix applying mixin to source instead of target |
|
Java | mit | e98ddb2975979559eb8d563e152a93a2f41f70f3 | 0 | vinsol/sms-scheduler | package com.vinsol.sms_scheduler;
import java.util.ArrayList;
import java.util.Random;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import com.vinsol.sms_scheduler.receivers.SMSHandleReceiver;
import com.vinsol.sms_scheduler.utils.Log;
public class DBAdapter {
private final String DATABASE_NAME = "smsDatabase";
private final String DATABASE_SMS_TABLE = "smsTable";
private final String DATABASE_PI_TABLE = "piTable";
private final String DATABASE_TEMPLATE_TABLE = "templateTable";
private final String DATABASE_GROUP_TABLE = "groupTable";
private final String DATABASE_GROUP_CONTACT_RELATION = "groupContactRelation";
private final String DATABASE_SPANS_TABLE = "spanTable";
private final String DATABASE_SPAN_GROUP_REL_TABLE = "span_grp_rel_table";
private final String DATABASE_RECENTS_TABLE = "recents_table";
private final int DATABASE_VERSION = 1;
Cursor cur;
//---------------------------static keys for columns---------------------------------------
//----------------keys for SMS table--------------------------
public static final String KEY_ID = "_id";
public static final String KEY_NUMBER = "number";
public static final String KEY_GRPID = "group_id";
public static final String KEY_MESSAGE = "message";
public static final String KEY_DATE = "date";
public static final String KEY_TIME_MILLIS = "time_millis";
public static final String KEY_SENT = "sent";
public static final String KEY_DELIVER = "deliver";
public static final String KEY_MSG_PARTS = "msg_parts";
public static final String KEY_S_MILLIS = "sent_milis";
public static final String KEY_D_MILLIS = "deliver_milis";
public static final String KEY_OPERATED = "operation_done";
public static final String KEY_DRAFT = "is_draft";
//--------------keys for PI table---------------------------
public static final String KEY_PI_ID = "_id";
public static final String KEY_PI_NUMBER = "pi_number";
public static final String KEY_SMS_ID = "sms_id";
public static final String KEY_TIME = "time";
public static final String KEY_ACTION = "action";
//----------------keys for template table---------------------
public static final String KEY_TEMP_ID = "_id";
public static final String KEY_TEMP_CONTENT = "content";
//-----------------keys for group table-----------------------
public static final String KEY_GROUP_ID = "_id";
public static final String KEY_GROUP_NAME = "group_name";
//----------------keys for group contacts relation----------------
public static final String KEY_RELATION_ID = "_id";
public static final String KEY_GROUP_REL_ID = "group_rel_id";
public static final String KEY_CONTACTS_ID = "contacts_id";
//-----------------keys for spans table----------------------------
public static final String KEY_SPAN_ID = "_id";
public static final String KEY_SPAN_DN = "span_display_name";
public static final String KEY_SPAN_TYPE = "span_type";
public static final String KEY_SPAN_ENTITY_ID = "span_entity_id";
public static final String KEY_SPAN_SMS_ID = "span_sms_id";
//-------------------keys for span-groupId relation--------------------
public static final String KEY_SPAN_GRP_REL_ID = "_id";
public static final String KEY_SPAN_GRP_REL_SPAN_ID = "span_grp_rel_span_id";
public static final String KEY_SPAN_GRP_REL_GRP_ID = "span_grp_rel_grp_id";
public static final String KEY_SPAN_GRP_REL_GRP_TYPE = "span_grp_rel_grp_type";
//------------------keys for recents table-------------------------
public static final String KEY_RECENT_CONTACT_ID = "_id";
public static final String KEY_RECENT_CONTACT_CONTACT_ID = "contact_id";
public static final String KEY_RECENT_CONTACT_NUMBER = "contact_number";
//------------------------------------------------------------------end of static keys defs-------
//SQL to open or create a database
private final String DATABASE_CREATE_SMS_TABLE = "create table " + DATABASE_SMS_TABLE
+ " ("
+ KEY_ID + " integer primary key autoincrement, "
+ KEY_GRPID + " integer, "
+ KEY_NUMBER + " text not null, "
+ KEY_MESSAGE + " text, "
+ KEY_DATE + " text, "
+ KEY_TIME_MILLIS + " long, "
+ KEY_SENT + " integer default 0, "
+ KEY_DELIVER + " integer default 0, "
+ KEY_MSG_PARTS + " integer default 0, "
+ KEY_S_MILLIS + " integer, "
+ KEY_D_MILLIS + " integer, "
+ KEY_OPERATED + " integer default 0, "
+ KEY_DRAFT + " integer default 0);";
private final String DATABASE_CREATE_PI_TABLE = "create table " + DATABASE_PI_TABLE
+ " ("
+ KEY_PI_ID + " integer primary key, "
+ KEY_PI_NUMBER + " integer, "
+ KEY_SMS_ID + " integer, "
+ KEY_TIME + " integer, "
+ KEY_ACTION + " text);";
private final String DATABASE_CREATE_TEMPLATE_TABLE = "create table " + DATABASE_TEMPLATE_TABLE
+ " ("
+ KEY_TEMP_ID + " integer primary key autoincrement, "
+ KEY_TEMP_CONTENT + " text);";
private final String DATABASE_CREATE_GROUP_TABLE = "create table " + DATABASE_GROUP_TABLE
+ " ("
+ KEY_GROUP_ID + " integer primary key autoincrement, "
+ KEY_GROUP_NAME + " text);";
private final String DATABASE_CREATE_GROUP_CONTACT_RELATION = "create table " +DATABASE_GROUP_CONTACT_RELATION
+ " ("
+ KEY_RELATION_ID + " integer primary key autoincrement, "
+ KEY_GROUP_REL_ID + " integer, "
+ KEY_CONTACTS_ID + " integer);";
private final String DATABASE_CREATE_SPANS_TABLE = "create table " + DATABASE_SPANS_TABLE
+ " ("
+ KEY_SPAN_ID + " integer primary key autoincrement, "
+ KEY_SPAN_DN + " text, "
+ KEY_SPAN_TYPE + " integer, "
+ KEY_SPAN_ENTITY_ID + " integer, "
+ KEY_SPAN_SMS_ID + " integer);";
private final String DATABASE_CREATE_SPAN_GROUP_REL_TABLE = "create table " + DATABASE_SPAN_GROUP_REL_TABLE
+ " ("
+ KEY_SPAN_GRP_REL_ID + " integer primary key autoincrement, "
+ KEY_SPAN_GRP_REL_SPAN_ID + " integer, "
+ KEY_SPAN_GRP_REL_GRP_ID + " integer, "
+ KEY_SPAN_GRP_REL_GRP_TYPE + " integer);";
private final String DATABASE_CREATE_RECENTS_TABLE = "create table " + DATABASE_RECENTS_TABLE
+ " ("
+ KEY_RECENT_CONTACT_ID + " integer primary key autoincrement, "
+ KEY_RECENT_CONTACT_CONTACT_ID + " integer, "
+ KEY_RECENT_CONTACT_NUMBER + " text);";
private SQLiteDatabase db;
private final Context context;
private MyOpenHelper myDbHelper;
public DBAdapter(Context _context){
context = _context;
myDbHelper = new MyOpenHelper(context);
}
public DBAdapter open() throws SQLException{
db = myDbHelper.getWritableDatabase();
return this;
}
public void close(){
db.close();
}
// functions-----------------------------------------------------------------------------------------
//------------------------functions for SMS table------------------------------
public Cursor fetchAllScheduled(){
Cursor cur = db.query(DATABASE_SMS_TABLE, new String[] {KEY_ID, KEY_GRPID, KEY_NUMBER, KEY_MESSAGE, KEY_TIME_MILLIS, KEY_DATE, KEY_SENT, KEY_DELIVER, KEY_MSG_PARTS, KEY_DRAFT}, KEY_SENT + "= 0", null, null, null, KEY_TIME_MILLIS);
return cur;
}
public Cursor fetchAllScheduledNoDraft(){
Cursor cur = db.query(DATABASE_SMS_TABLE, new String[] {KEY_ID, KEY_GRPID, KEY_NUMBER, KEY_MESSAGE, KEY_TIME_MILLIS, KEY_DATE, KEY_SENT, KEY_DELIVER, KEY_MSG_PARTS, KEY_DRAFT}, KEY_SENT + "= 0 AND " + KEY_DRAFT + "=0 AND " + KEY_OPERATED + "=0", null, null, null, KEY_TIME_MILLIS);
return cur;
}
public Cursor fetchAllSent(){
Cursor cur = db.query(DATABASE_SMS_TABLE, new String[] {KEY_ID, KEY_GRPID, KEY_NUMBER, KEY_MESSAGE, KEY_DATE, KEY_TIME_MILLIS, KEY_SENT, KEY_DELIVER, KEY_MSG_PARTS, KEY_S_MILLIS, KEY_D_MILLIS}, KEY_OPERATED + "=1", null, null, null, KEY_TIME_MILLIS);
return cur;
}
public Cursor fetchAllDrafts(){
Cursor cur = db.query(DATABASE_SMS_TABLE, new String[] {KEY_ID, KEY_GRPID, KEY_NUMBER, KEY_MESSAGE, KEY_TIME_MILLIS, KEY_DATE, KEY_SENT, KEY_DELIVER, KEY_MSG_PARTS, KEY_DRAFT}, KEY_DRAFT + "= 1", null, null, null, KEY_TIME_MILLIS);
return cur;
}
public Cursor fetchRemainingScheduled(){
Cursor cur = db.query(DATABASE_SMS_TABLE, new String[] {KEY_ID, KEY_GRPID, KEY_NUMBER, KEY_MESSAGE, KEY_TIME_MILLIS, KEY_DATE, KEY_SENT, KEY_DELIVER, KEY_MSG_PARTS}, KEY_OPERATED + "=0 AND " + KEY_DRAFT + "=0"/* + KEY_MESSAGE + " NOT LIKE ' '"*/ , null, null, null, KEY_TIME_MILLIS);
return cur;
}
public Cursor fetchSmsDetails(long id){
Cursor cur = db.query(DATABASE_SMS_TABLE, new String[] {KEY_ID, KEY_GRPID, KEY_NUMBER, KEY_MESSAGE, KEY_DATE, KEY_SENT, KEY_DELIVER, KEY_MSG_PARTS, KEY_TIME_MILLIS, KEY_DRAFT}, KEY_ID + "=" + id, null, null, null, null);
return cur;
}
public long scheduleSms(String number, String content, String date, int parts, long group_id, long timeInMilis){
ContentValues addValues = new ContentValues();
addValues.put(KEY_NUMBER, number);
addValues.put(KEY_MESSAGE, content);
addValues.put(KEY_DATE, date);
addValues.put(KEY_TIME_MILLIS, timeInMilis);
addValues.put(KEY_SENT, 0);
addValues.put(KEY_DELIVER, 0);
addValues.put(KEY_MSG_PARTS, parts);
addValues.put(KEY_GRPID, group_id);
addValues.put(KEY_S_MILLIS, -1);
addValues.put(KEY_D_MILLIS, -1);
return db.insert(DATABASE_SMS_TABLE, null, addValues);
}
public void setAsDraft(long smsId){
ContentValues cv = new ContentValues();
cv.put(KEY_DRAFT, 1);
db.update(DATABASE_SMS_TABLE, cv, KEY_ID + "=" + smsId, null);
}
public int getNextGroupId(){
cur = db.query(DATABASE_SMS_TABLE, new String[] {KEY_GRPID}, null, null, null, null, KEY_GRPID + " ASC");
if(cur.moveToFirst()){
cur.moveToLast();
return cur.getInt(cur.getColumnIndex(KEY_GRPID)) + 1;
}else{
return 0;
}
}
public void makeOperated(long id){
ContentValues cv = new ContentValues();
cv.put(KEY_OPERATED, 1);
db.update(DATABASE_SMS_TABLE, cv, KEY_ID + "=" + id, null);
}
private int getSent(long id){
Cursor cur = db.query(DATABASE_SMS_TABLE, new String[] {KEY_SENT}, KEY_ID + "=" + id, null, null, null, null);
if(cur.moveToFirst())
return cur.getInt(cur.getColumnIndex(KEY_SENT));
else
return 0;
}
public boolean increaseSent(long id){
int sent = getSent(id);
ContentValues sentValue = new ContentValues();
sentValue.put(KEY_SENT, sent + 1);
try{
db.update(DATABASE_SMS_TABLE, sentValue, KEY_ID + "=" + id, null);
Cursor cur = db.query(DATABASE_SMS_TABLE, new String[] {KEY_SENT}, KEY_ID + "=" + id, null, null, null, null);
int sentval = 0;
if(cur.moveToFirst()){
sentval = cur.getInt(cur.getColumnIndex("sent"));
}
cur = db.query(DATABASE_SMS_TABLE, new String[] {KEY_MSG_PARTS}, KEY_ID + "=" + id, null, null, null, null);
cur.moveToFirst();
int parts = cur.getInt(cur.getColumnIndex(KEY_MSG_PARTS));
if (sentval == parts){
ContentValues sentTimeSaver = new ContentValues();
sentTimeSaver.put(KEY_S_MILLIS, System.currentTimeMillis());
db.update(DATABASE_SMS_TABLE, sentTimeSaver, KEY_ID + "=" + id, null);
}
return true;
}catch(SQLiteException ex){
return false;
}
}
public boolean checkSent(long id){
Cursor cur = db.query(DATABASE_SMS_TABLE, new String[] {KEY_SENT, KEY_MSG_PARTS}, KEY_ID + "=" + id, null, null, null, null);
return ((cur.getInt(cur.getColumnIndex(KEY_SENT)) == cur.getInt(cur.getColumnIndex(KEY_MSG_PARTS))));
}
public boolean removeAllDelivered(){
try{
db.delete(DATABASE_SMS_TABLE, KEY_DELIVER + "=" + KEY_MSG_PARTS, null);
return true;
}catch(SQLiteException ex){
return false;
}
}
public ArrayList<Long> getIds(Long grp){
ArrayList<Long> ids = new ArrayList<Long>();
Cursor cur = db.query(DATABASE_SMS_TABLE, new String[] {KEY_ID}, KEY_GRPID + "=" + grp, null, null, null, null);
if(cur.moveToFirst()){
do{
ids.add(cur.getLong(cur.getColumnIndex(KEY_ID)));
}while(cur.moveToNext());
}
return ids;
}
public void deleteSms(long id, Context context){
if(getCurrentPiId()==id){
Cursor cur = getPiDetails();
cur.moveToFirst();
Intent intent = new Intent(context, SMSHandleReceiver.class);
intent.setAction(Constants.PRIVATE_SMS_ACTION);
PendingIntent pi = PendingIntent.getBroadcast(context, cur.getInt(cur.getColumnIndex(KEY_PI_NUMBER)), intent, PendingIntent.FLAG_CANCEL_CURRENT);
pi.cancel();
deleteSpan(id);
db.delete(DATABASE_SMS_TABLE, KEY_ID + "=" + id, null);
Cursor cur2 = fetchRemainingScheduled();
Log.d("cursor2 size : " + cur2.getCount());
if(cur2.moveToFirst()){
intent.setAction(Constants.PRIVATE_SMS_ACTION);
intent.putExtra("ID", cur2.getString(cur2.getColumnIndex(KEY_ID)));
intent.putExtra("NUMBER", cur2.getString(cur2.getColumnIndex(KEY_NUMBER)));
intent.putExtra("MESSAGE", cur2.getString(cur2.getColumnIndex(KEY_MESSAGE)));
Random rand = new Random();
int piNumber = rand.nextInt();
pi = PendingIntent.getBroadcast(context, piNumber, intent, PendingIntent.FLAG_UPDATE_CURRENT);
updatePi(piNumber, cur2.getLong(cur2.getColumnIndex(KEY_ID)), cur2.getLong(cur2.getColumnIndex(KEY_TIME_MILLIS)));
AlarmManager alarmManager = (AlarmManager) context.getSystemService(context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, cur2.getLong(cur2.getColumnIndex(KEY_TIME_MILLIS)), pi);
}else{
updatePi(0, -1, -1);
}
}else{
deleteSpan(id);
db.delete(DATABASE_SMS_TABLE, KEY_ID + "=" + id, null);
}
}
private int getDelivers(long id){
Cursor cur = db.query(DATABASE_SMS_TABLE, new String[] {KEY_DELIVER}, KEY_ID + "=" + id, null, null, null, null);
if(cur.moveToFirst())
return cur.getInt(cur.getColumnIndex(KEY_DELIVER));
else
return 0;
}
public boolean increaseDeliver(long id){
int deliver = getDelivers(id);
ContentValues deliverValue = new ContentValues();
deliverValue.put(KEY_DELIVER, deliver + 1);
try{
db.update(DATABASE_SMS_TABLE, deliverValue, KEY_ID + "=" + id, null);
if(checkDeliver(id)){
ContentValues deliverTimeSaver = new ContentValues();
deliverTimeSaver.put(KEY_D_MILLIS, System.currentTimeMillis());
db.update(DATABASE_SMS_TABLE, deliverTimeSaver, KEY_ID + "=" + id, null);
}
return true;
}catch(SQLiteException ex){
return false;
}
}
public boolean checkDeliver(long id){
Cursor cur = db.query(DATABASE_SMS_TABLE, new String[] {KEY_DELIVER, KEY_MSG_PARTS}, KEY_ID + "=" + id, null, null, null, null);
cur.moveToFirst();
boolean bool = ((cur.getInt(cur.getColumnIndex(KEY_DELIVER))) == (cur.getInt(cur.getColumnIndex(KEY_MSG_PARTS))));
return bool;
}
public long getSentDate(long id){
Cursor cur = db.query(DATABASE_SMS_TABLE, new String[] {KEY_S_MILLIS}, KEY_ID + "=" + id, null, null, null, null);
cur.moveToFirst();
return cur.getLong(cur.getColumnIndex(KEY_S_MILLIS));
}
public long getDeliveryDate(long id){
Cursor cur = db.query(DATABASE_SMS_TABLE, new String[] {KEY_D_MILLIS}, KEY_ID + "=" + id, null, null, null, null);
cur.moveToFirst();
return cur.getLong(cur.getColumnIndex(KEY_D_MILLIS));
}
//--------------------------------------------------------end of functions for SMS table---------------
//--------------------------------------functions for Pending Intent Table -----------------------------------------
public Cursor getPiDetails(){
return db.query(DATABASE_PI_TABLE, null, KEY_PI_ID + "= 1", null, null, null, null);
}
public long getCurrentPiId(){
Cursor cur = db.query(DATABASE_PI_TABLE, new String[] {KEY_SMS_ID}, KEY_PI_ID + "=1", null, null, null, null);
cur.moveToFirst();
long currentSmsId = cur.getLong(cur.getColumnIndex(KEY_SMS_ID));
return currentSmsId;
}
public void updatePi(long pi_number, long id, long time){
ContentValues cv = new ContentValues();
if(getCurrentPiId()!=-1){
Cursor cur = fetchSmsDetails(getCurrentPiId());
if(cur.moveToFirst()){
if(cur.getLong(cur.getColumnIndex(KEY_TIME_MILLIS))>System.currentTimeMillis()){
cv.put(KEY_OPERATED, 0);
db.update(DATABASE_SMS_TABLE, cv, KEY_ID + "=" + getCurrentPiId(), null);
}
}
}
cv.clear();
cv.put(KEY_PI_NUMBER, pi_number);
cv.put(KEY_SMS_ID, id);
cv.put(KEY_TIME, time);
db.update(DATABASE_PI_TABLE, cv, KEY_PI_ID + "= 1", null);
}
public long getCurrentPiFiretime(){
Cursor cur = db.query(DATABASE_PI_TABLE, new String[] {KEY_TIME}, KEY_PI_ID + "= 1", null, null, null, null);
cur.moveToFirst();
long currentPiFireTime = cur.getLong(cur.getColumnIndex(KEY_TIME));
return currentPiFireTime;
}
//--------------------------------------------------------end of functions for Pending Intent table---------
//-------------------------functions for template table---------------------------
public Cursor fetchAllTemplates(){
Cursor cur = db.query(DATABASE_TEMPLATE_TABLE, new String[] {KEY_TEMP_CONTENT, KEY_TEMP_ID}, null, null, null, null, null);
Log.d(cur.getCount()+" ui");
return cur;
}
public long addTemplate(String template){
ContentValues addTemplateValues = new ContentValues();
addTemplateValues.put(KEY_TEMP_CONTENT, template);
try{
long newId = db.insert(DATABASE_TEMPLATE_TABLE, null, addTemplateValues);
return newId;
}catch(SQLException sqe){
return 0;
}
}
public void editTemplate(long rowId, String template){
ContentValues cv = new ContentValues();
cv.put(KEY_TEMP_CONTENT, template);
db.update(DATABASE_TEMPLATE_TABLE, cv, KEY_TEMP_ID + "=" + rowId, null);
}
public boolean removeTemplate(long id){
try{
db.delete(DATABASE_TEMPLATE_TABLE, KEY_TEMP_ID + "=" + id, null);
return true;
}catch(SQLException sqe){
return false;
}
}
//-----------------------------------------------------end of functions for template table-----
//-----------------------------------functions for group table--------------------------------------
public Cursor fetchAllGroups(){
Cursor cur = db.query(DATABASE_GROUP_TABLE, null, null, null, null, null, null);
return cur;
}
public ArrayList<Long> fetchIdsForGroups(long groupId){
ArrayList<Long> ids = new ArrayList<Long>();
Cursor cur = db.query(DATABASE_GROUP_CONTACT_RELATION, new String[]{KEY_CONTACTS_ID}, KEY_GROUP_REL_ID + "=" + groupId, null, null, null, null);
if(cur.moveToFirst()){
do{
ids.add(cur.getLong(cur.getColumnIndex(KEY_CONTACTS_ID)));
}while(cur.moveToNext());
}
return ids;
}
public long createGroup(String name, ArrayList<Long> contactIds){
ContentValues cv = new ContentValues();
cv.put(KEY_GROUP_NAME, name);
long grpid = db.insert(DATABASE_GROUP_TABLE, null, cv);
for(int i = 0; i< contactIds.size(); i++){
addContactToGroup(contactIds.get(i), grpid);
}
return grpid;
}
public void addContactToGroup(long contactId, long groupId){
ContentValues cv = new ContentValues();
cv.put(KEY_GROUP_REL_ID, groupId);
cv.put(KEY_CONTACTS_ID, contactId);
db.insert(DATABASE_GROUP_CONTACT_RELATION, null, cv);
}
public void removeContactFromGroup(long contactId, long groupId){
db.delete(DATABASE_GROUP_CONTACT_RELATION, KEY_GROUP_REL_ID + "=" + groupId + " AND " + KEY_CONTACTS_ID + "=" + contactId, null);
}
public void removeGroup(long groupId){
db.delete(DATABASE_GROUP_CONTACT_RELATION, KEY_GROUP_REL_ID + "=" + groupId, null);
db.delete(DATABASE_GROUP_TABLE, KEY_GROUP_ID + "=" + groupId, null);
}
public void setGroupName(String name, long groupId){
ContentValues cv = new ContentValues();
cv.put(KEY_GROUP_NAME, name);
db.update(DATABASE_GROUP_TABLE, cv, KEY_GROUP_ID + "=" + groupId, null);
}
//---------------------------------------------------------------end of functions for group table---------------------
//---------------------------functions for spans table---------------------------------
public Cursor fetchSpanForSms(long smsId){
Cursor cur = db.query(DATABASE_SPANS_TABLE, null, KEY_SPAN_SMS_ID + "=" + smsId, null, null, null, null);
return cur;
}
public long createSpan(String displayName, long entityId, int type, long smsId){
ContentValues cv = new ContentValues();
cv.put(KEY_SPAN_DN, displayName);
cv.put(KEY_SPAN_ENTITY_ID, entityId);
cv.put(KEY_SPAN_TYPE, type);
cv.put(KEY_SPAN_SMS_ID, smsId);
long spanId = db.insert(DATABASE_SPANS_TABLE, null, cv);
return spanId;
}
public void deleteSpan(long smsId){
Cursor spanIds = db.query(DATABASE_SPANS_TABLE, new String []{KEY_SPAN_ID}, KEY_SPAN_SMS_ID + "=" + smsId, null, null, null, null);
if(spanIds.moveToFirst()){
do{
deleteSpanGroupRelsForSpan(spanIds.getLong(spanIds.getColumnIndex(KEY_SPAN_ID)));
}while(spanIds.moveToNext());
}
db.delete(DATABASE_SPANS_TABLE, KEY_SPAN_SMS_ID + "=" + smsId, null);
}
//---------------------------------------------------------------end of functions for spans table--------------
//--------------------------------functions for span-group-relation table--------------------------------
//*** Table to log the relation between added spans and groups ***
public ArrayList<Long> fetchGroupsForSpan(long spanId){
Cursor cur = db.query(DATABASE_SPAN_GROUP_REL_TABLE, new String[]{KEY_SPAN_GRP_REL_GRP_ID}, KEY_SPAN_GRP_REL_SPAN_ID + "=" + spanId, null, null, null, null);
ArrayList<Long> groupIds = new ArrayList<Long>();
if(cur.moveToFirst()){
do{
groupIds.add(cur.getLong(cur.getColumnIndex(KEY_SPAN_GRP_REL_GRP_ID)));
}while(cur.moveToNext());
}
return groupIds;
}
public ArrayList<Integer> fetchGroupTypesForSpan(long spanId){
Cursor cur = db.query(DATABASE_SPAN_GROUP_REL_TABLE, new String[]{KEY_SPAN_GRP_REL_GRP_TYPE}, KEY_SPAN_GRP_REL_SPAN_ID + "=" + spanId, null, null, null, null);
ArrayList<Integer> groupTypes = new ArrayList<Integer>();
if(cur.moveToFirst()){
do{
groupTypes.add(cur.getInt(cur.getColumnIndex(KEY_SPAN_GRP_REL_GRP_TYPE)));
}while(cur.moveToNext());
}
return groupTypes;
}
public ArrayList<Long> fetchSpansForGroup(long groupId, int type){
Cursor cur = db.query(DATABASE_SPAN_GROUP_REL_TABLE, new String[]{KEY_SPAN_GRP_REL_SPAN_ID}, KEY_SPAN_GRP_REL_GRP_ID + "=" + groupId + " AND " + KEY_SPAN_GRP_REL_GRP_TYPE + "=" + type, null, null, null, null);
ArrayList<Long> spanIds = new ArrayList<Long>();
if(cur.moveToFirst()){
do{
spanIds.add(cur.getLong(cur.getColumnIndex(KEY_SPAN_GRP_REL_SPAN_ID)));
}while(cur.moveToNext());
}
return spanIds;
}
public void addSpanGroupRel(long spanId, long groupId, int type){
ContentValues cv = new ContentValues();
cv.put(KEY_SPAN_GRP_REL_SPAN_ID, spanId);
cv.put(KEY_SPAN_GRP_REL_GRP_ID, groupId);
cv.put(KEY_SPAN_GRP_REL_GRP_TYPE, type);
db.insert(DATABASE_SPAN_GROUP_REL_TABLE, null, cv);
}
public void deleteSpanGroupRelsForSpan(long spanId){
db.delete(DATABASE_SPAN_GROUP_REL_TABLE, KEY_SPAN_GRP_REL_SPAN_ID + "=" + spanId, null);
}
public void deleteSpanGroupRel(long spanId, long groupId, int type){
db.delete(DATABASE_SPAN_GROUP_REL_TABLE, KEY_SPAN_GRP_REL_SPAN_ID + "=" + spanId + " AND " + KEY_SPAN_GRP_REL_GRP_ID + "=" + groupId + " AND " + KEY_SPAN_GRP_REL_GRP_TYPE + "=" + type, null);
}
//----------------------------------------------end of functions for span-group-relation table----------------
//----------------------------functions for recents table----------------------------------
public void addRecentContact(long contactId, String contactNumber){
Cursor cur = db.query(DATABASE_RECENTS_TABLE, new String[]{KEY_RECENT_CONTACT_ID, KEY_RECENT_CONTACT_CONTACT_ID, KEY_RECENT_CONTACT_NUMBER}, null, null, null, null, KEY_RECENT_CONTACT_ID);
boolean contactExist = false;
if(cur.moveToFirst()){
do{
if((cur.getLong(cur.getColumnIndex(KEY_RECENT_CONTACT_CONTACT_ID)) == contactId)){// || (cur.getString(cur.getColumnIndex(KEY_RECENT_CONTACT_NUMBER)).equals(contactNumber))){
contactExist = true;
break;
}
if(((cur.getLong(cur.getColumnIndex(KEY_RECENT_CONTACT_CONTACT_ID))) == -1) && (cur.getString(cur.getColumnIndex(KEY_RECENT_CONTACT_NUMBER)).equals(contactNumber))){
contactExist = true;
break;
}
}while(cur.moveToNext());
}
if(!contactExist){
ContentValues cv = new ContentValues();
cv.put(KEY_RECENT_CONTACT_CONTACT_ID, contactId);
cv.put(KEY_RECENT_CONTACT_NUMBER, contactNumber);
if(cur.getCount()<20){
db.insert(DATABASE_RECENTS_TABLE, null, cv);
}else{
cur.moveToFirst();
long idToDelete = cur.getLong(cur.getColumnIndex(KEY_RECENT_CONTACT_ID));
db.delete(DATABASE_RECENTS_TABLE, KEY_RECENT_CONTACT_ID + "=" + idToDelete, null);
db.insert(DATABASE_RECENTS_TABLE, null, cv);
}
}
}
public Cursor fetchAllRecents(){
Cursor cur = db.query(DATABASE_RECENTS_TABLE, null, null, null, null, null, KEY_RECENT_CONTACT_ID + " DESC");
return cur;
}
//----------------------------------------------end of functions for recents table-----------------
//----------------------------------------------------------end of functions--------------------------------
public class MyOpenHelper extends SQLiteOpenHelper{
MyOpenHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE_SMS_TABLE);
db.execSQL(DATABASE_CREATE_TEMPLATE_TABLE);
db.execSQL(DATABASE_CREATE_PI_TABLE);
db.execSQL(DATABASE_CREATE_GROUP_TABLE);
db.execSQL(DATABASE_CREATE_GROUP_CONTACT_RELATION);
db.execSQL(DATABASE_CREATE_SPANS_TABLE);
db.execSQL(DATABASE_CREATE_SPAN_GROUP_REL_TABLE);
db.execSQL(DATABASE_CREATE_RECENTS_TABLE);
//-------Setting initial content of Pending Intent-------
ContentValues initialPi = new ContentValues();
initialPi.put(KEY_PI_ID, 1);
initialPi.put(KEY_PI_NUMBER, 0);
initialPi.put(KEY_SMS_ID, -1);
initialPi.put(KEY_TIME, -1);
initialPi.put(KEY_ACTION, "");
db.insert(DATABASE_PI_TABLE, null, initialPi);
//-------------------------------------------------------
//-------Setting default templates for the app-----------
ContentValues initialTemplates = new ContentValues();
initialTemplates.put(KEY_TEMP_CONTENT, "I'm in a meeting. I'll contact you later.");
db.insert(DATABASE_TEMPLATE_TABLE, null, initialTemplates);
initialTemplates.put(KEY_TEMP_CONTENT, "I'm driving now. I'll contact you later.");
db.insert(DATABASE_TEMPLATE_TABLE, null, initialTemplates);
initialTemplates.put(KEY_TEMP_CONTENT, "I'm busy. Will give you a call later.");
db.insert(DATABASE_TEMPLATE_TABLE, null, initialTemplates);
initialTemplates.put(KEY_TEMP_CONTENT, "Sorry, I'm going to be late.");
db.insert(DATABASE_TEMPLATE_TABLE, null, initialTemplates);
initialTemplates.put(KEY_TEMP_CONTENT, "Have a nice day!");
db.insert(DATABASE_TEMPLATE_TABLE, null, initialTemplates);
//---------------------------------------------------------
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
}
} | src/com/vinsol/sms_scheduler/DBAdapter.java | package com.vinsol.sms_scheduler;
import java.util.ArrayList;
import java.util.Random;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import com.vinsol.sms_scheduler.receivers.SMSHandleReceiver;
import com.vinsol.sms_scheduler.utils.Log;
public class DBAdapter {
private final String DATABASE_NAME = "smsDatabase";
private final String DATABASE_SMS_TABLE = "smsTable";
private final String DATABASE_PI_TABLE = "piTable";
private final String DATABASE_TEMPLATE_TABLE = "templateTable";
private final String DATABASE_GROUP_TABLE = "groupTable";
private final String DATABASE_GROUP_CONTACT_RELATION = "groupContactRelation";
private final String DATABASE_SPANS_TABLE = "spanTable";
private final String DATABASE_SPAN_GROUP_REL_TABLE = "span_grp_rel_table";
private final String DATABASE_RECENTS_TABLE = "recents_table";
private final int DATABASE_VERSION = 1;
Cursor cur;
//---------------------------static keys for columns---------------------------------------
//----------------keys for SMS table--------------------------
public static final String KEY_ID = "_id";
public static final String KEY_NUMBER = "number";
public static final String KEY_GRPID = "group_id";
public static final String KEY_MESSAGE = "message";
public static final String KEY_DATE = "date";
public static final String KEY_TIME_MILLIS = "time_millis";
public static final String KEY_SENT = "sent";
public static final String KEY_DELIVER = "deliver";
public static final String KEY_MSG_PARTS = "msg_parts";
public static final String KEY_S_MILLIS = "sent_milis";
public static final String KEY_D_MILLIS = "deliver_milis";
public static final String KEY_OPERATED = "operation_done";
public static final String KEY_DRAFT = "is_draft";
//--------------keys for PI table---------------------------
public static final String KEY_PI_ID = "_id";
public static final String KEY_PI_NUMBER = "pi_number";
public static final String KEY_SMS_ID = "sms_id";
public static final String KEY_TIME = "time";
public static final String KEY_ACTION = "action";
//----------------keys for template table---------------------
public static final String KEY_TEMP_ID = "_id";
public static final String KEY_TEMP_CONTENT = "content";
//-----------------keys for group table-----------------------
public static final String KEY_GROUP_ID = "_id";
public static final String KEY_GROUP_NAME = "group_name";
//----------------keys for group contacts relation----------------
public static final String KEY_RELATION_ID = "_id";
public static final String KEY_GROUP_REL_ID = "group_rel_id";
public static final String KEY_CONTACTS_ID = "contacts_id";
//-----------------keys for spans table----------------------------
public static final String KEY_SPAN_ID = "_id";
public static final String KEY_SPAN_DN = "span_display_name";
public static final String KEY_SPAN_TYPE = "span_type";
public static final String KEY_SPAN_ENTITY_ID = "span_entity_id";
public static final String KEY_SPAN_SMS_ID = "span_sms_id";
//-------------------keys for span-groupId relation--------------------
public static final String KEY_SPAN_GRP_REL_ID = "_id";
public static final String KEY_SPAN_GRP_REL_SPAN_ID = "span_grp_rel_span_id";
public static final String KEY_SPAN_GRP_REL_GRP_ID = "span_grp_rel_grp_id";
public static final String KEY_SPAN_GRP_REL_GRP_TYPE = "span_grp_rel_grp_type";
//------------------keys for recents table-------------------------
public static final String KEY_RECENT_CONTACT_ID = "_id";
public static final String KEY_RECENT_CONTACT_CONTACT_ID = "contact_id";
public static final String KEY_RECENT_CONTACT_NUMBER = "contact_number";
//------------------------------------------------------------------end of static keys defs-------
//SQL to open or create a database
private final String DATABASE_CREATE_SMS_TABLE = "create table " +
DATABASE_SMS_TABLE + " (" + KEY_ID + " integer primary key autoincrement, " + KEY_GRPID + " integer, " +
KEY_NUMBER + " text not null, " + KEY_MESSAGE + " text, " + KEY_DATE + " text, " + KEY_TIME_MILLIS + " long, "
+ KEY_SENT + " integer default 0, "+ KEY_DELIVER + " integer default 0, " + KEY_MSG_PARTS + " integer default 0, "
+ KEY_S_MILLIS + " integer, " + KEY_D_MILLIS + " integer, " + KEY_OPERATED + " integer default 0, "
+ KEY_DRAFT + " integer default 0);";
private final String DATABASE_CREATE_PI_TABLE = "create table " +
DATABASE_PI_TABLE + " (" + KEY_PI_ID + " integer primary key, " + KEY_PI_NUMBER + " integer, " +
KEY_SMS_ID + " integer, " + KEY_TIME + " integer, " + KEY_ACTION + " text);";
private final String DATABASE_CREATE_TEMPLATE_TABLE = "create table " +
DATABASE_TEMPLATE_TABLE + " (" + KEY_TEMP_ID + " integer primary key autoincrement, " +
KEY_TEMP_CONTENT + " text);";
private final String DATABASE_CREATE_GROUP_TABLE = "create table " +
DATABASE_GROUP_TABLE + " (" + KEY_GROUP_ID + " integer primary key autoincrement, " +
KEY_GROUP_NAME + " text);";
private final String DATABASE_CREATE_GROUP_CONTACT_RELATION = "create table " +
DATABASE_GROUP_CONTACT_RELATION + " (" + KEY_RELATION_ID + " integer primary key autoincrement, " +
KEY_GROUP_REL_ID + " integer, " + KEY_CONTACTS_ID + " integer);";
private final String DATABASE_CREATE_SPANS_TABLE = "create table " +
DATABASE_SPANS_TABLE + " (" + KEY_SPAN_ID + " integer primary key autoincrement, " +
KEY_SPAN_DN + " text, " + KEY_SPAN_TYPE + " integer, " + KEY_SPAN_ENTITY_ID + " integer, " +
KEY_SPAN_SMS_ID + " integer);";
private final String DATABASE_CREATE_SPAN_GROUP_REL_TABLE = "create table " +
DATABASE_SPAN_GROUP_REL_TABLE + " (" + KEY_SPAN_GRP_REL_ID + " integer primary key autoincrement, " +
KEY_SPAN_GRP_REL_SPAN_ID + " integer, " + KEY_SPAN_GRP_REL_GRP_ID + " integer, " +
KEY_SPAN_GRP_REL_GRP_TYPE + " integer);";
private final String DATABASE_CREATE_RECENTS_TABLE = "create table " +
DATABASE_RECENTS_TABLE + " (" + KEY_RECENT_CONTACT_ID + " integer primary key autoincrement, " +
KEY_RECENT_CONTACT_CONTACT_ID + " integer, " + KEY_RECENT_CONTACT_NUMBER + " text);";
private SQLiteDatabase db;
private final Context context;
private MyOpenHelper myDbHelper;
public DBAdapter(Context _context){
context = _context;
myDbHelper = new MyOpenHelper(context);
}
public DBAdapter open() throws SQLException{
db = myDbHelper.getWritableDatabase();
return this;
}
public void close(){
db.close();
}
// functions-----------------------------------------------------------------------------------------
//------------------------functions for SMS table------------------------------
public Cursor fetchAllScheduled(){
Cursor cur = db.query(DATABASE_SMS_TABLE, new String[] {KEY_ID, KEY_GRPID, KEY_NUMBER, KEY_MESSAGE, KEY_TIME_MILLIS, KEY_DATE, KEY_SENT, KEY_DELIVER, KEY_MSG_PARTS, KEY_DRAFT}, KEY_SENT + "= 0", null, null, null, KEY_TIME_MILLIS);
return cur;
}
public Cursor fetchAllScheduledNoDraft(){
Cursor cur = db.query(DATABASE_SMS_TABLE, new String[] {KEY_ID, KEY_GRPID, KEY_NUMBER, KEY_MESSAGE, KEY_TIME_MILLIS, KEY_DATE, KEY_SENT, KEY_DELIVER, KEY_MSG_PARTS, KEY_DRAFT}, KEY_SENT + "= 0 AND " + KEY_DRAFT + "=0 AND " + KEY_OPERATED + "=0", null, null, null, KEY_TIME_MILLIS);
return cur;
}
public Cursor fetchAllSent(){
Cursor cur = db.query(DATABASE_SMS_TABLE, new String[] {KEY_ID, KEY_GRPID, KEY_NUMBER, KEY_MESSAGE, KEY_DATE, KEY_TIME_MILLIS, KEY_SENT, KEY_DELIVER, KEY_MSG_PARTS, KEY_S_MILLIS, KEY_D_MILLIS}, KEY_OPERATED + "=1", null, null, null, KEY_TIME_MILLIS);
return cur;
}
public Cursor fetchAllDrafts(){
Cursor cur = db.query(DATABASE_SMS_TABLE, new String[] {KEY_ID, KEY_GRPID, KEY_NUMBER, KEY_MESSAGE, KEY_TIME_MILLIS, KEY_DATE, KEY_SENT, KEY_DELIVER, KEY_MSG_PARTS, KEY_DRAFT}, KEY_DRAFT + "= 1", null, null, null, KEY_TIME_MILLIS);
return cur;
}
public Cursor fetchRemainingScheduled(){
Cursor cur = db.query(DATABASE_SMS_TABLE, new String[] {KEY_ID, KEY_GRPID, KEY_NUMBER, KEY_MESSAGE, KEY_TIME_MILLIS, KEY_DATE, KEY_SENT, KEY_DELIVER, KEY_MSG_PARTS}, KEY_OPERATED + "=0 AND " + KEY_DRAFT + "=0"/* + KEY_MESSAGE + " NOT LIKE ' '"*/ , null, null, null, KEY_TIME_MILLIS);
return cur;
}
public Cursor fetchSmsDetails(long id){
Cursor cur = db.query(DATABASE_SMS_TABLE, new String[] {KEY_ID, KEY_GRPID, KEY_NUMBER, KEY_MESSAGE, KEY_DATE, KEY_SENT, KEY_DELIVER, KEY_MSG_PARTS, KEY_TIME_MILLIS, KEY_DRAFT}, KEY_ID + "=" + id, null, null, null, null);
return cur;
}
public long scheduleSms(String number, String content, String date, int parts, long group_id, long timeInMilis){
ContentValues addValues = new ContentValues();
addValues.put(KEY_NUMBER, number);
addValues.put(KEY_MESSAGE, content);
addValues.put(KEY_DATE, date);
addValues.put(KEY_TIME_MILLIS, timeInMilis);
addValues.put(KEY_SENT, 0);
addValues.put(KEY_DELIVER, 0);
addValues.put(KEY_MSG_PARTS, parts);
addValues.put(KEY_GRPID, group_id);
addValues.put(KEY_S_MILLIS, -1);
addValues.put(KEY_D_MILLIS, -1);
return db.insert(DATABASE_SMS_TABLE, null, addValues);
}
public void setAsDraft(long smsId){
ContentValues cv = new ContentValues();
cv.put(KEY_DRAFT, 1);
db.update(DATABASE_SMS_TABLE, cv, KEY_ID + "=" + smsId, null);
}
public int getNextGroupId(){
cur = db.query(DATABASE_SMS_TABLE, new String[] {KEY_GRPID}, null, null, null, null, KEY_GRPID + " ASC");
if(cur.moveToFirst()){
cur.moveToLast();
return cur.getInt(cur.getColumnIndex(KEY_GRPID)) + 1;
}else{
return 0;
}
}
public void makeOperated(long id){
ContentValues cv = new ContentValues();
cv.put(KEY_OPERATED, 1);
db.update(DATABASE_SMS_TABLE, cv, KEY_ID + "=" + id, null);
}
private int getSent(long id){
Cursor cur = db.query(DATABASE_SMS_TABLE, new String[] {KEY_SENT}, KEY_ID + "=" + id, null, null, null, null);
if(cur.moveToFirst())
return cur.getInt(cur.getColumnIndex(KEY_SENT));
else
return 0;
}
public boolean increaseSent(long id){
int sent = getSent(id);
ContentValues sentValue = new ContentValues();
sentValue.put(KEY_SENT, sent + 1);
try{
db.update(DATABASE_SMS_TABLE, sentValue, KEY_ID + "=" + id, null);
Cursor cur = db.query(DATABASE_SMS_TABLE, new String[] {KEY_SENT}, KEY_ID + "=" + id, null, null, null, null);
int sentval = 0;
if(cur.moveToFirst()){
sentval = cur.getInt(cur.getColumnIndex("sent"));
}
cur = db.query(DATABASE_SMS_TABLE, new String[] {KEY_MSG_PARTS}, KEY_ID + "=" + id, null, null, null, null);
cur.moveToFirst();
int parts = cur.getInt(cur.getColumnIndex(KEY_MSG_PARTS));
if (sentval == parts){
ContentValues sentTimeSaver = new ContentValues();
sentTimeSaver.put(KEY_S_MILLIS, System.currentTimeMillis());
db.update(DATABASE_SMS_TABLE, sentTimeSaver, KEY_ID + "=" + id, null);
}
return true;
}catch(SQLiteException ex){
return false;
}
}
public boolean checkSent(long id){
Cursor cur = db.query(DATABASE_SMS_TABLE, new String[] {KEY_SENT, KEY_MSG_PARTS}, KEY_ID + "=" + id, null, null, null, null);
return ((cur.getInt(cur.getColumnIndex(KEY_SENT)) == cur.getInt(cur.getColumnIndex(KEY_MSG_PARTS))));
}
public boolean removeAllDelivered(){
try{
db.delete(DATABASE_SMS_TABLE, KEY_DELIVER + "=" + KEY_MSG_PARTS, null);
return true;
}catch(SQLiteException ex){
return false;
}
}
public ArrayList<Long> getIds(Long grp){
ArrayList<Long> ids = new ArrayList<Long>();
Cursor cur = db.query(DATABASE_SMS_TABLE, new String[] {KEY_ID}, KEY_GRPID + "=" + grp, null, null, null, null);
if(cur.moveToFirst()){
do{
ids.add(cur.getLong(cur.getColumnIndex(KEY_ID)));
}while(cur.moveToNext());
}
return ids;
}
public void deleteSms(long id, Context context){
if(getCurrentPiId()==id){
Cursor cur = getPiDetails();
cur.moveToFirst();
Intent intent = new Intent(context, SMSHandleReceiver.class);
intent.setAction(Constants.PRIVATE_SMS_ACTION);
PendingIntent pi = PendingIntent.getBroadcast(context, cur.getInt(cur.getColumnIndex(KEY_PI_NUMBER)), intent, PendingIntent.FLAG_CANCEL_CURRENT);
pi.cancel();
deleteSpan(id);
db.delete(DATABASE_SMS_TABLE, KEY_ID + "=" + id, null);
Cursor cur2 = fetchRemainingScheduled();
Log.d("cursor2 size : " + cur2.getCount());
if(cur2.moveToFirst()){
intent.setAction(Constants.PRIVATE_SMS_ACTION);
intent.putExtra("ID", cur2.getString(cur2.getColumnIndex(KEY_ID)));
intent.putExtra("NUMBER", cur2.getString(cur2.getColumnIndex(KEY_NUMBER)));
intent.putExtra("MESSAGE", cur2.getString(cur2.getColumnIndex(KEY_MESSAGE)));
Random rand = new Random();
int piNumber = rand.nextInt();
pi = PendingIntent.getBroadcast(context, piNumber, intent, PendingIntent.FLAG_UPDATE_CURRENT);
updatePi(piNumber, cur2.getLong(cur2.getColumnIndex(KEY_ID)), cur2.getLong(cur2.getColumnIndex(KEY_TIME_MILLIS)));
AlarmManager alarmManager = (AlarmManager) context.getSystemService(context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, cur2.getLong(cur2.getColumnIndex(KEY_TIME_MILLIS)), pi);
}else{
updatePi(0, -1, -1);
}
}else{
deleteSpan(id);
db.delete(DATABASE_SMS_TABLE, KEY_ID + "=" + id, null);
}
}
private int getDelivers(long id){
Cursor cur = db.query(DATABASE_SMS_TABLE, new String[] {KEY_DELIVER}, KEY_ID + "=" + id, null, null, null, null);
if(cur.moveToFirst())
return cur.getInt(cur.getColumnIndex(KEY_DELIVER));
else
return 0;
}
public boolean increaseDeliver(long id){
int deliver = getDelivers(id);
ContentValues deliverValue = new ContentValues();
deliverValue.put(KEY_DELIVER, deliver + 1);
try{
db.update(DATABASE_SMS_TABLE, deliverValue, KEY_ID + "=" + id, null);
if(checkDeliver(id)){
ContentValues deliverTimeSaver = new ContentValues();
deliverTimeSaver.put(KEY_D_MILLIS, System.currentTimeMillis());
db.update(DATABASE_SMS_TABLE, deliverTimeSaver, KEY_ID + "=" + id, null);
}
return true;
}catch(SQLiteException ex){
return false;
}
}
public boolean checkDeliver(long id){
Cursor cur = db.query(DATABASE_SMS_TABLE, new String[] {KEY_DELIVER, KEY_MSG_PARTS}, KEY_ID + "=" + id, null, null, null, null);
cur.moveToFirst();
boolean bool = ((cur.getInt(cur.getColumnIndex(KEY_DELIVER))) == (cur.getInt(cur.getColumnIndex(KEY_MSG_PARTS))));
return bool;
}
public long getSentDate(long id){
Cursor cur = db.query(DATABASE_SMS_TABLE, new String[] {KEY_S_MILLIS}, KEY_ID + "=" + id, null, null, null, null);
cur.moveToFirst();
return cur.getLong(cur.getColumnIndex(KEY_S_MILLIS));
}
public long getDeliveryDate(long id){
Cursor cur = db.query(DATABASE_SMS_TABLE, new String[] {KEY_D_MILLIS}, KEY_ID + "=" + id, null, null, null, null);
cur.moveToFirst();
return cur.getLong(cur.getColumnIndex(KEY_D_MILLIS));
}
//--------------------------------------------------------end of functions for SMS table---------------
//--------------------------------------functions for Pending Intent Table -----------------------------------------
public Cursor getPiDetails(){
return db.query(DATABASE_PI_TABLE, null, KEY_PI_ID + "= 1", null, null, null, null);
}
public long getCurrentPiId(){
Cursor cur = db.query(DATABASE_PI_TABLE, new String[] {KEY_SMS_ID}, KEY_PI_ID + "=1", null, null, null, null);
cur.moveToFirst();
long currentSmsId = cur.getLong(cur.getColumnIndex(KEY_SMS_ID));
return currentSmsId;
}
public void updatePi(long pi_number, long id, long time){
ContentValues cv = new ContentValues();
if(getCurrentPiId()!=-1){
Cursor cur = fetchSmsDetails(getCurrentPiId());
if(cur.moveToFirst()){
if(cur.getLong(cur.getColumnIndex(KEY_TIME_MILLIS))>System.currentTimeMillis()){
cv.put(KEY_OPERATED, 0);
db.update(DATABASE_SMS_TABLE, cv, KEY_ID + "=" + getCurrentPiId(), null);
}
}
}
cv.clear();
cv.put(KEY_PI_NUMBER, pi_number);
cv.put(KEY_SMS_ID, id);
cv.put(KEY_TIME, time);
db.update(DATABASE_PI_TABLE, cv, KEY_PI_ID + "= 1", null);
}
public long getCurrentPiFiretime(){
Cursor cur = db.query(DATABASE_PI_TABLE, new String[] {KEY_TIME}, KEY_PI_ID + "= 1", null, null, null, null);
cur.moveToFirst();
long currentPiFireTime = cur.getLong(cur.getColumnIndex(KEY_TIME));
return currentPiFireTime;
}
//--------------------------------------------------------end of functions for Pending Intent table---------
//-------------------------functions for template table---------------------------
public Cursor fetchAllTemplates(){
Cursor cur = db.query(DATABASE_TEMPLATE_TABLE, new String[] {KEY_TEMP_CONTENT, KEY_TEMP_ID}, null, null, null, null, null);
Log.d(cur.getCount()+" ui");
return cur;
}
public long addTemplate(String template){
ContentValues addTemplateValues = new ContentValues();
addTemplateValues.put(KEY_TEMP_CONTENT, template);
try{
long newId = db.insert(DATABASE_TEMPLATE_TABLE, null, addTemplateValues);
return newId;
}catch(SQLException sqe){
return 0;
}
}
public void editTemplate(long rowId, String template){
ContentValues cv = new ContentValues();
cv.put(KEY_TEMP_CONTENT, template);
db.update(DATABASE_TEMPLATE_TABLE, cv, KEY_TEMP_ID + "=" + rowId, null);
}
public boolean removeTemplate(long id){
try{
db.delete(DATABASE_TEMPLATE_TABLE, KEY_TEMP_ID + "=" + id, null);
return true;
}catch(SQLException sqe){
return false;
}
}
//-----------------------------------------------------end of functions for template table-----
//-----------------------------------functions for group table--------------------------------------
public Cursor fetchAllGroups(){
Cursor cur = db.query(DATABASE_GROUP_TABLE, null, null, null, null, null, null);
return cur;
}
public ArrayList<Long> fetchIdsForGroups(long groupId){
ArrayList<Long> ids = new ArrayList<Long>();
Cursor cur = db.query(DATABASE_GROUP_CONTACT_RELATION, new String[]{KEY_CONTACTS_ID}, KEY_GROUP_REL_ID + "=" + groupId, null, null, null, null);
if(cur.moveToFirst()){
do{
ids.add(cur.getLong(cur.getColumnIndex(KEY_CONTACTS_ID)));
}while(cur.moveToNext());
}
return ids;
}
public long createGroup(String name, ArrayList<Long> contactIds){
ContentValues cv = new ContentValues();
cv.put(KEY_GROUP_NAME, name);
long grpid = db.insert(DATABASE_GROUP_TABLE, null, cv);
for(int i = 0; i< contactIds.size(); i++){
addContactToGroup(contactIds.get(i), grpid);
}
return grpid;
}
public void addContactToGroup(long contactId, long groupId){
ContentValues cv = new ContentValues();
cv.put(KEY_GROUP_REL_ID, groupId);
cv.put(KEY_CONTACTS_ID, contactId);
db.insert(DATABASE_GROUP_CONTACT_RELATION, null, cv);
}
public void removeContactFromGroup(long contactId, long groupId){
db.delete(DATABASE_GROUP_CONTACT_RELATION, KEY_GROUP_REL_ID + "=" + groupId + " AND " + KEY_CONTACTS_ID + "=" + contactId, null);
}
public void removeGroup(long groupId){
db.delete(DATABASE_GROUP_CONTACT_RELATION, KEY_GROUP_REL_ID + "=" + groupId, null);
db.delete(DATABASE_GROUP_TABLE, KEY_GROUP_ID + "=" + groupId, null);
}
public void setGroupName(String name, long groupId){
ContentValues cv = new ContentValues();
cv.put(KEY_GROUP_NAME, name);
db.update(DATABASE_GROUP_TABLE, cv, KEY_GROUP_ID + "=" + groupId, null);
}
//---------------------------------------------------------------end of functions for group table---------------------
//---------------------------functions for spans table---------------------------------
public Cursor fetchSpanForSms(long smsId){
Cursor cur = db.query(DATABASE_SPANS_TABLE, null, KEY_SPAN_SMS_ID + "=" + smsId, null, null, null, null);
return cur;
}
public long createSpan(String displayName, long entityId, int type, long smsId){
ContentValues cv = new ContentValues();
cv.put(KEY_SPAN_DN, displayName);
cv.put(KEY_SPAN_ENTITY_ID, entityId);
cv.put(KEY_SPAN_TYPE, type);
cv.put(KEY_SPAN_SMS_ID, smsId);
long spanId = db.insert(DATABASE_SPANS_TABLE, null, cv);
return spanId;
}
public void deleteSpan(long smsId){
Cursor spanIds = db.query(DATABASE_SPANS_TABLE, new String []{KEY_SPAN_ID}, KEY_SPAN_SMS_ID + "=" + smsId, null, null, null, null);
if(spanIds.moveToFirst()){
do{
deleteSpanGroupRelsForSpan(spanIds.getLong(spanIds.getColumnIndex(KEY_SPAN_ID)));
}while(spanIds.moveToNext());
}
db.delete(DATABASE_SPANS_TABLE, KEY_SPAN_SMS_ID + "=" + smsId, null);
}
//---------------------------------------------------------------end of functions for spans table--------------
//--------------------------------functions for span-group-relation table--------------------------------
//*** Table to log the relation between added spans and groups ***
public ArrayList<Long> fetchGroupsForSpan(long spanId){
Cursor cur = db.query(DATABASE_SPAN_GROUP_REL_TABLE, new String[]{KEY_SPAN_GRP_REL_GRP_ID}, KEY_SPAN_GRP_REL_SPAN_ID + "=" + spanId, null, null, null, null);
ArrayList<Long> groupIds = new ArrayList<Long>();
if(cur.moveToFirst()){
do{
groupIds.add(cur.getLong(cur.getColumnIndex(KEY_SPAN_GRP_REL_GRP_ID)));
}while(cur.moveToNext());
}
return groupIds;
}
public ArrayList<Integer> fetchGroupTypesForSpan(long spanId){
Cursor cur = db.query(DATABASE_SPAN_GROUP_REL_TABLE, new String[]{KEY_SPAN_GRP_REL_GRP_TYPE}, KEY_SPAN_GRP_REL_SPAN_ID + "=" + spanId, null, null, null, null);
ArrayList<Integer> groupTypes = new ArrayList<Integer>();
if(cur.moveToFirst()){
do{
groupTypes.add(cur.getInt(cur.getColumnIndex(KEY_SPAN_GRP_REL_GRP_TYPE)));
}while(cur.moveToNext());
}
return groupTypes;
}
public ArrayList<Long> fetchSpansForGroup(long groupId, int type){
Cursor cur = db.query(DATABASE_SPAN_GROUP_REL_TABLE, new String[]{KEY_SPAN_GRP_REL_SPAN_ID}, KEY_SPAN_GRP_REL_GRP_ID + "=" + groupId + " AND " + KEY_SPAN_GRP_REL_GRP_TYPE + "=" + type, null, null, null, null);
ArrayList<Long> spanIds = new ArrayList<Long>();
if(cur.moveToFirst()){
do{
spanIds.add(cur.getLong(cur.getColumnIndex(KEY_SPAN_GRP_REL_SPAN_ID)));
}while(cur.moveToNext());
}
return spanIds;
}
public void addSpanGroupRel(long spanId, long groupId, int type){
ContentValues cv = new ContentValues();
cv.put(KEY_SPAN_GRP_REL_SPAN_ID, spanId);
cv.put(KEY_SPAN_GRP_REL_GRP_ID, groupId);
cv.put(KEY_SPAN_GRP_REL_GRP_TYPE, type);
db.insert(DATABASE_SPAN_GROUP_REL_TABLE, null, cv);
}
public void deleteSpanGroupRelsForSpan(long spanId){
db.delete(DATABASE_SPAN_GROUP_REL_TABLE, KEY_SPAN_GRP_REL_SPAN_ID + "=" + spanId, null);
}
public void deleteSpanGroupRel(long spanId, long groupId, int type){
db.delete(DATABASE_SPAN_GROUP_REL_TABLE, KEY_SPAN_GRP_REL_SPAN_ID + "=" + spanId + " AND " + KEY_SPAN_GRP_REL_GRP_ID + "=" + groupId + " AND " + KEY_SPAN_GRP_REL_GRP_TYPE + "=" + type, null);
}
//----------------------------------------------end of functions for span-group-relation table----------------
//----------------------------functions for recents table----------------------------------
public void addRecentContact(long contactId, String contactNumber){
Cursor cur = db.query(DATABASE_RECENTS_TABLE, new String[]{KEY_RECENT_CONTACT_ID, KEY_RECENT_CONTACT_CONTACT_ID, KEY_RECENT_CONTACT_NUMBER}, null, null, null, null, KEY_RECENT_CONTACT_ID);
boolean contactExist = false;
if(cur.moveToFirst()){
do{
if((cur.getLong(cur.getColumnIndex(KEY_RECENT_CONTACT_CONTACT_ID)) == contactId)){// || (cur.getString(cur.getColumnIndex(KEY_RECENT_CONTACT_NUMBER)).equals(contactNumber))){
contactExist = true;
break;
}
if(((cur.getLong(cur.getColumnIndex(KEY_RECENT_CONTACT_CONTACT_ID))) == -1) && (cur.getString(cur.getColumnIndex(KEY_RECENT_CONTACT_NUMBER)).equals(contactNumber))){
contactExist = true;
break;
}
}while(cur.moveToNext());
}
if(!contactExist){
ContentValues cv = new ContentValues();
cv.put(KEY_RECENT_CONTACT_CONTACT_ID, contactId);
cv.put(KEY_RECENT_CONTACT_NUMBER, contactNumber);
if(cur.getCount()<20){
db.insert(DATABASE_RECENTS_TABLE, null, cv);
}else{
cur.moveToFirst();
long idToDelete = cur.getLong(cur.getColumnIndex(KEY_RECENT_CONTACT_ID));
db.delete(DATABASE_RECENTS_TABLE, KEY_RECENT_CONTACT_ID + "=" + idToDelete, null);
db.insert(DATABASE_RECENTS_TABLE, null, cv);
}
}
}
public Cursor fetchAllRecents(){
Cursor cur = db.query(DATABASE_RECENTS_TABLE, null, null, null, null, null, KEY_RECENT_CONTACT_ID + " DESC");
return cur;
}
//----------------------------------------------end of functions for recents table-----------------
//----------------------------------------------------------end of functions--------------------------------
public class MyOpenHelper extends SQLiteOpenHelper{
MyOpenHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE_SMS_TABLE);
db.execSQL(DATABASE_CREATE_TEMPLATE_TABLE);
db.execSQL(DATABASE_CREATE_PI_TABLE);
db.execSQL(DATABASE_CREATE_GROUP_TABLE);
db.execSQL(DATABASE_CREATE_GROUP_CONTACT_RELATION);
db.execSQL(DATABASE_CREATE_SPANS_TABLE);
db.execSQL(DATABASE_CREATE_SPAN_GROUP_REL_TABLE);
db.execSQL(DATABASE_CREATE_RECENTS_TABLE);
//-------Setting initial content of Pending Intent-------
ContentValues initialPi = new ContentValues();
initialPi.put(KEY_PI_ID, 1);
initialPi.put(KEY_PI_NUMBER, 0);
initialPi.put(KEY_SMS_ID, -1);
initialPi.put(KEY_TIME, -1);
initialPi.put(KEY_ACTION, "");
db.insert(DATABASE_PI_TABLE, null, initialPi);
//-------------------------------------------------------
//-------Setting default templates for the app-----------
ContentValues initialTemplates = new ContentValues();
initialTemplates.put(KEY_TEMP_CONTENT, "I'm in a meeting. I'll contact you later.");
db.insert(DATABASE_TEMPLATE_TABLE, null, initialTemplates);
initialTemplates.put(KEY_TEMP_CONTENT, "I'm driving now. I'll contact you later.");
db.insert(DATABASE_TEMPLATE_TABLE, null, initialTemplates);
initialTemplates.put(KEY_TEMP_CONTENT, "I'm busy. Will give you a call later.");
db.insert(DATABASE_TEMPLATE_TABLE, null, initialTemplates);
initialTemplates.put(KEY_TEMP_CONTENT, "Sorry, I'm going to be late.");
db.insert(DATABASE_TEMPLATE_TABLE, null, initialTemplates);
initialTemplates.put(KEY_TEMP_CONTENT, "Have a nice day!");
db.insert(DATABASE_TEMPLATE_TABLE, null, initialTemplates);
//---------------------------------------------------------
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
}
} | minor changes
| src/com/vinsol/sms_scheduler/DBAdapter.java | minor changes |
|
Java | mit | e0afc818e67540b5c606611077010c98b4858464 | 0 | fredyw/leetcode,fredyw/leetcode,fredyw/leetcode,fredyw/leetcode | package leetcode;
/**
* https://leetcode.com/problems/bulb-switcher-iii/
*/
public class Problem1375 {
public int numTimesAllBlue(int[] light) {
int answer = 0;
int[] colors = new int[light.length]; // 0 = white, 1 = yellow, 2 = blue
int yellowCount = 0;
for (int l : light) {
if (l - 2 >= 0 && colors[l - 2] == 2 && yellowCount == 0) {
colors[l - 1] = 2;
answer++;
continue;
} else {
colors[l - 1] = 1;
yellowCount++;
}
int i = 0;
while (i < light.length && (colors[i] == 1 || colors[i] == 2)) {
if (colors[i] == 1) {
yellowCount--;
}
colors[i] = 2;
i++;
}
if (yellowCount == 0) {
answer++;
}
}
return answer;
}
}
| src/main/java/leetcode/Problem1375.java | package leetcode;
/**
* https://leetcode.com/problems/bulb-switcher-iii/
*/
public class Problem1375 {
public int numTimesAllBlue(int[] light) {
int answer = 0;
Color[] colors = new Color[light.length];
for (int i = 0; i < light.length; i++) {
colors[i] = Color.WHITE;
}
int yellowCount = 0;
for (int l : light) {
if (l - 2 >= 0 && colors[l - 2] == Color.BLUE && yellowCount == 0) {
colors[l - 1] = Color.BLUE;
answer++;
continue;
} else {
colors[l - 1] = Color.YELLOW;
yellowCount++;
}
int i = 0;
while (i < light.length && colors[i].on) {
if (colors[i] == Color.YELLOW) {
yellowCount--;
}
colors[i] = Color.BLUE;
i++;
}
if (yellowCount == 0) {
answer++;
}
}
return answer;
}
private enum Color {
WHITE(false),
YELLOW(true),
BLUE(true);
private final boolean on;
Color(boolean on) {
this.on = on;
}
}
public static void main(String[] args) {
Problem1375 prob = new Problem1375();
// System.out.println(prob.numTimesAllBlue(new int[]{2,1,3,5,4})); // 3
// System.out.println(prob.numTimesAllBlue(new int[]{3,2,4,1,5})); // 2
System.out.println(prob.numTimesAllBlue(new int[]{4,1,2,3})); // 1
// System.out.println(prob.numTimesAllBlue(new int[]{2,1,4,3,6,5})); // 3
// System.out.println(prob.numTimesAllBlue(new int[]{1,2,3,4,5,6})); // 6
// System.out.println(prob.numTimesAllBlue(new int[]{3,2,1})); // 1
// System.out.println(prob.numTimesAllBlue(new int[]{3,1,2})); // 1
}
}
| Solve problem 1375
| src/main/java/leetcode/Problem1375.java | Solve problem 1375 |
|
Java | mit | ca0e31ecc6c2aaa08da0ce68c7ee49e02c526d7c | 0 | jwarwick/processing-edmx | package eDMX;
import java.net.*;
import java.io.*;
import java.nio.ByteBuffer;
import java.util.UUID;
import processing.core.*;
public class sACN {
private static final String default_source_name = "Processing";
private static final int sdt_acn_port = 5568;
private String source_name;
private byte priority = 100;
private boolean preview_data = false;
private byte sequence_number = 0;
private UUID cid = UUID.randomUUID();
private DatagramSocket datagramSocket;
public sACN(PApplet applet) throws SocketException {
this(applet, default_source_name);
}
public sACN(PApplet applet, String source_name) throws SocketException {
this.source_name = source_name;
this.datagramSocket = new DatagramSocket();
System.out.println("CREATED sACN object:" + this.source_name);
applet.registerMethod("dispose", this);
}
public void sendPacket(int universe_number, byte start_code, byte[] data) throws UnknownHostException, IOException {
this.sendPacket(universe_number, start_code, data, this.source_name, this.priority,
this.preview_data, this.sequence_number, this.cid);
}
public void sendPacket(int universe_number, byte start_code, byte[] data, String source_name,
byte priority, boolean preview_data, byte sequence_number, UUID cid) throws UnknownHostException, IOException {
final InetAddress addr = getUniverseAddress(universe_number);
System.out.println("Sending to ip: " + addr.getHostAddress() + ":" + this.sdt_acn_port);
final int packet_size = 126 + data.length;
ByteBuffer buffer = ByteBuffer.allocate(packet_size);
writeRootLayer(buffer, packet_size, cid);
DatagramPacket packet = new DatagramPacket(buffer.array(), packet_size, addr, this.sdt_acn_port);
this.datagramSocket.send(packet);
}
private static final short rl_preamble_size = 0x0010;
private static final short rl_postamble_size = 0x0000;
private static final byte[] rl_identifier = {0x41, 0x53, 0x43, 0x2d, 0x45,
0x31, 0x2e, 0x31, 0x37, 0x00,
0x00, 0x00};
private static final byte rl_high = 0x07;
private static final int rl_vector = 0x00000004;
private void writeRootLayer(ByteBuffer buffer, final int packet_size, final UUID cid) {
buffer.putShort(rl_preamble_size);
buffer.putShort(rl_postamble_size);
buffer.put(rl_identifier);
// root pdu length starts from octet 16
final short flags = lengthFlags(packet_size - 16);
buffer.putShort(flags);
buffer.putInt(rl_vector);
buffer.putLong(cid.getMostSignificantBits());
buffer.putLong(cid.getLeastSignificantBits());
}
private short lengthFlags(final int packet_size) {
// low 12 bits = pdu length, high 4 bits = 0x7
int flags = 0x7;
flags = flags << 12;
flags = flags | (packet_size & 0x0fff);
return (short)flags;
}
private InetAddress getUniverseAddress(int universe_number) throws UnknownHostException {
byte[] ip = new byte[4];
ip[0] = (byte)239;
ip[1] = (byte)235;
ip[2] = (byte)((universe_number & 0xffff) >> 8);
ip[3] = (byte)(universe_number & 0xff);
InetAddress address = InetAddress.getByAddress(ip);
return address;
}
/**
* Close the socket. This method is automatically called by Processing when
* the PApplet shuts down.
*
* @see sACN#close()
*/
public void dispose() {
close();
}
/**
* Close the socket.
*/
public void close() {
datagramSocket.close();
}
}
| src/sACN.java | package eDMX;
import java.net.*;
import processing.core.*;
public class sACN {
private static final String default_source_name = "Processing";
private String source_name;
private byte priority = 100;
private boolean preview_data = false;
private byte sequence_number = 0;
private short cid = 0x123;
private DatagramSocket datagramSocket;
public sACN(PApplet applet) throws SocketException {
this(applet, default_source_name);
}
public sACN(PApplet applet, String source_name) throws SocketException {
this.source_name = source_name;
DatagramSocket datagramSocket = new DatagramSocket();
System.out.println("CREATED sACN object:" + this.source_name);
applet.registerMethod("dispose", this);
}
public void sendPacket(int universe_number, byte start_code, byte[] data) {
this.sendPacket(universe_number, start_code, data, this.source_name, this.priority,
this.preview_data, this.sequence_number, this.cid);
}
public void sendPacket(int universe_number, byte start_code, byte[] data, String source_name,
byte priority, boolean preview_data, byte sequence_number, short cid) {
}
private InetAddress getUniverseAddress(int universe_number) throws UnknownHostException {
byte[] ip = new byte[4];
ip[0] = (byte)239;
ip[1] = (byte)235;
ip[2] = (byte)((universe_number & 0xffff) >> 8);
ip[3] = (byte)(universe_number & 0xff);
InetAddress address = InetAddress.getByAddress(ip);
return address;
}
/**
* Close the socket. This method is automatically called by Processing when
* the PApplet shuts down.
*
* @see sACN#close()
*/
public void dispose() {
close();
}
/**
* Close the socket.
*/
public void close() {
datagramSocket.close();
}
}
| Writing root layer pdu
| src/sACN.java | Writing root layer pdu |
|
Java | mit | 8b572782428455e873a9b8f61def440ef5a12fa8 | 0 | fredyw/leetcode,fredyw/leetcode,fredyw/leetcode,fredyw/leetcode | package leetcode;
/**
* https://leetcode.com/problems/k-concatenation-maximum-sum/
*/
public class Problem1191 {
public int kConcatenationMaxSum(int[] arr, int k) {
long answer = 0;
long maxSoFar = 0;
for (int j = 0; j < k; j++) {
for (int i = 0; i < arr.length; i++) {
maxSoFar = Math.max(arr[i], (maxSoFar + arr[i]) % 1_000_000_007) ;
answer = Math.max(answer, maxSoFar);
}
}
return (int) answer;
}
public static void main(String[] args) {
Problem1191 prob = new Problem1191();
// System.out.println(prob.kConcatenationMaxSum(new int[]{1,2}, 3)); // 9
// System.out.println(prob.kConcatenationMaxSum(new int[]{1,-2,1}, 5)); // 2
System.out.println(prob.kConcatenationMaxSum(new int[]{1,3-2,5,8}, 2)); // 30
// System.out.println(prob.kConcatenationMaxSum(new int[]{-1,-2}, 7)); // 0
// System.out.println(prob.kConcatenationMaxSum(new int[]{1,2,-3}, 3)); // 3
// System.out.println(prob.kConcatenationMaxSum(new int[]{1,2,-3,4}, 3)); // 12
}
}
| src/main/java/leetcode/Problem1191.java | package leetcode;
/**
* https://leetcode.com/problems/k-concatenation-maximum-sum/
*/
public class Problem1191 {
public int kConcatenationMaxSum(int[] arr, int k) {
int answer = 0;
int maxSoFar = 0;
for (int i = 0; i < arr.length; i++) {
maxSoFar = Math.max(maxSoFar, maxSoFar + arr[i]);
answer = Math.max(answer, maxSoFar);
}
return answer;
}
public static void main(String[] args) {
Problem1191 prob = new Problem1191();
System.out.println(prob.kConcatenationMaxSum(new int[]{1,2}, 3)); // 9
System.out.println(prob.kConcatenationMaxSum(new int[]{1,-2,1}, 5)); // 2
System.out.println(prob.kConcatenationMaxSum(new int[]{-1,-2}, 7)); // 0
System.out.println(prob.kConcatenationMaxSum(new int[]{1,2,-3}, 3)); // 3
System.out.println(prob.kConcatenationMaxSum(new int[]{1,2,-3,4}, 3)); // 12
}
}
| Update problem 1191
| src/main/java/leetcode/Problem1191.java | Update problem 1191 |
|
Java | mit | d3289712575246e653e47e9ab5090930ca9fb656 | 0 | OpenMods/OpenModsLib,nevercast/OpenModsLib,OpenMods/OpenModsLib | package openmods.utils;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang3.ArrayUtils;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.base.Throwables;
import com.google.common.collect.BiMap;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.Lists;
public class ReflectionHelper {
private static class NullMarker {
public final Class<?> cls;
private NullMarker(Class<?> cls) {
this.cls = cls;
}
}
private static class TypeMarker {
public final Class<?> cls;
public final Object value;
private TypeMarker(Class<?> cls, Object value) {
this.cls = cls;
this.value = value;
}
}
public static Object nullValue(Class<?> cls) {
return new NullMarker(cls);
}
public static Object typed(Object value, Class<?> cls) {
return new TypeMarker(cls, value);
}
public static Object primitive(char value) {
return new TypeMarker(char.class, value);
}
public static Object primitive(long value) {
return new TypeMarker(long.class, value);
}
public static Object primitive(int value) {
return new TypeMarker(int.class, value);
}
public static Object primitive(short value) {
return new TypeMarker(short.class, value);
}
public static Object primitive(byte value) {
return new TypeMarker(byte.class, value);
}
public static Object primitive(float value) {
return new TypeMarker(float.class, value);
}
public static Object primitive(double value) {
return new TypeMarker(double.class, value);
}
public static Object primitive(boolean value) {
return new TypeMarker(boolean.class, value);
}
@SuppressWarnings("unchecked")
public static <T> T getProperty(Class<?> klazz, Object instance, String... fields) {
Field field = getField(klazz == null? instance.getClass() : klazz, fields);
Preconditions.checkNotNull(field, "Fields %s not found", Arrays.toString(fields));
try {
return (T)field.get(instance);
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
public static <T> T getProperty(String className, Object instance, String... fields) {
return getProperty(getClass(className), instance, fields);
}
public static <T> T getProperty(Object instance, String... fields) {
return getProperty(instance.getClass(), instance, fields);
}
public static void setProperty(Class<?> klazz, Object instance, Object value, String... fields) {
Field field = getField(klazz == null? instance.getClass() : klazz, fields);
Preconditions.checkNotNull(field, "Fields %s not found", Arrays.toString(fields));
try {
field.set(instance, value);
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
public static void setProperty(String className, Object instance, Object value, String... fields) {
setProperty(getClass(className), instance, value, fields);
}
public static void setProperty(Object instance, Object value, String... fields) {
setProperty(instance.getClass(), instance, value, fields);
}
public static <T> T callStatic(Class<?> klazz, String methodName, Object... args) {
return call(klazz, null, ArrayUtils.toArray(methodName), args);
}
public static <T> T call(Object instance, String methodName, Object... args) {
return call(instance.getClass(), instance, ArrayUtils.toArray(methodName), args);
}
public static <T> T call(Object instance, String[] methodNames, Object... args) {
return call(instance.getClass(), instance, methodNames, args);
}
public static <T> T call(Class<?> cls, Object instance, String methodName, Object... args) {
return call(cls, instance, ArrayUtils.toArray(methodName), args);
}
@SuppressWarnings("unchecked")
public static <T> T call(Class<?> klazz, Object instance, String[] methodNames, Object... args) {
Method m = getMethod(klazz, methodNames, args);
Preconditions.checkNotNull(m, "Method %s not found", Arrays.toString(methodNames));
for (int i = 0; i < args.length; i++) {
final Object arg = args[i];
if (arg instanceof NullMarker) args[i] = null;
if (arg instanceof TypeMarker) args[i] = ((TypeMarker)arg).value;
}
m.setAccessible(true);
try {
return (T)m.invoke(instance, args);
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
public static Method getMethod(Class<?> klazz, String[] methodNames, Object... args) {
if (klazz == null) return null;
Class<?> argTypes[] = new Class<?>[args.length];
for (int i = 0; i < args.length; i++) {
final Object arg = args[i];
Preconditions.checkNotNull(arg, "No nulls allowed, use wrapper types");
if (arg instanceof NullMarker) argTypes[i] = ((NullMarker)arg).cls;
else if (arg instanceof TypeMarker) argTypes[i] = ((TypeMarker)arg).cls;
else argTypes[i] = arg.getClass();
}
for (String name : methodNames) {
Method result = getDeclaredMethod(klazz, name, argTypes);
if (result != null) return result;
}
return null;
}
public static Method getMethod(Class<?> klazz, String[] methodNames, Class<?>... types) {
if (klazz == null) return null;
for (String name : methodNames) {
Method result = getDeclaredMethod(klazz, name, types);
if (result != null) return result;
}
return null;
}
public static Method getDeclaredMethod(Class<?> clazz, String name, Class<?>[] argsTypes) {
while (clazz != null) {
try {
return clazz.getDeclaredMethod(name, argsTypes);
} catch (NoSuchMethodException e) {} catch (Exception e) {
throw Throwables.propagate(e);
}
clazz = clazz.getSuperclass();
}
return null;
}
public static List<Method> getAllMethods(Class<?> clazz) {
List<Method> methods = Lists.newArrayList();
while (clazz != null) {
for (Method m : clazz.getDeclaredMethods())
methods.add(m);
clazz = clazz.getSuperclass();
}
return methods;
}
public static Field getField(Class<?> klazz, String... fields) {
for (String field : fields) {
Class<?> current = klazz;
while (current != null) {
try {
Field f = current.getDeclaredField(field);
f.setAccessible(true);
return f;
} catch (NoSuchFieldException e) {} catch (Exception e) {
throw Throwables.propagate(e);
}
current = current.getSuperclass();
}
}
return null;
}
public static Class<?> getClass(String className) {
if (Strings.isNullOrEmpty(className)) return null;
try {
return Class.forName(className);
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
public static final BiMap<Class<?>, Class<?>> WRAPPERS = ImmutableBiMap.<Class<?>, Class<?>> builder()
.put(long.class, Long.class)
.put(int.class, Integer.class)
.put(short.class, Short.class)
.put(byte.class, Byte.class)
.put(boolean.class, Boolean.class)
.put(double.class, Double.class)
.put(float.class, Float.class)
.put(char.class, Character.class)
.build();
public static boolean compareTypes(Class<?> left, Class<?> right) {
if (left.isPrimitive()) left = WRAPPERS.get(left);
if (right.isPrimitive()) right = WRAPPERS.get(right);
return left.equals(right);
}
}
| src/openmods/utils/ReflectionHelper.java | package openmods.utils;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang3.ArrayUtils;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.base.Throwables;
import com.google.common.collect.BiMap;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.Lists;
public class ReflectionHelper {
private static class NullMarker {
public final Class<?> cls;
private NullMarker(Class<?> cls) {
this.cls = cls;
}
}
private static class TypeMarker {
public final Class<?> cls;
public final Object value;
private TypeMarker(Class<?> cls, Object value) {
this.cls = cls;
this.value = value;
}
}
public static Object nullValue(Class<?> cls) {
return new NullMarker(cls);
}
public static Object typed(Object value, Class<?> cls) {
return new TypeMarker(cls, value);
}
public static Object primitive(char value) {
return new TypeMarker(char.class, value);
}
public static Object primitive(long value) {
return new TypeMarker(long.class, value);
}
public static Object primitive(int value) {
return new TypeMarker(int.class, value);
}
public static Object primitive(short value) {
return new TypeMarker(short.class, value);
}
public static Object primitive(byte value) {
return new TypeMarker(byte.class, value);
}
public static Object primitive(float value) {
return new TypeMarker(float.class, value);
}
public static Object primitive(double value) {
return new TypeMarker(double.class, value);
}
public static Object primitive(boolean value) {
return new TypeMarker(boolean.class, value);
}
public static Object getProperty(Class<?> klazz, Object instance, String... fields) {
Field field = getField(klazz == null? instance.getClass() : klazz, fields);
Preconditions.checkNotNull(field, "Fields %s not found", Arrays.toString(fields));
try {
return field.get(instance);
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
public static Object getProperty(String className, Object instance, String... fields) {
return getProperty(getClass(className), instance, fields);
}
public static <T> T callStatic(Class<?> klazz, String methodName, Object... args) {
return call(klazz, null, ArrayUtils.toArray(methodName), args);
}
public static <T> T call(Object instance, String methodName, Object... args) {
return call(instance.getClass(), instance, ArrayUtils.toArray(methodName), args);
}
public static <T> T call(Object instance, String[] methodNames, Object... args) {
return call(instance.getClass(), instance, methodNames, args);
}
public static <T> T call(Class<?> cls, Object instance, String methodName, Object... args) {
return call(cls, instance, ArrayUtils.toArray(methodName), args);
}
@SuppressWarnings("unchecked")
public static <T> T call(Class<?> klazz, Object instance, String[] methodNames, Object... args) {
Method m = getMethod(klazz, methodNames, args);
Preconditions.checkNotNull(m, "Method %s not found", Arrays.toString(methodNames));
for (int i = 0; i < args.length; i++) {
final Object arg = args[i];
if (arg instanceof NullMarker) args[i] = null;
if (arg instanceof TypeMarker) args[i] = ((TypeMarker)arg).value;
}
m.setAccessible(true);
try {
return (T)m.invoke(instance, args);
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
public static Method getMethod(Class<?> klazz, String[] methodNames, Object... args) {
if (klazz == null) return null;
Class<?> argTypes[] = new Class<?>[args.length];
for (int i = 0; i < args.length; i++) {
final Object arg = args[i];
Preconditions.checkNotNull(arg, "No nulls allowed, use wrapper types");
if (arg instanceof NullMarker) argTypes[i] = ((NullMarker)arg).cls;
else if (arg instanceof TypeMarker) argTypes[i] = ((TypeMarker)arg).cls;
else argTypes[i] = arg.getClass();
}
for (String name : methodNames) {
Method result = getDeclaredMethod(klazz, name, argTypes);
if (result != null) return result;
}
return null;
}
public static Method getMethod(Class<?> klazz, String[] methodNames, Class<?>... types) {
if (klazz == null) return null;
for (String name : methodNames) {
Method result = getDeclaredMethod(klazz, name, types);
if (result != null) return result;
}
return null;
}
public static Method getDeclaredMethod(Class<?> clazz, String name, Class<?>[] argsTypes) {
while (clazz != null) {
try {
return clazz.getDeclaredMethod(name, argsTypes);
} catch (NoSuchMethodException e) {} catch (Exception e) {
throw Throwables.propagate(e);
}
clazz = clazz.getSuperclass();
}
return null;
}
public static List<Method> getAllMethods(Class<?> clazz) {
List<Method> methods = Lists.newArrayList();
while (clazz != null) {
for (Method m : clazz.getDeclaredMethods())
methods.add(m);
clazz = clazz.getSuperclass();
}
return methods;
}
public static Field getField(Class<?> klazz, String... fields) {
for (String field : fields) {
Class<?> current = klazz;
while (current != null) {
try {
Field f = current.getDeclaredField(field);
f.setAccessible(true);
return f;
} catch (NoSuchFieldException e) {} catch (Exception e) {
throw Throwables.propagate(e);
}
current = current.getSuperclass();
}
}
return null;
}
public static Class<?> getClass(String className) {
if (Strings.isNullOrEmpty(className)) return null;
try {
return Class.forName(className);
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
public static final BiMap<Class<?>, Class<?>> WRAPPERS = ImmutableBiMap.<Class<?>, Class<?>> builder()
.put(long.class, Long.class)
.put(int.class, Integer.class)
.put(short.class, Short.class)
.put(byte.class, Byte.class)
.put(boolean.class, Boolean.class)
.put(double.class, Double.class)
.put(float.class, Float.class)
.put(char.class, Character.class)
.build();
public static boolean compareTypes(Class<?> left, Class<?> right) {
if (left.isPrimitive()) left = WRAPPERS.get(left);
if (right.isPrimitive()) right = WRAPPERS.get(right);
return left.equals(right);
}
}
| More reflection utils
| src/openmods/utils/ReflectionHelper.java | More reflection utils |
|
Java | mit | 539d2cc927b4db61363adde5b3c9090708c29492 | 0 | openforis/collect,openforis/collect,openforis/collect,openforis/collect | /**
*
*/
package org.openforis.collect.manager;
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.Map.Entry;
import java.util.Set;
import javax.xml.namespace.QName;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openforis.collect.model.CollectRecord;
import org.openforis.collect.model.CollectRecord.State;
import org.openforis.collect.model.CollectRecord.Step;
import org.openforis.collect.model.CollectSurvey;
import org.openforis.collect.model.FieldSymbol;
import org.openforis.collect.model.RecordLock;
import org.openforis.collect.model.RecordSummarySortField;
import org.openforis.collect.model.User;
import org.openforis.collect.persistence.MissingRecordKeyException;
import org.openforis.collect.persistence.MultipleEditException;
import org.openforis.collect.persistence.RecordDao;
import org.openforis.collect.persistence.RecordLockedByActiveUserException;
import org.openforis.collect.persistence.RecordLockedException;
import org.openforis.collect.persistence.RecordPersistenceException;
import org.openforis.collect.persistence.RecordUnlockedException;
import org.openforis.idm.metamodel.AttributeDefault;
import org.openforis.idm.metamodel.AttributeDefinition;
import org.openforis.idm.metamodel.CodeAttributeDefinition;
import org.openforis.idm.metamodel.CodeList;
import org.openforis.idm.metamodel.CodeListItem;
import org.openforis.idm.metamodel.EntityDefinition;
import org.openforis.idm.metamodel.ModelVersion;
import org.openforis.idm.metamodel.NodeDefinition;
import org.openforis.idm.metamodel.Schema;
import org.openforis.idm.model.Attribute;
import org.openforis.idm.model.Code;
import org.openforis.idm.model.CodeAttribute;
import org.openforis.idm.model.Entity;
import org.openforis.idm.model.Field;
import org.openforis.idm.model.Node;
import org.openforis.idm.model.NodePointer;
import org.openforis.idm.model.Record;
import org.openforis.idm.model.expression.InvalidExpressionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
/**
* @author M. Togna
* @author S. Ricci
*/
public class RecordManager {
private final Log log = LogFactory.getLog(RecordManager.class);
private static final QName LAYOUT_ANNOTATION = new QName("http://www.openforis.org/collect/3.0/ui", "layout");
@Autowired
private RecordDao recordDao;
private Map<Integer, RecordLock> locks;
private long lockTimeoutMillis = 60000;
protected void init() {
locks = new HashMap<Integer, RecordLock>();
}
@Transactional
public void save(CollectRecord record, String sessionId) throws RecordPersistenceException {
User user = record.getModifiedBy();
record.updateRootEntityKeyValues();
checkAllKeysSpecified(record);
record.updateEntityCounts();
Integer id = record.getId();
if(id == null) {
recordDao.insert(record);
id = record.getId();
//todo fix: concurrency problem may occur..
lock(id, user, sessionId);
} else {
checkIsLocked(id, user, sessionId);
recordDao.update(record);
}
}
@Transactional
public void delete(int recordId) throws RecordPersistenceException {
if ( isLocked(recordId) ) {
RecordLock lock = getLock(recordId);
User lockUser = lock.getUser();
throw new RecordLockedException(lockUser.getName());
} else {
recordDao.delete(recordId);
}
}
/**
* Returns a record and lock it
*
* @param survey
* @param user
* @param recordId
* @param step
* @param sessionId
* @param forceUnlock
* @return
* @throws RecordLockedException
* @throws MultipleEditException
*/
@Transactional
public synchronized CollectRecord checkout(CollectSurvey survey, User user, int recordId, int step, String sessionId, boolean forceUnlock) throws RecordLockedException, MultipleEditException {
isLockAllowed(user, recordId, sessionId, forceUnlock);
lock(recordId, user, sessionId, forceUnlock);
CollectRecord record = recordDao.load(survey, recordId, step);
return record;
}
@Transactional
public CollectRecord load(CollectSurvey survey, int recordId, int step) throws RecordPersistenceException {
CollectRecord record = recordDao.load(survey, recordId, step);
return record;
}
@Transactional
public List<CollectRecord> getSummaries(CollectSurvey survey, String rootEntity, String... keys) {
return recordDao.loadSummaries(survey, rootEntity, keys);
}
@Transactional
public List<CollectRecord> loadSummaries(CollectSurvey survey, String rootEntity, int offset, int maxNumberOfRecords, List<RecordSummarySortField> sortFields, String... keyValues) {
List<CollectRecord> recordsSummary = recordDao.loadSummaries(survey, rootEntity, offset, maxNumberOfRecords, sortFields, keyValues);
return recordsSummary;
}
@Transactional
public int getRecordCount(CollectSurvey survey, String rootEntity, String... keyValues) {
Schema schema = survey.getSchema();
EntityDefinition rootEntityDefinition = schema.getRootEntityDefinition(rootEntity);
int count = recordDao.countRecords(rootEntityDefinition.getId(), keyValues);
return count;
}
@Transactional
public CollectRecord create(CollectSurvey survey, EntityDefinition rootEntityDefinition, User user, String modelVersionName, String sessionId) throws RecordPersistenceException {
CollectRecord record = new CollectRecord(survey, modelVersionName);
record.createRootEntity(rootEntityDefinition.getName());
record.setCreationDate(new Date());
record.setCreatedBy(user);
record.setStep(Step.ENTRY);
return record;
}
@Transactional
public void promote(CollectRecord record, User user) throws RecordPromoteException, MissingRecordKeyException {
Integer errors = record.getErrors();
Integer skipped = record.getSkipped();
Integer missing = record.getMissingErrors();
int totalErrors = errors + skipped + missing;
if( totalErrors > 0 ){
throw new RecordPromoteException("Record cannot be promoted becuase it contains errors.");
}
record.updateRootEntityKeyValues();
checkAllKeysSpecified(record);
record.updateEntityCounts();
Integer id = record.getId();
// before save record in current step
if( id == null ) {
recordDao.insert( record );
} else {
recordDao.update( record );
}
applyDefaultValues(record);
//change step and update the record
Step currentStep = record.getStep();
Step nextStep = currentStep.getNext();
Date now = new Date();
record.setModifiedBy( user );
record.setModifiedDate( now );
record.setState( null );
/**
* 1. clear node states
* 2. update record step
* 3. update all validation states
*/
record.clearNodeStates();
record.setStep( nextStep );
record.updateDerivedStates();
recordDao.update( record );
}
/**
* Applies default values on each descendant attribute of a record in which empty nodes have already been added.
* Default values are applied only to "empty" attributes.
*
* @param record
* @throws InvalidExpressionException
*/
protected void applyDefaultValues(CollectRecord record) {
Entity rootEntity = record.getRootEntity();
applyDefaultValues(rootEntity);
}
/**
* Applies default values on each descendant attribute of an Entity in which empty nodes have already been added.
* Default values are applied only to "empty" attributes.
*
* @param entity
* @throws InvalidExpressionException
*/
protected void applyDefaultValues(Entity entity) {
List<Node<?>> children = entity.getChildren();
for (Node<?> child: children) {
if ( child instanceof Attribute ) {
Attribute<?, ?> attribute = (Attribute<?, ?>) child;
if ( attribute.isEmpty() ) {
applyDefaultValue(attribute);
}
} else if ( child instanceof Entity ) {
applyDefaultValues((Entity) child);
}
}
}
public <V> void applyDefaultValue(Attribute<?, V> attribute) {
AttributeDefinition attributeDefn = (AttributeDefinition) attribute.getDefinition();
List<AttributeDefault> defaults = attributeDefn.getAttributeDefaults();
if ( defaults != null && defaults.size() > 0 ) {
for (AttributeDefault attributeDefault : defaults) {
try {
V value = attributeDefault.evaluate(attribute);
if ( value != null ) {
attribute.setValue(value);
clearRelevanceRequiredStates(attribute);
clearValidationResults(attribute);
}
} catch (InvalidExpressionException e) {
log.warn("Error applying default value for attribute " + attributeDefn.getPath());
}
}
}
}
@Transactional
public void demote(CollectSurvey survey, int recordId, Step currentStep, User user) throws RecordPersistenceException {
Step prevStep = currentStep.getPrevious();
CollectRecord record = recordDao.load( survey, recordId, prevStep.getStepNumber() );
record.setModifiedBy( user );
record.setModifiedDate( new Date() );
record.setStep( prevStep );
record.setState( State.REJECTED );
record.updateDerivedStates();
recordDao.update( record );
}
public Entity addEntity(Entity parentEntity, String nodeName) {
Entity entity = parentEntity.addEntity(nodeName);
addEmptyNodes(entity);
return entity;
}
public void moveNode(CollectRecord record, int nodeId, int index) {
Node<?> node = record.getNodeByInternalId(nodeId);
Entity parent = node.getParent();
String name = node.getName();
List<Node<?>> siblings = parent.getAll(name);
int oldIndex = siblings.indexOf(node);
parent.move(name, oldIndex, index);
}
public void addEmptyNodes(Entity entity) {
Record record = entity.getRecord();
ModelVersion version = record.getVersion();
addEmptyEnumeratedEntities(entity);
EntityDefinition entityDefn = entity.getDefinition();
List<NodeDefinition> childDefinitions = entityDefn.getChildDefinitions();
for (NodeDefinition nodeDefn : childDefinitions) {
if(version.isApplicable(nodeDefn)) {
String name = nodeDefn.getName();
if(entity.getCount(name) == 0) {
int count = 0;
int toBeInserted = entity.getEffectiveMinCount(name);
String layout = nodeDefn.getAnnotation(LAYOUT_ANNOTATION);
if(nodeDefn instanceof AttributeDefinition || (! (nodeDefn.isMultiple() && "form".equals(layout)))) {
//insert at least one node
toBeInserted = 1;
}
while(count < toBeInserted) {
if(nodeDefn instanceof AttributeDefinition) {
Node<?> createNode = nodeDefn.createNode();
entity.add(createNode);
} else if(nodeDefn instanceof EntityDefinition) {
addEntity(entity, name);
}
count ++;
}
} else {
List<Node<?>> all = entity.getAll(name);
for (Node<?> node : all) {
if(node instanceof Entity) {
addEmptyNodes((Entity) node);
}
}
}
}
}
}
@SuppressWarnings("unchecked")
public <V> void setFieldValue(Attribute<?,?> attribute, Object value, String remarks, FieldSymbol symbol, int fieldIdx){
if(fieldIdx < 0){
fieldIdx = 0;
}
Field<V> field = (Field<V>) attribute.getField(fieldIdx);
field.setValue((V)value);
field.setRemarks(remarks);
Character symbolChar = null;
if (symbol != null) {
symbolChar = symbol.getCode();
}
field.setSymbol(symbolChar);
}
@SuppressWarnings("unchecked")
public <V> void setAttributeValue(Attribute<?,V> attribute, Object value, String remarks){
attribute.setValue((V)value);
Field<V> field = (Field<V>) attribute.getField(0);
field.setRemarks(remarks);
field.setSymbol(null);
}
public Set<Attribute<?, ?>> clearValidationResults(Attribute<?,?> attribute){
Set<Attribute<?,?>> checkDependencies = attribute.getCheckDependencies();
clearValidationResults(checkDependencies);
return checkDependencies;
}
public void clearValidationResults(Set<Attribute<?, ?>> checkDependencies) {
for (Attribute<?, ?> attr : checkDependencies) {
attr.clearValidationResults();
}
}
public Set<NodePointer> clearRelevanceRequiredStates(Node<?> node){
Set<NodePointer> relevantDependencies = node.getRelevantDependencies();
clearRelevantDependencies(relevantDependencies);
Set<NodePointer> requiredDependencies = node.getRequiredDependencies();
requiredDependencies.addAll(relevantDependencies);
clearRequiredDependencies(requiredDependencies);
return requiredDependencies;
}
public void clearRelevantDependencies(Set<NodePointer> nodePointers) {
for (NodePointer nodePointer : nodePointers) {
Entity entity = nodePointer.getEntity();
entity.clearRelevanceState(nodePointer.getChildName());
}
}
public void clearRequiredDependencies(Set<NodePointer> nodePointers) {
for (NodePointer nodePointer : nodePointers) {
Entity entity = nodePointer.getEntity();
entity.clearRequiredState(nodePointer.getChildName());
}
}
private void addEmptyEnumeratedEntities(Entity entity) {
Record record = entity.getRecord();
ModelVersion version = record.getVersion();
EntityDefinition entityDefn = entity.getDefinition();
List<NodeDefinition> childDefinitions = entityDefn.getChildDefinitions();
for (NodeDefinition childDefn : childDefinitions) {
if(childDefn instanceof EntityDefinition && version.isApplicable(childDefn)) {
EntityDefinition childEntityDefn = (EntityDefinition) childDefn;
if(childEntityDefn.isMultiple() && childEntityDefn.isEnumerable()) {
addEmptyEnumeratedEntities(entity, childEntityDefn);
}
}
}
}
private void addEmptyEnumeratedEntities(Entity entity, EntityDefinition enumeratedEntityDefn) {
Record record = entity.getRecord();
ModelVersion version = record.getVersion();
CodeAttributeDefinition enumeratingCodeDefn = getEnumeratingKeyCodeAttribute(enumeratedEntityDefn, version);
if(enumeratingCodeDefn != null) {
CodeList list = enumeratingCodeDefn.getList();
List<CodeListItem> items = list.getItems();
for (CodeListItem item : items) {
if(version.isApplicable(item)) {
String code = item.getCode();
if(! hasEnumeratedEntity(entity, enumeratedEntityDefn, enumeratingCodeDefn, code)) {
Entity addedEntity = addEntity(entity, enumeratedEntityDefn.getName());
//there will be an empty CodeAttribute after the adding of the new entity
//set the value into this node
CodeAttribute addedCode = (CodeAttribute) addedEntity.get(enumeratingCodeDefn.getName(), 0);
addedCode.setValue(new Code(code));
}
}
}
}
}
private CodeAttributeDefinition getEnumeratingKeyCodeAttribute(EntityDefinition entity, ModelVersion version) {
List<AttributeDefinition> keys = entity.getKeyAttributeDefinitions();
for (AttributeDefinition key: keys) {
if(key instanceof CodeAttributeDefinition && version.isApplicable(key)) {
CodeAttributeDefinition codeDefn = (CodeAttributeDefinition) key;
if(codeDefn.getList().getLookupTable() == null) {
return codeDefn;
}
}
}
return null;
}
private boolean hasEnumeratedEntity(Entity parentEntity, EntityDefinition childEntityDefn,
CodeAttributeDefinition enumeratingCodeAttributeDef, String value) {
List<Node<?>> children = parentEntity.getAll(childEntityDefn.getName());
for (Node<?> node : children) {
Entity child = (Entity) node;
Code code = getCodeAttributeValue(child, enumeratingCodeAttributeDef);
if(code != null && value.equals(code.getCode())) {
return true;
}
}
return false;
}
private Code getCodeAttributeValue(Entity entity, CodeAttributeDefinition def) {
Node<?> node = entity.get(def.getName(), 0);
if(node != null) {
return ((CodeAttribute)node).getValue();
} else {
return null;
}
}
private void checkAllKeysSpecified(CollectRecord record) throws MissingRecordKeyException {
List<String> rootEntityKeyValues = record.getRootEntityKeyValues();
Entity rootEntity = record.getRootEntity();
EntityDefinition rootEntityDefn = rootEntity.getDefinition();
List<AttributeDefinition> keyAttributeDefns = rootEntityDefn.getKeyAttributeDefinitions();
for (int i = 0; i < keyAttributeDefns.size(); i++) {
AttributeDefinition keyAttrDefn = keyAttributeDefns.get(i);
if ( rootEntity.isRequired(keyAttrDefn.getName()) ) {
String keyValue = rootEntityKeyValues.get(i);
if ( StringUtils.isBlank(keyValue) ) {
throw new MissingRecordKeyException();
}
}
}
}
/* --- START OF LOCKING METHODS --- */
public synchronized void releaseLock(int recordId) {
RecordLock lock = getLock(recordId);
if ( lock != null ) {
locks.remove(recordId);
}
}
public synchronized boolean checkIsLocked(int recordId, User user, String sessionId) throws RecordUnlockedException {
RecordLock lock = getLock(recordId);
String lockUserName = null;
if ( lock != null) {
String lockSessionId = lock.getSessionId();
int lockRecordId = lock.getRecordId();
User lUser = lock.getUser();
if( recordId == lockRecordId &&
( lUser == user || lUser.getId() == user.getId() ) &&
lockSessionId.equals(sessionId) ) {
lock.keepAlive();
return true;
} else {
User lockUser = lock.getUser();
lockUserName = lockUser.getName();
}
}
throw new RecordUnlockedException(lockUserName);
}
private synchronized void lock(int recordId, User user, String sessionId) throws RecordLockedException, MultipleEditException {
lock(recordId, user, sessionId, false);
}
private synchronized void lock(int recordId, User user, String sessionId, boolean forceUnlock) throws RecordLockedException, MultipleEditException {
RecordLock oldLock = getLock(recordId);
if ( oldLock != null ) {
locks.remove(recordId);
}
RecordLock lock = new RecordLock(sessionId, recordId, user, lockTimeoutMillis);
locks.put(recordId, lock);
}
private boolean isForceUnlockAllowed(User user, RecordLock lock) {
boolean isAdmin = user.hasRole("ROLE_ADMIN");
Integer userId = user.getId();
User lockUser = lock.getUser();
return isAdmin || userId.equals(lockUser.getId());
}
private synchronized boolean isLockAllowed(User user, int recordId, String sessionId, boolean forceUnlock) throws RecordLockedException, MultipleEditException {
RecordLock uLock = getLockBySessionId(sessionId);
if ( uLock != null ) {
throw new MultipleEditException("User is editing another record: " + uLock.getRecordId());
}
RecordLock lock = getLock(recordId);
if ( lock == null || ( forceUnlock && isForceUnlockAllowed(user, lock) ) ) {
return true;
} else if ( lock.getUser().getId().equals(user.getId()) ) {
throw new RecordLockedByActiveUserException(user.getName());
} else {
String lockingUserName = lock.getUser().getName();
throw new RecordLockedException("Record already locked", lockingUserName);
}
}
private synchronized boolean isLocked(int recordId) {
RecordLock lock = getLock(recordId);
return lock != null;
}
private synchronized RecordLock getLock(int recordId) {
clearInactiveLocks();
RecordLock lock = locks.get(recordId);
return lock;
}
private synchronized RecordLock getLockBySessionId(String sessionId) {
clearInactiveLocks();
Collection<RecordLock> lcks = locks.values();
for (RecordLock l : lcks) {
if ( l.getSessionId().equals(sessionId) ) {
return l;
}
}
return null;
}
private synchronized void clearInactiveLocks() {
Set<Entry<Integer, RecordLock>> entrySet = locks.entrySet();
Iterator<Entry<Integer, RecordLock>> iterator = entrySet.iterator();
while (iterator.hasNext()) {
Entry<Integer, RecordLock> entry = iterator.next();
RecordLock lock = entry.getValue();
if( !lock.isActive() ){
iterator.remove();
}
}
}
/* --- END OF LOCKING METHODS --- */
/**
* GETTERS AND SETTERS
*/
public long getLockTimeoutMillis() {
return lockTimeoutMillis;
}
public void setLockTimeoutMillis(long timeoutMillis) {
this.lockTimeoutMillis = timeoutMillis;
}
}
| collect-core/src/main/java/org/openforis/collect/manager/RecordManager.java | /**
*
*/
package org.openforis.collect.manager;
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.Map.Entry;
import java.util.Set;
import javax.xml.namespace.QName;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openforis.collect.model.CollectRecord;
import org.openforis.collect.model.CollectRecord.State;
import org.openforis.collect.model.CollectRecord.Step;
import org.openforis.collect.model.CollectSurvey;
import org.openforis.collect.model.FieldSymbol;
import org.openforis.collect.model.RecordLock;
import org.openforis.collect.model.RecordSummarySortField;
import org.openforis.collect.model.User;
import org.openforis.collect.persistence.MissingRecordKeyException;
import org.openforis.collect.persistence.MultipleEditException;
import org.openforis.collect.persistence.RecordDao;
import org.openforis.collect.persistence.RecordLockedByActiveUserException;
import org.openforis.collect.persistence.RecordLockedException;
import org.openforis.collect.persistence.RecordPersistenceException;
import org.openforis.collect.persistence.RecordUnlockedException;
import org.openforis.idm.metamodel.AttributeDefault;
import org.openforis.idm.metamodel.AttributeDefinition;
import org.openforis.idm.metamodel.CodeAttributeDefinition;
import org.openforis.idm.metamodel.CodeList;
import org.openforis.idm.metamodel.CodeListItem;
import org.openforis.idm.metamodel.EntityDefinition;
import org.openforis.idm.metamodel.ModelVersion;
import org.openforis.idm.metamodel.NodeDefinition;
import org.openforis.idm.metamodel.Schema;
import org.openforis.idm.model.Attribute;
import org.openforis.idm.model.Code;
import org.openforis.idm.model.CodeAttribute;
import org.openforis.idm.model.Entity;
import org.openforis.idm.model.Field;
import org.openforis.idm.model.Node;
import org.openforis.idm.model.NodePointer;
import org.openforis.idm.model.Record;
import org.openforis.idm.model.expression.InvalidExpressionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
/**
* @author M. Togna
* @author S. Ricci
*/
public class RecordManager {
private final Log log = LogFactory.getLog(RecordManager.class);
private static final QName LAYOUT_ANNOTATION = new QName("http://www.openforis.org/collect/3.0/ui", "layout");
@Autowired
private RecordDao recordDao;
private Map<Integer, RecordLock> locks;
private long lockTimeoutMillis = 60000;
protected void init() {
locks = new HashMap<Integer, RecordLock>();
}
@Transactional
public void save(CollectRecord record, String sessionId) throws RecordPersistenceException {
User user = record.getModifiedBy();
record.updateRootEntityKeyValues();
checkAllKeysSpecified(record);
record.updateEntityCounts();
Integer id = record.getId();
if(id == null) {
recordDao.insert(record);
id = record.getId();
//todo fix: concurrency problem may occur..
lock(id, user, sessionId);
} else {
checkIsLocked(id, user, sessionId);
recordDao.update(record);
}
}
@Transactional
public void delete(int recordId) throws RecordPersistenceException {
if ( isLocked(recordId) ) {
RecordLock lock = getLock(recordId);
User lockUser = lock.getUser();
throw new RecordLockedException(lockUser.getName());
} else {
recordDao.delete(recordId);
}
}
/**
* Returns a record and lock it
*
* @param survey
* @param user
* @param recordId
* @param step
* @param sessionId
* @param forceUnlock
* @return
* @throws RecordLockedException
* @throws MultipleEditException
*/
@Transactional
public synchronized CollectRecord checkout(CollectSurvey survey, User user, int recordId, int step, String sessionId, boolean forceUnlock) throws RecordLockedException, MultipleEditException {
isLockAllowed(user, recordId, sessionId, forceUnlock);
lock(recordId, user, sessionId, forceUnlock);
CollectRecord record = recordDao.load(survey, recordId, step);
return record;
}
@Transactional
public CollectRecord load(CollectSurvey survey, int recordId, int step) throws RecordPersistenceException {
CollectRecord record = recordDao.load(survey, recordId, step);
return record;
}
@Transactional
public List<CollectRecord> getSummaries(CollectSurvey survey, String rootEntity, String... keys) {
return recordDao.loadSummaries(survey, rootEntity, keys);
}
@Transactional
public List<CollectRecord> loadSummaries(CollectSurvey survey, String rootEntity, int offset, int maxNumberOfRecords, List<RecordSummarySortField> sortFields, String... keyValues) {
List<CollectRecord> recordsSummary = recordDao.loadSummaries(survey, rootEntity, offset, maxNumberOfRecords, sortFields, keyValues);
return recordsSummary;
}
@Transactional
public int getRecordCount(CollectSurvey survey, String rootEntity, String... keyValues) {
Schema schema = survey.getSchema();
EntityDefinition rootEntityDefinition = schema.getRootEntityDefinition(rootEntity);
int count = recordDao.countRecords(rootEntityDefinition.getId(), keyValues);
return count;
}
@Transactional
public CollectRecord create(CollectSurvey survey, EntityDefinition rootEntityDefinition, User user, String modelVersionName, String sessionId) throws RecordPersistenceException {
CollectRecord record = new CollectRecord(survey, modelVersionName);
record.createRootEntity(rootEntityDefinition.getName());
record.setCreationDate(new Date());
record.setCreatedBy(user);
record.setStep(Step.ENTRY);
return record;
}
@Transactional
public void promote(CollectRecord record, User user) throws RecordPromoteException, MissingRecordKeyException {
Integer errors = record.getErrors();
Integer skipped = record.getSkipped();
Integer missing = record.getMissingErrors();
int totalErrors = errors + skipped + missing;
if( totalErrors > 0 ){
throw new RecordPromoteException("Record cannot be promoted becuase it contains errors.");
}
record.updateRootEntityKeyValues();
checkAllKeysSpecified(record);
record.updateEntityCounts();
Integer id = record.getId();
// before save record in current step
if( id == null ) {
recordDao.insert( record );
} else {
recordDao.update( record );
}
applyDefaultValues(record);
//change step and update the record
Step currentStep = record.getStep();
Step nextStep = currentStep.getNext();
Date now = new Date();
record.setModifiedBy( user );
record.setModifiedDate( now );
record.setState( null );
/**
* 1. clear node states
* 2. update record step
* 3. update all validation states
*/
record.clearNodeStates();
record.setStep( nextStep );
record.updateDerivedStates();
recordDao.update( record );
}
/**
* Applies default values on each descendant attribute of a record in which empty nodes have already been added.
* Default values are applied only to "empty" attributes.
*
* @param record
* @throws InvalidExpressionException
*/
protected void applyDefaultValues(CollectRecord record) {
Entity rootEntity = record.getRootEntity();
applyDefaultValues(rootEntity);
}
/**
* Applies default values on each descendant attribute of an Entity in which empty nodes have already been added.
* Default values are applied only to "empty" attributes.
*
* @param entity
* @throws InvalidExpressionException
*/
protected void applyDefaultValues(Entity entity) {
List<Node<?>> children = entity.getChildren();
for (Node<?> child: children) {
if ( child instanceof Attribute ) {
Attribute<?, ?> attribute = (Attribute<?, ?>) child;
if ( attribute.isEmpty() ) {
applyDefaultValue(attribute);
}
} else if ( child instanceof Entity ) {
applyDefaultValues((Entity) child);
}
}
}
public <V> void applyDefaultValue(Attribute<?, V> attribute) {
AttributeDefinition attributeDefn = (AttributeDefinition) attribute.getDefinition();
List<AttributeDefault> defaults = attributeDefn.getAttributeDefaults();
if ( defaults != null && defaults.size() > 0 ) {
for (AttributeDefault attributeDefault : defaults) {
try {
V value = attributeDefault.evaluate(attribute);
if ( value != null ) {
attribute.setValue(value);
clearRelevanceRequiredStates(attribute);
clearValidationResults(attribute);
}
} catch (InvalidExpressionException e) {
log.warn("Error applying default value for attribute " + attributeDefn.getPath());
}
}
}
}
@Transactional
public void demote(CollectSurvey survey, int recordId, Step currentStep, User user) throws RecordPersistenceException {
Step prevStep = currentStep.getPrevious();
CollectRecord record = recordDao.load( survey, recordId, prevStep.getStepNumber() );
record.setModifiedBy( user );
record.setModifiedDate( new Date() );
record.setStep( prevStep );
record.setState( State.REJECTED );
record.updateDerivedStates();
recordDao.update( record );
}
public Entity addEntity(Entity parentEntity, String nodeName) {
Entity entity = parentEntity.addEntity(nodeName);
addEmptyNodes(entity);
return entity;
}
public void addEmptyNodes(Entity entity) {
Record record = entity.getRecord();
ModelVersion version = record.getVersion();
addEmptyEnumeratedEntities(entity);
EntityDefinition entityDefn = entity.getDefinition();
List<NodeDefinition> childDefinitions = entityDefn.getChildDefinitions();
for (NodeDefinition nodeDefn : childDefinitions) {
if(version.isApplicable(nodeDefn)) {
String name = nodeDefn.getName();
if(entity.getCount(name) == 0) {
int count = 0;
int toBeInserted = entity.getEffectiveMinCount(name);
String layout = nodeDefn.getAnnotation(LAYOUT_ANNOTATION);
if(nodeDefn instanceof AttributeDefinition || (! (nodeDefn.isMultiple() && "form".equals(layout)))) {
//insert at least one node
toBeInserted = 1;
}
while(count < toBeInserted) {
if(nodeDefn instanceof AttributeDefinition) {
Node<?> createNode = nodeDefn.createNode();
entity.add(createNode);
} else if(nodeDefn instanceof EntityDefinition) {
addEntity(entity, name);
}
count ++;
}
} else {
List<Node<?>> all = entity.getAll(name);
for (Node<?> node : all) {
if(node instanceof Entity) {
addEmptyNodes((Entity) node);
}
}
}
}
}
}
@SuppressWarnings("unchecked")
public <V> void setFieldValue(Attribute<?,?> attribute, Object value, String remarks, FieldSymbol symbol, int fieldIdx){
if(fieldIdx < 0){
fieldIdx = 0;
}
Field<V> field = (Field<V>) attribute.getField(fieldIdx);
field.setValue((V)value);
field.setRemarks(remarks);
Character symbolChar = null;
if (symbol != null) {
symbolChar = symbol.getCode();
}
field.setSymbol(symbolChar);
}
@SuppressWarnings("unchecked")
public <V> void setAttributeValue(Attribute<?,V> attribute, Object value, String remarks){
attribute.setValue((V)value);
Field<V> field = (Field<V>) attribute.getField(0);
field.setRemarks(remarks);
field.setSymbol(null);
}
public Set<Attribute<?, ?>> clearValidationResults(Attribute<?,?> attribute){
Set<Attribute<?,?>> checkDependencies = attribute.getCheckDependencies();
clearValidationResults(checkDependencies);
return checkDependencies;
}
public void clearValidationResults(Set<Attribute<?, ?>> checkDependencies) {
for (Attribute<?, ?> attr : checkDependencies) {
attr.clearValidationResults();
}
}
public Set<NodePointer> clearRelevanceRequiredStates(Node<?> node){
Set<NodePointer> relevantDependencies = node.getRelevantDependencies();
clearRelevantDependencies(relevantDependencies);
Set<NodePointer> requiredDependencies = node.getRequiredDependencies();
requiredDependencies.addAll(relevantDependencies);
clearRequiredDependencies(requiredDependencies);
return requiredDependencies;
}
public void clearRelevantDependencies(Set<NodePointer> nodePointers) {
for (NodePointer nodePointer : nodePointers) {
Entity entity = nodePointer.getEntity();
entity.clearRelevanceState(nodePointer.getChildName());
}
}
public void clearRequiredDependencies(Set<NodePointer> nodePointers) {
for (NodePointer nodePointer : nodePointers) {
Entity entity = nodePointer.getEntity();
entity.clearRequiredState(nodePointer.getChildName());
}
}
private void addEmptyEnumeratedEntities(Entity entity) {
Record record = entity.getRecord();
ModelVersion version = record.getVersion();
EntityDefinition entityDefn = entity.getDefinition();
List<NodeDefinition> childDefinitions = entityDefn.getChildDefinitions();
for (NodeDefinition childDefn : childDefinitions) {
if(childDefn instanceof EntityDefinition && version.isApplicable(childDefn)) {
EntityDefinition childEntityDefn = (EntityDefinition) childDefn;
if(childEntityDefn.isMultiple() && childEntityDefn.isEnumerable()) {
addEmptyEnumeratedEntities(entity, childEntityDefn);
}
}
}
}
private void addEmptyEnumeratedEntities(Entity entity, EntityDefinition enumeratedEntityDefn) {
Record record = entity.getRecord();
ModelVersion version = record.getVersion();
CodeAttributeDefinition enumeratingCodeDefn = getEnumeratingKeyCodeAttribute(enumeratedEntityDefn, version);
if(enumeratingCodeDefn != null) {
CodeList list = enumeratingCodeDefn.getList();
List<CodeListItem> items = list.getItems();
for (CodeListItem item : items) {
if(version.isApplicable(item)) {
String code = item.getCode();
if(! hasEnumeratedEntity(entity, enumeratedEntityDefn, enumeratingCodeDefn, code)) {
Entity addedEntity = addEntity(entity, enumeratedEntityDefn.getName());
//there will be an empty CodeAttribute after the adding of the new entity
//set the value into this node
CodeAttribute addedCode = (CodeAttribute) addedEntity.get(enumeratingCodeDefn.getName(), 0);
addedCode.setValue(new Code(code));
}
}
}
}
}
private CodeAttributeDefinition getEnumeratingKeyCodeAttribute(EntityDefinition entity, ModelVersion version) {
List<AttributeDefinition> keys = entity.getKeyAttributeDefinitions();
for (AttributeDefinition key: keys) {
if(key instanceof CodeAttributeDefinition && version.isApplicable(key)) {
CodeAttributeDefinition codeDefn = (CodeAttributeDefinition) key;
if(codeDefn.getList().getLookupTable() == null) {
return codeDefn;
}
}
}
return null;
}
private boolean hasEnumeratedEntity(Entity parentEntity, EntityDefinition childEntityDefn,
CodeAttributeDefinition enumeratingCodeAttributeDef, String value) {
List<Node<?>> children = parentEntity.getAll(childEntityDefn.getName());
for (Node<?> node : children) {
Entity child = (Entity) node;
Code code = getCodeAttributeValue(child, enumeratingCodeAttributeDef);
if(code != null && value.equals(code.getCode())) {
return true;
}
}
return false;
}
private Code getCodeAttributeValue(Entity entity, CodeAttributeDefinition def) {
Node<?> node = entity.get(def.getName(), 0);
if(node != null) {
return ((CodeAttribute)node).getValue();
} else {
return null;
}
}
private void checkAllKeysSpecified(CollectRecord record) throws MissingRecordKeyException {
List<String> rootEntityKeyValues = record.getRootEntityKeyValues();
Entity rootEntity = record.getRootEntity();
EntityDefinition rootEntityDefn = rootEntity.getDefinition();
List<AttributeDefinition> keyAttributeDefns = rootEntityDefn.getKeyAttributeDefinitions();
for (int i = 0; i < keyAttributeDefns.size(); i++) {
AttributeDefinition keyAttrDefn = keyAttributeDefns.get(i);
if ( rootEntity.isRequired(keyAttrDefn.getName()) ) {
String keyValue = rootEntityKeyValues.get(i);
if ( StringUtils.isBlank(keyValue) ) {
throw new MissingRecordKeyException();
}
}
}
}
/* --- START OF LOCKING METHODS --- */
public synchronized void releaseLock(int recordId) {
RecordLock lock = getLock(recordId);
if ( lock != null ) {
locks.remove(recordId);
}
}
public synchronized boolean checkIsLocked(int recordId, User user, String sessionId) throws RecordUnlockedException {
RecordLock lock = getLock(recordId);
String lockUserName = null;
if ( lock != null) {
String lockSessionId = lock.getSessionId();
int lockRecordId = lock.getRecordId();
User lUser = lock.getUser();
if( recordId == lockRecordId &&
( lUser == user || lUser.getId() == user.getId() ) &&
lockSessionId.equals(sessionId) ) {
lock.keepAlive();
return true;
} else {
User lockUser = lock.getUser();
lockUserName = lockUser.getName();
}
}
throw new RecordUnlockedException(lockUserName);
}
private synchronized void lock(int recordId, User user, String sessionId) throws RecordLockedException, MultipleEditException {
lock(recordId, user, sessionId, false);
}
private synchronized void lock(int recordId, User user, String sessionId, boolean forceUnlock) throws RecordLockedException, MultipleEditException {
RecordLock oldLock = getLock(recordId);
if ( oldLock != null ) {
locks.remove(recordId);
}
RecordLock lock = new RecordLock(sessionId, recordId, user, lockTimeoutMillis);
locks.put(recordId, lock);
}
private boolean isForceUnlockAllowed(User user, RecordLock lock) {
boolean isAdmin = user.hasRole("ROLE_ADMIN");
Integer userId = user.getId();
User lockUser = lock.getUser();
return isAdmin || userId.equals(lockUser.getId());
}
private synchronized boolean isLockAllowed(User user, int recordId, String sessionId, boolean forceUnlock) throws RecordLockedException, MultipleEditException {
RecordLock uLock = getLockBySessionId(sessionId);
if ( uLock != null ) {
throw new MultipleEditException("User is editing another record: " + uLock.getRecordId());
}
RecordLock lock = getLock(recordId);
if ( lock == null || ( forceUnlock && isForceUnlockAllowed(user, lock) ) ) {
return true;
} else if ( lock.getUser().getId().equals(user.getId()) ) {
throw new RecordLockedByActiveUserException(user.getName());
} else {
String lockingUserName = lock.getUser().getName();
throw new RecordLockedException("Record already locked", lockingUserName);
}
}
private synchronized boolean isLocked(int recordId) {
RecordLock lock = getLock(recordId);
return lock != null;
}
private synchronized RecordLock getLock(int recordId) {
clearInactiveLocks();
RecordLock lock = locks.get(recordId);
return lock;
}
private synchronized RecordLock getLockBySessionId(String sessionId) {
clearInactiveLocks();
Collection<RecordLock> lcks = locks.values();
for (RecordLock l : lcks) {
if ( l.getSessionId().equals(sessionId) ) {
return l;
}
}
return null;
}
private synchronized void clearInactiveLocks() {
Set<Entry<Integer, RecordLock>> entrySet = locks.entrySet();
Iterator<Entry<Integer, RecordLock>> iterator = entrySet.iterator();
while (iterator.hasNext()) {
Entry<Integer, RecordLock> entry = iterator.next();
RecordLock lock = entry.getValue();
if( !lock.isActive() ){
iterator.remove();
}
}
}
/* --- END OF LOCKING METHODS --- */
/**
* GETTERS AND SETTERS
*/
public long getLockTimeoutMillis() {
return lockTimeoutMillis;
}
public void setLockTimeoutMillis(long timeoutMillis) {
this.lockTimeoutMillis = timeoutMillis;
}
}
| Added moveNode function | collect-core/src/main/java/org/openforis/collect/manager/RecordManager.java | Added moveNode function |
|
Java | mpl-2.0 | ad0712175a267b27bd969a03c4edb9a63ef81b94 | 0 | qhanam/rhino,ashwinrayaprolu1984/rhino,ashwinrayaprolu1984/rhino,swannodette/rhino,jsdoc3/rhino,tntim96/rhino-jscover,tuchida/rhino,tuchida/rhino,Angelfirenze/rhino,Distrotech/rhino,tuchida/rhino,tntim96/rhino-apigee,lv7777/egit_test,lv7777/egit_test,Angelfirenze/rhino,sam/htmlunit-rhino-fork,ashwinrayaprolu1984/rhino,Pilarbrist/rhino,sainaen/rhino,AlexTrotsenko/rhino,tuchida/rhino,Angelfirenze/rhino,tejassaoji/RhinoCoarseTainting,sainaen/rhino,lv7777/egit_test,lv7777/egit_test,rasmuserik/rhino,InstantWebP2P/rhino-android,tejassaoji/RhinoCoarseTainting,tntim96/rhino-apigee,Angelfirenze/rhino,AlexTrotsenko/rhino,tejassaoji/RhinoCoarseTainting,tejassaoji/RhinoCoarseTainting,jsdoc3/rhino,tntim96/rhino-jscover-repackaged,tejassaoji/RhinoCoarseTainting,AlexTrotsenko/rhino,Distrotech/rhino,swannodette/rhino,AlexTrotsenko/rhino,sam/htmlunit-rhino-fork,qhanam/rhino,sam/htmlunit-rhino-fork,lv7777/egit_test,swannodette/rhino,AlexTrotsenko/rhino,sam/htmlunit-rhino-fork,tntim96/rhino-jscover,Angelfirenze/rhino,qhanam/rhino,ashwinrayaprolu1984/rhino,sam/htmlunit-rhino-fork,tuchida/rhino,sainaen/rhino,sam/htmlunit-rhino-fork,Pilarbrist/rhino,Pilarbrist/rhino,swannodette/rhino,swannodette/rhino,Angelfirenze/rhino,tejassaoji/RhinoCoarseTainting,swannodette/rhino,tntim96/htmlunit-rhino-fork,sainaen/rhino,qhanam/rhino,lv7777/egit_test,tuchida/rhino,Angelfirenze/rhino,tuchida/rhino,sainaen/rhino,sainaen/rhino,rasmuserik/rhino,Pilarbrist/rhino,ashwinrayaprolu1984/rhino,tntim96/rhino-jscover-repackaged,sainaen/rhino,lv7777/egit_test,ashwinrayaprolu1984/rhino,Pilarbrist/rhino,swannodette/rhino,tntim96/htmlunit-rhino-fork,tntim96/rhino-apigee,jsdoc3/rhino,sam/htmlunit-rhino-fork,ashwinrayaprolu1984/rhino,Pilarbrist/rhino,tejassaoji/RhinoCoarseTainting,InstantWebP2P/rhino-android,AlexTrotsenko/rhino,AlexTrotsenko/rhino,Pilarbrist/rhino | /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1997-1999
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Norris Boyd
* Roger Lawrence
*
* Alternatively, the contents of this file may be used under the terms of
* the GNU General Public License Version 2 or later (the "GPL"), in which
* case the provisions of the GPL are applicable instead of those above. If
* you wish to allow use of your version of this file only under the terms of
* the GPL and not to allow others to use your version of this file under the
* MPL, indicate your decision by deleting the provisions above and replacing
* them with the notice and other provisions required by the GPL. If you do
* not delete the provisions above, a recipient may use your version of this
* file under either the MPL or the GPL.
*
* ***** END LICENSE BLOCK ***** */
package org.mozilla.javascript;
/**
* A proxy for the regexp package, so that the regexp package can be
* loaded optionally.
*
* @author Norris Boyd
*/
public interface RegExpProxy
{
// Types of regexp actions
public static final int RA_MATCH = 1;
public static final int RA_REPLACE = 2;
public static final int RA_SEARCH = 3;
public boolean isRegExp(Scriptable obj);
public Object compileRegExp(Context cx, String source, String flags);
public Scriptable wrapRegExp(Context cx, Scriptable scope,
Object compiled);
public Object action(Context cx, Scriptable scope,
Scriptable thisObj, Object[] args,
int actionType);
public int find_split(Context cx, Scriptable scope, String target,
String separator, Scriptable re,
int[] ip, int[] matchlen,
boolean[] matched, String[][] parensp);
public Object js_split(Context _cx, Scriptable _scope,
String thisString, Object[] _args);
}
| src/org/mozilla/javascript/RegExpProxy.java | /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1997-1999
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Norris Boyd
* Roger Lawrence
*
* Alternatively, the contents of this file may be used under the terms of
* the GNU General Public License Version 2 or later (the "GPL"), in which
* case the provisions of the GPL are applicable instead of those above. If
* you wish to allow use of your version of this file only under the terms of
* the GPL and not to allow others to use your version of this file under the
* MPL, indicate your decision by deleting the provisions above and replacing
* them with the notice and other provisions required by the GPL. If you do
* not delete the provisions above, a recipient may use your version of this
* file under either the MPL or the GPL.
*
* ***** END LICENSE BLOCK ***** */
package org.mozilla.javascript;
/**
* A proxy for the regexp package, so that the regexp package can be
* loaded optionally.
*
* @author Norris Boyd
*/
public interface RegExpProxy
{
// Types of regexp actions
public static final int RA_MATCH = 1;
public static final int RA_REPLACE = 2;
public static final int RA_SEARCH = 3;
public boolean isRegExp(Scriptable obj);
public Object compileRegExp(Context cx, String source, String flags);
public Scriptable wrapRegExp(Context cx, Scriptable scope,
Object compiled);
public Object action(Context cx, Scriptable scope,
Scriptable thisObj, Object[] args,
int actionType);
public int find_split(Context cx, Scriptable scope, String target,
String separator, Scriptable re,
int[] ip, int[] matchlen,
boolean[] matched, String[][] parensp);
public Object js_split(Context _cx, Scriptable _scope, String thisString, Object[] _args);
}
| Fix formatting
| src/org/mozilla/javascript/RegExpProxy.java | Fix formatting |
|
Java | lgpl-2.1 | a66e6e21d241e1aacedf7e390aed68b46099fca2 | 0 | CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine | /*
* jETeL/CloverETL - Java based ETL application framework.
* Copyright (c) Javlin, a.s. ([email protected])
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.jetel.component;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.Pipe;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetel.component.tree.reader.AbortParsingException;
import org.jetel.component.tree.reader.DataRecordProvider;
import org.jetel.component.tree.reader.DataRecordReceiver;
import org.jetel.component.tree.reader.FieldFillingException;
import org.jetel.component.tree.reader.InputAdapter;
import org.jetel.component.tree.reader.TreeReaderParserProvider;
import org.jetel.component.tree.reader.TreeStreamParser;
import org.jetel.component.tree.reader.TreeXMLReaderAdaptor;
import org.jetel.component.tree.reader.TreeXmlContentHandlerAdapter;
import org.jetel.component.tree.reader.XPathEvaluator;
import org.jetel.component.tree.reader.XPathPushParser;
import org.jetel.component.tree.reader.XPathSequenceProvider;
import org.jetel.component.tree.reader.mappping.FieldMapping;
import org.jetel.component.tree.reader.mappping.FieldNameEncoder;
import org.jetel.component.tree.reader.mappping.ImplicitMappingAddingVisitor;
import org.jetel.component.tree.reader.mappping.MalformedMappingException;
import org.jetel.component.tree.reader.mappping.MappingContext;
import org.jetel.component.tree.reader.mappping.MappingElementFactory;
import org.jetel.component.tree.reader.mappping.MappingVisitor;
import org.jetel.component.tree.reader.xml.XmlXPathEvaluator;
import org.jetel.data.DataField;
import org.jetel.data.DataRecord;
import org.jetel.data.DataRecordFactory;
import org.jetel.data.Defaults;
import org.jetel.data.sequence.Sequence;
import org.jetel.data.sequence.SequenceFactory;
import org.jetel.exception.AttributeNotFoundException;
import org.jetel.exception.BadDataFormatException;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.exception.ConfigurationProblem;
import org.jetel.exception.ConfigurationStatus;
import org.jetel.exception.ConfigurationStatus.Priority;
import org.jetel.exception.ConfigurationStatus.Severity;
import org.jetel.exception.JetelException;
import org.jetel.exception.JetelRuntimeException;
import org.jetel.exception.PolicyType;
import org.jetel.exception.XMLConfigurationException;
import org.jetel.graph.Node;
import org.jetel.graph.OutputPort;
import org.jetel.graph.Result;
import org.jetel.graph.TransformationGraph;
import org.jetel.graph.runtime.CloverWorker;
import org.jetel.graph.runtime.FutureOfRunnable;
import org.jetel.metadata.DataFieldMetadata;
import org.jetel.metadata.DataFieldType;
import org.jetel.metadata.DataRecordMetadata;
import org.jetel.sequence.PrimitiveSequence;
import org.jetel.util.AutoFilling;
import org.jetel.util.ExceptionUtils;
import org.jetel.util.SourceIterator;
import org.jetel.util.XmlUtils;
import org.jetel.util.file.FileUtils;
import org.jetel.util.property.ComponentXMLAttributes;
import org.jetel.util.property.RefResFlag;
import org.jetel.util.string.StringUtils;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
/**
* @author lkrejci ([email protected]) (c) Javlin, a.s. (www.cloveretl.com)
*
* @created 19 Jan 2012
*/
public abstract class TreeReader extends Node implements DataRecordProvider, DataRecordReceiver, XPathSequenceProvider {
/**
* TreeReader works in several processing modes. Chosen processing mode depends on provided
* {@link TreeReaderParserProvider} and mapping complexity. The priority of modes:
* <ol>
* <li>{@link ProcessingMode#STREAM}</li>
* <li>{@link ProcessingMode#XPATH_DIRECT}</li>
* <li>{@link ProcessingMode#XPATH_CONVERT_STREAM}</li>
* </ol>
*
* @author krejcil ([email protected]) (c) Javlin, a.s. (www.cloveretl.com)
*/
private static enum ProcessingMode {
/**
* #NOT IMPLEMENTED# {@link TreeReaderParserProvider} provides {@link TreeStreamParser} and mapping is simple
* enough input is processed in SAX-like manner
*/
STREAM,
/**
* {@link TreeReaderParserProvider} provides {@link XPathEvaluator} xpath expressions are evaluated directly on
* input
*/
XPATH_DIRECT,
/**
* {@link TreeReaderParserProvider} provides {@link TreeReaderParserProvider} -- input is converted to xml and
* xml xpath evaluator is used to resolve xpath expressions on converted input
*/
XPATH_CONVERT_STREAM
}
private static final Log LOG = LogFactory.getLog(TreeReader.class);
private static final int INPUT_PORT_INDEX = 0;
// this attribute is not used at runtime right now
public static final String XML_SCHEMA_ATTRIBUTE = "schema";
protected final static String XML_FILE_URL_ATTRIBUTE = "fileURL";
public final static String XML_MAPPING_URL_ATTRIBUTE = "mappingURL";
public final static String XML_MAPPING_ATTRIBUTE = "mapping";
public final static String XML_DATAPOLICY_ATTRIBUTE = "dataPolicy";
public static final String XML_CHARSET_ATTRIBUTE = "charset";
public static final String XML_IMPLICIT_MAPPING_ATTRIBUTE = "implicitMapping";
protected static void readCommonAttributes(TreeReader treeReader, ComponentXMLAttributes xattribs)
throws XMLConfigurationException, AttributeNotFoundException {
treeReader.setFileURL(xattribs.getStringEx(XML_FILE_URL_ATTRIBUTE, null, RefResFlag.URL));
if (xattribs.exists(XML_CHARSET_ATTRIBUTE)) {
treeReader.setCharset(xattribs.getString(XML_CHARSET_ATTRIBUTE));
}
treeReader.setPolicyType(xattribs.getString(XML_DATAPOLICY_ATTRIBUTE, null));
String mappingURL = xattribs.getStringEx(XML_MAPPING_URL_ATTRIBUTE, null, RefResFlag.URL);
String mapping = xattribs.getString(XML_MAPPING_ATTRIBUTE, null);
if (mappingURL != null) {
treeReader.setMappingURL(mappingURL);
} else {
treeReader.setMappingString(mapping);
}
treeReader.setImplicitMapping(xattribs.getBoolean(XML_IMPLICIT_MAPPING_ATTRIBUTE, false));
}
// DataRecordProvider, DataRecordReceiver, XPathSequenceProvider properties
private DataRecord outputRecords[];
private OutputPort outputPorts[];
private boolean recordReadWithException[];
private String defaultSequenceId;
protected String fileURL;
protected String charset;
private SourceIterator sourceIterator;
private String policyTypeStr;
private PolicyType policyType;
private String mappingString;
private String mappingURL;
private boolean implicitMapping;
private TreeReaderParserProvider parserProvider;
private TreeProcessor treeProcessor;
private AutoFilling autoFilling = new AutoFilling();
private int[] sourcePortRecordCounters; // counters of records written to particular ports per source
private boolean errorPortLogging;
private DataRecord errorLogRecord;
private int maxErrors = -1;
private int errorsCount;
public TreeReader(String id) {
super(id);
}
protected abstract TreeReaderParserProvider getTreeReaderParserProvider();
protected FieldNameEncoder getFieldNameEncoder() {
// no encoding by default
return null;
}
protected ConfigurationStatus disallowEmptyCharsetOnDictionaryAndPort(ConfigurationStatus status) {
ConfigurationStatus configStatus = super.checkConfig(status);
for (String fileUrlEntry : this.getFileUrl().split(";")) {
if ((fileUrlEntry.startsWith("dict:") || fileUrlEntry.startsWith("port:")) && charset == null) {
status.add(new ConfigurationProblem("Charset cannot be auto-detected for input from a port or dictionary. Define it in the \"Charset\" attribute explicitly.", ConfigurationStatus.Severity.ERROR, this, ConfigurationStatus.Priority.NORMAL));
}
}
return configStatus;
}
@Override
public ConfigurationStatus checkConfig(ConfigurationStatus status) {
super.checkConfig(status);
if (!checkInputPorts(status, 0, 1) || !checkOutputPorts(status, 1, Integer.MAX_VALUE)) {
return status;
}
if (!PolicyType.isPolicyType(policyTypeStr)) {
status.add("Invalid data policy: " + policyTypeStr, Severity.ERROR, this, Priority.NORMAL, XML_DATAPOLICY_ATTRIBUTE);
} else {
policyType = PolicyType.valueOfIgnoreCase(policyTypeStr);
}
if (StringUtils.isEmpty(this.getFileUrl())) {
status.add(new ConfigurationProblem("Missing required attribute 'File URL'", ConfigurationStatus.Severity.ERROR, this, ConfigurationStatus.Priority.NORMAL, XML_FILE_URL_ATTRIBUTE));
}
if (StringUtils.isEmpty(mappingURL) && StringUtils.isEmpty(mappingString)) {
status.add(new ConfigurationProblem("Missing required attribute 'Mapping'", ConfigurationStatus.Severity.ERROR, this, ConfigurationStatus.Priority.NORMAL));
}
if (charset != null && !Charset.isSupported(charset)) {
status.add(new ConfigurationProblem("Charset " + charset + " not supported!", ConfigurationStatus.Severity.ERROR, this, ConfigurationStatus.Priority.NORMAL, XML_CHARSET_ATTRIBUTE));
}
/*
* TODO validate mapping model in checkConfig with respect to port metadata i.e. that there are all fields
* available and all mentioned ports are connected
*/
return status;
}
@Override
public void init() throws ComponentNotReadyException {
if (isInitialized()) {
return;
}
super.init();
policyType = PolicyType.valueOfIgnoreCase(policyTypeStr);
this.parserProvider = getTreeReaderParserProvider();
recordProviderReceiverInit();
for (OutputPort outPort : outPortsArray) {
autoFilling.addAutoFillingFields(outPort.getMetadata());
}
sourcePortRecordCounters = new int[outPortsSize];
sourceIterator = createSourceIterator();
// FIXME: mapping should not be initialized here in init if is passed via external file, since it is possible
// that mapping file does not exist at this moment, or its content can change
MappingContext rootContext = createMapping();
if (implicitMapping) {
MappingVisitor implicitMappingVisitor = new ImplicitMappingAddingVisitor(getOutMetadata(), getFieldNameEncoder());
rootContext.acceptVisitor(implicitMappingVisitor);
}
XPathPushParser pushParser;
ProcessingMode processingMode = resolveProcessingMode();
switch (processingMode) {
case XPATH_CONVERT_STREAM:
pushParser = new XPathPushParser(this, this, new XmlXPathEvaluator(), parserProvider.getValueHandler(), this);
treeProcessor = new StreamConvertingXPathProcessor(parserProvider, pushParser, rootContext, charset);
break;
case XPATH_DIRECT:
pushParser = new XPathPushParser(this, this, parserProvider.getXPathEvaluator(), parserProvider.getValueHandler(), this);
InputAdapter inputAdapter = parserProvider.getInputAdapter();
treeProcessor = new XPathProcessor(pushParser, rootContext, inputAdapter);
break;
default:
throw new UnsupportedOperationException("Processing mode " + processingMode + " is not supported");
}
errorPortLogging = isErrorPortLogging(rootContext);
if (errorPortLogging) {
LOG.info("Using port " + getErrorPortIndex() + " as error logging port");
errorLogRecord = DataRecordFactory.newRecord(getOutputPort(getErrorPortIndex()).getMetadata());
}
}
private void recordProviderReceiverInit() {
int portCount = getOutPorts().size();
outputRecords = new DataRecord[portCount];
outputPorts = new OutputPort[portCount];
recordReadWithException = new boolean[portCount];
for (int i = 0; i < portCount; ++i) {
OutputPort port = getOutputPort(i);
outputPorts[i] = port;
DataRecord record = DataRecordFactory.newRecord(port.getMetadata());
outputRecords[i] = record;
}
}
private ProcessingMode resolveProcessingMode() {
if (parserProvider.providesXPathEvaluator()) {
return ProcessingMode.XPATH_DIRECT;
} else if (parserProvider.providesTreeStreamParser()) {
return ProcessingMode.XPATH_CONVERT_STREAM;
} else {
throw new IllegalStateException("Invalid parser provider configuration");
}
}
protected MappingContext createMapping() throws ComponentNotReadyException {
Document mappingDocument;
try {
if (mappingURL != null) {
ReadableByteChannel ch = FileUtils.getReadableChannel(getContextURL(), mappingURL);
mappingDocument = XmlUtils.createDocumentFromChannel(ch);
} else {
mappingDocument = XmlUtils.createDocumentFromString(mappingString);
}
} catch (IOException e) {
throw new ComponentNotReadyException("Mapping parameter parse error occured.", e);
} catch (JetelException e) {
throw new ComponentNotReadyException("Mapping parameter parse error occured.", e);
}
try {
return new MappingElementFactory().readMapping(mappingDocument);
} catch (MalformedMappingException e) {
throw new ComponentNotReadyException("Input mapping is not valid.", e);
}
}
protected SourceIterator createSourceIterator() {
TransformationGraph graph = getGraph();
URL projectURL = getContextURL();
SourceIterator iterator = new SourceIterator(getInputPort(INPUT_PORT_INDEX), projectURL, fileURL);
iterator.setCharset(charset);
iterator.setPropertyRefResolver(getPropertyRefResolver());
iterator.setDictionary(graph.getDictionary());
return iterator;
}
/**
* @return true iff the last out port is not used in the mapping and it has prescribed metadata
*/
private boolean isErrorPortLogging(MappingContext rootContext) {
OutputPort errorPortCandidate = outPortsArray[getErrorPortIndex()];
if (isPortUsed(errorPortCandidate.getOutputPortNumber(), rootContext)) {
return false;
} else {
if (hasErrorLoggingMetadata(errorPortCandidate)) {
return true;
} else {
LOG.warn("If the last output port is intended for error logging, metadata should be: "
+ "integer (out port number), integer (record number per source and port), integer (field number), "
+ "string (field name), string (value which caused the error), string (error message), string (source name - optional field)");
return false;
}
}
}
private int getErrorPortIndex() {
return outPortsSize - 1;
}
private boolean hasErrorLoggingMetadata(OutputPort errorPort) {
DataRecordMetadata metadata = errorPort.getMetadata();
int errorNumFields = metadata.getNumFields();
return (errorNumFields == 6 || errorNumFields == 7)
&& metadata.getField(0).getDataType() == DataFieldType.INTEGER // port number
&& metadata.getField(1).getDataType() == DataFieldType.INTEGER // port record number per source
&& metadata.getField(2).getDataType() == DataFieldType.INTEGER // field number
&& isStringOrByte(metadata.getField(3)) // field name
&& isStringOrByte(metadata.getField(4)) // offending value
&& isStringOrByte(metadata.getField(5)) // error message
&& (errorNumFields == 6 || isStringOrByte(metadata.getField(6))); // optional source name
}
private boolean isStringOrByte(DataFieldMetadata field) {
return field.getDataType() == DataFieldType.STRING || field.getDataType() == DataFieldType.BYTE || field.getDataType() == DataFieldType.CBYTE;
}
private static boolean isPortUsed(int portIndex, MappingContext rootContext) {
PortUsageMappingVisitor portUsageMappingVisitor = new PortUsageMappingVisitor();
rootContext.acceptVisitor(portUsageMappingVisitor);
return portUsageMappingVisitor.isPortUsed(portIndex);
}
@Override
public void preExecute() throws ComponentNotReadyException {
super.preExecute();
// FIXME: init of source iterator is not implemented well right now, so it has to be called here in preExecute!
sourceIterator.init();
sourceIterator.preExecute();
}
@Override
public Result execute() throws Exception {
Object inputData = getNextSource();
while (inputData != null) {
try {
treeProcessor.processInput(inputData, sourceIterator.getCurrenRecord());
} catch (AbortParsingException e) {
if (!runIt) {
return Result.ABORTED;
} else if (e.getCause() instanceof MaxErrorsCountExceededException) {
return Result.ERROR;
} else if (e.getCause() instanceof Exception) { // TODO BadDataFormatException / Exception ?
throw (Exception) e.getCause();
}
} finally {
if (inputData instanceof Closeable) {
try {
((Closeable) inputData).close();
} catch (Exception ex) {
LOG.error("Failed to close input");
}
}
}
inputData = getNextSource();
}
return runIt ? Result.FINISHED_OK : Result.ABORTED;
}
@Override
public void postExecute() throws ComponentNotReadyException {
super.postExecute();
}
@Override
public String[] getUsedUrls() {
return new String[] { fileURL };
}
private Object getNextSource() throws JetelException {
Object input = null;
while (sourceIterator.hasNext()) {
input = sourceIterator.next();
if (input == null) {
continue; // if record no record found
}
autoFilling.resetSourceCounter();
autoFilling.resetGlobalSourceCounter();
autoFilling.setFilename(sourceIterator.getCurrentFileName());
if (!sourceIterator.isGraphDependentSource()) {
long fileSize = 0;
Date fileTimestamp = null;
if (autoFilling.getFilename() != null &&
FileUtils.isLocalFile(null, autoFilling.getFilename()) &&
!sourceIterator.isGraphDependentSource()) {
File tmpFile = new File(autoFilling.getFilename());
long timestamp = tmpFile.lastModified();
fileTimestamp = timestamp == 0 ? null : new Date(timestamp);
fileSize = tmpFile.length();
}
autoFilling.setFileSize(fileSize);
autoFilling.setFileTimestamp(fileTimestamp);
}
Arrays.fill(sourcePortRecordCounters, 0);
return input;
}
sourceIterator.blankRead();
return input;
}
public String getFileUrl() {
return fileURL;
}
public void setFileURL(String fileURL) {
this.fileURL = fileURL;
}
private void setCharset(String charset) {
this.charset = charset;
}
public void setPolicyType(String policyTypeStr) {
this.policyTypeStr = policyTypeStr;
}
public void setMappingString(String mappingString) {
this.mappingString = mappingString;
}
public void setMappingURL(String mappingURL) {
this.mappingURL = mappingURL;
}
public void setImplicitMapping(boolean implicitMapping) {
this.implicitMapping = implicitMapping;
}
@Override
public void receive(DataRecord record, int port) throws AbortParsingException {
if (runIt) {
try {
sourcePortRecordCounters[port]++;
autoFilling.incGlobalCounter();
autoFilling.incSourceCounter();
// FIXME: some autofilling fields should be filled sooner - so that it can be used with combination of
// generated key pointing at autofilled field
autoFilling.setAutoFillingFields(record);
outputPorts[port].writeRecord(record);
} catch (Exception e) {
throw new RuntimeException(e);
}
} else {
throw new AbortParsingException();
}
}
@Override
public void exceptionOccurred(FieldFillingException e) throws AbortParsingException {
if (policyType == PolicyType.STRICT) {
LOG.error("Could not assign data field \"" + e.getFieldMetadata().getName() + "\" ("
+ e.getFieldMetadata().getDataType().getName() + ") on port " + e.getPortIndex(), e.getCause());
throw new AbortParsingException(e);
} else if (policyType == PolicyType.CONTROLLED) {
if (!recordReadWithException[e.getPortIndex()]) {
recordReadWithException[e.getPortIndex()] = true;
sourcePortRecordCounters[e.getPortIndex()]++;
}
if (errorPortLogging) {
writeErrorLogRecord(e);
} else {
BadDataFormatException bdfe = e.getCause();
bdfe.setRecordNumber(sourcePortRecordCounters[e.getPortIndex()]);
bdfe.setFieldNumber(e.getFieldMetadata().getNumber());
bdfe.setFieldName(e.getFieldMetadata().getName());
bdfe.setRecordName(e.getFieldMetadata().getDataRecordMetadata().getName());
String errorMsg = ExceptionUtils.getMessage(bdfe) + "; output port: " + e.getPortIndex();
if (!sourceIterator.isSingleSource()) {
errorMsg += "; input source: " + sourceIterator.getCurrentFileName();
}
LOG.error(errorMsg);
}
if (maxErrors != -1 && ++errorsCount > maxErrors) {
LOG.error("Max errors count exceeded.", e);
throw new AbortParsingException(new MaxErrorsCountExceededException());
}
}
}
private void writeErrorLogRecord(FieldFillingException e) {
int i = 0;
errorLogRecord.getField(i++).setValue(e.getPortIndex());
errorLogRecord.getField(i++).setValue(sourcePortRecordCounters[e.getPortIndex()]);
errorLogRecord.getField(i++).setValue(e.getFieldMetadata().getNumber() + 1);
setCharSequenceToField(e.getFieldMetadata().getName(), errorLogRecord.getField(i++));
setCharSequenceToField(e.getCause().getOffendingValue(), errorLogRecord.getField(i++));
setCharSequenceToField(ExceptionUtils.getMessage(e.getCause()), errorLogRecord.getField(i++));
if (errorLogRecord.getNumFields() > i) {
setCharSequenceToField(sourceIterator.getCurrentFileName(), errorLogRecord.getField(i++));
}
try {
outputPorts[getErrorPortIndex()].writeRecord(errorLogRecord);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
private void setCharSequenceToField(CharSequence charSeq, DataField field) {
if (charSeq == null) {
field.setNull(true);
} else {
field.setNull(false);
if (field.getMetadata().getDataType() == DataFieldType.STRING) {
field.setValue(charSeq);
} else if (field.getMetadata().getDataType() == DataFieldType.BYTE || field.getMetadata().getDataType() == DataFieldType.CBYTE) {
String cs;
if (charset != null) {
cs = charset;
} else {
cs = Defaults.DataParser.DEFAULT_CHARSET_DECODER;
}
try {
field.setValue(charSeq.toString().getBytes(cs));
} catch (UnsupportedEncodingException e) {
LOG.error(getId() + ": failed to write log record", e);
}
} else {
throw new IllegalArgumentException("Type of field \""+ field.getMetadata().getName() +"\" has to be string, byte or cbyte");
}
}
}
@Override
public DataRecord getDataRecord(int port) throws AbortParsingException {
if (runIt) {
recordReadWithException[port] = false;
/*
* answer copy of record instead of re-usage because
* parser could ask for new record without previous record
* having been written
*/
return outputRecords[port].duplicate();
} else {
throw new AbortParsingException();
}
}
@Override
public Sequence getSequence(MappingContext context) {
if (context.getSequenceId() != null) {
Sequence result = getGraph().getSequence(context.getSequenceId());
if (result == null) {
throw new JetelRuntimeException("Could not find sequence: " + context.getSequenceId());
}
return result;
} else {
if (defaultSequenceId == null) {
String id = getId() + "_DefaultSequence";
Sequence defaultSequence = SequenceFactory.createSequence(getGraph(), PrimitiveSequence.SEQUENCE_TYPE,
new Object[] {id, getGraph(), id}, new Class[] {String.class, TransformationGraph.class, String.class});
try {
PrimitiveSequence ps = (PrimitiveSequence)defaultSequence;
ps.setGraph(getGraph());
ps.init();
ps.setStart(1);
} catch (ComponentNotReadyException e) {
throw new JetelRuntimeException(e);
}
getGraph().addSequence(defaultSequence);
defaultSequenceId = id;
}
return getGraph().getSequence(defaultSequenceId);
}
}
/**
* Interface for classes encapsulating the functionality of one {@link ProcessingMode} of TreeReader
*
* @author krejcil ([email protected]) (c) Javlin, a.s. (www.cloveretl.com)
*
* @created 10.3.2012
*/
private interface TreeProcessor {
void processInput(Object input, DataRecord inputRecord) throws Exception;
}
/**
* TreeProcessor implementing {@link ProcessingMode#XPATH_DIRECT} mode
*
* @author krejcil ([email protected]) (c) Javlin, a.s. (www.cloveretl.com)
*
* @created 10.3.2012
*/
private static class XPathProcessor implements TreeProcessor {
private XPathPushParser pushParser;
private MappingContext rootContext;
private InputAdapter inputAdapter;
private XPathProcessor(XPathPushParser pushParser, MappingContext rootContext, InputAdapter inputAdapter) {
this.pushParser = pushParser;
this.rootContext = rootContext;
this.inputAdapter = inputAdapter;
}
@Override
public void processInput(Object input, DataRecord inputRecord) throws AbortParsingException {
pushParser.parse(rootContext, inputAdapter.adapt(input), inputRecord);
}
}
/**
* TreeProcessor implementing {@link ProcessingMode#XPATH_CONVERT_STREAM} mode.
*
* @author krejcil ([email protected]) (c) Javlin, a.s. (www.cloveretl.com)
*
* @created 14.3.2012
*/
private class StreamConvertingXPathProcessor implements TreeProcessor {
private PipeTransformer pipeTransformer;
private PipeParser pipeParser;
boolean killIt = false;
TreeReaderParserProvider parserProvider;
XPathPushParser pushParser;
MappingContext rootContext;
private String charset;
public StreamConvertingXPathProcessor(TreeReaderParserProvider parserProvider, XPathPushParser pushParser,
MappingContext rootContext, String charset) {
this.charset = charset;
this.parserProvider = parserProvider;
this.pushParser = pushParser;
this.rootContext = rootContext;
}
@Override
public void processInput(Object input, DataRecord inputRecord) throws Exception {
if (input instanceof ReadableByteChannel) {
/*
* Convert input stream to XML
*/
InputSource source = new InputSource(Channels.newInputStream((ReadableByteChannel) input));
if (charset != null) {
source.setEncoding(charset);
}
Pipe pipe = null;
try {
pipe = Pipe.open();
try {
TreeStreamParser treeStreamParser = parserProvider.getTreeStreamParser();
treeStreamParser.setTreeContentHandler(new TreeXmlContentHandlerAdapter());
XMLReader treeXmlReader = new TreeXMLReaderAdaptor(treeStreamParser);
pipeTransformer = new PipeTransformer(TreeReader.this, treeXmlReader);
pipeTransformer.setInputOutput(Channels.newWriter(pipe.sink(), "UTF-8"), source);
pipeParser = new PipeParser(TreeReader.this, pushParser, rootContext);
pipeParser.setInput(Channels.newReader(pipe.source(), "UTF-8"));
pipeParser.setInputDataRecord(inputRecord);
} catch (TransformerFactoryConfigurationError e) {
throw new JetelRuntimeException("Failed to instantiate transformer", e);
}
FutureOfRunnable<PipeTransformer> pipeTransformerFuture = CloverWorker.startWorker(pipeTransformer);
FutureOfRunnable<PipeParser> pipeParserFuture = CloverWorker.startWorker(pipeParser);
pipeTransformerFuture.get();
pipeParserFuture.get();
if (pipeTransformerFuture.getRunnable().getException() != null) {
throw new JetelRuntimeException("Pipe transformer failed.", pipeTransformerFuture.getRunnable().getException());
}
if (pipeParserFuture.getRunnable().getException() != null) {
throw new JetelRuntimeException("Pipe parser failed.", pipeParserFuture.getRunnable().getException());
}
} finally {
if (pipe != null) {
closeQuietly(pipe.sink());
closeQuietly(pipe.source());
}
}
} else {
throw new JetelRuntimeException("Could not read input " + input);
}
}
@SuppressFBWarnings("DE_MIGHT_IGNORE")
private void closeQuietly(Closeable c) {
if (c != null) {
try {
c.close();
} catch (Exception e) {
// ignore
}
}
}
private class PipeTransformer extends CloverWorker {
private XMLReader treeXmlReader;
private Transformer transformer;
private Writer pipedWriter;
private InputSource source;
public PipeTransformer(Node node, XMLReader treeXmlReader) {
super(node, "PipeTransformer");
try {
this.transformer = TransformerFactory.newInstance().newTransformer();
this.treeXmlReader = treeXmlReader;
} catch (TransformerConfigurationException e) {
throw new JetelRuntimeException("Failed to instantiate transformer", e);
} catch (TransformerFactoryConfigurationError e) {
throw new JetelRuntimeException("Failed to instantiate transformer", e);
}
}
@Override
public void work() throws TransformerException {
javax.xml.transform.Result result = new StreamResult(pipedWriter);
try {
transformer.transform(new SAXSource(treeXmlReader, source), result);
} finally {
IOUtils.closeQuietly(pipedWriter);
}
}
public void setInputOutput(Writer pipedWriter, InputSource source) {
this.pipedWriter = pipedWriter;
this.source = source;
}
}
private class PipeParser extends CloverWorker {
private XPathPushParser pushParser;
private MappingContext rootContext;
private Reader pipedReader;
private DataRecord inputRecord;
public PipeParser(Node node, XPathPushParser parser, MappingContext root) {
super(node, "PipeParser");
this.pushParser = parser;
this.rootContext = root;
}
public void setInputDataRecord(DataRecord inputRecord) {
this.inputRecord = inputRecord;
}
@Override
public void work() throws InterruptedException, AbortParsingException {
try {
pushParser.parse(rootContext, new SAXSource(new InputSource(pipedReader)), inputRecord);
} finally {
IOUtils.closeQuietly(pipedReader);
}
}
private void setInput(Reader pipedReader) {
this.pipedReader = pipedReader;
}
}
}
private static class MaxErrorsCountExceededException extends RuntimeException {
private static final long serialVersionUID = -3499614028763254366L;
}
private static class PortUsageMappingVisitor implements MappingVisitor {
private Set<Integer> usedPortIndexes = new HashSet<Integer>();
@Override
public void visitBegin(MappingContext context) {
Integer port = context.getOutputPort();
if (port != null) {
usedPortIndexes.add(port);
}
}
@Override
public void visitEnd(MappingContext context) { }
@Override
public void visit(FieldMapping mapping) { }
public boolean isPortUsed(int portIndex) {
return usedPortIndexes.contains(portIndex);
}
}
} | cloveretl.component/src/org/jetel/component/TreeReader.java | /*
* jETeL/CloverETL - Java based ETL application framework.
* Copyright (c) Javlin, a.s. ([email protected])
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.jetel.component;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.Pipe;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetel.component.tree.reader.AbortParsingException;
import org.jetel.component.tree.reader.DataRecordProvider;
import org.jetel.component.tree.reader.DataRecordReceiver;
import org.jetel.component.tree.reader.FieldFillingException;
import org.jetel.component.tree.reader.InputAdapter;
import org.jetel.component.tree.reader.TreeReaderParserProvider;
import org.jetel.component.tree.reader.TreeStreamParser;
import org.jetel.component.tree.reader.TreeXMLReaderAdaptor;
import org.jetel.component.tree.reader.TreeXmlContentHandlerAdapter;
import org.jetel.component.tree.reader.XPathEvaluator;
import org.jetel.component.tree.reader.XPathPushParser;
import org.jetel.component.tree.reader.XPathSequenceProvider;
import org.jetel.component.tree.reader.mappping.FieldMapping;
import org.jetel.component.tree.reader.mappping.FieldNameEncoder;
import org.jetel.component.tree.reader.mappping.ImplicitMappingAddingVisitor;
import org.jetel.component.tree.reader.mappping.MalformedMappingException;
import org.jetel.component.tree.reader.mappping.MappingContext;
import org.jetel.component.tree.reader.mappping.MappingElementFactory;
import org.jetel.component.tree.reader.mappping.MappingVisitor;
import org.jetel.component.tree.reader.xml.XmlXPathEvaluator;
import org.jetel.data.DataField;
import org.jetel.data.DataRecord;
import org.jetel.data.DataRecordFactory;
import org.jetel.data.Defaults;
import org.jetel.data.sequence.Sequence;
import org.jetel.data.sequence.SequenceFactory;
import org.jetel.exception.AttributeNotFoundException;
import org.jetel.exception.BadDataFormatException;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.exception.ConfigurationProblem;
import org.jetel.exception.ConfigurationStatus;
import org.jetel.exception.ConfigurationStatus.Priority;
import org.jetel.exception.ConfigurationStatus.Severity;
import org.jetel.exception.JetelException;
import org.jetel.exception.JetelRuntimeException;
import org.jetel.exception.PolicyType;
import org.jetel.exception.XMLConfigurationException;
import org.jetel.graph.Node;
import org.jetel.graph.OutputPort;
import org.jetel.graph.Result;
import org.jetel.graph.TransformationGraph;
import org.jetel.graph.runtime.CloverWorker;
import org.jetel.graph.runtime.FutureOfRunnable;
import org.jetel.metadata.DataFieldMetadata;
import org.jetel.metadata.DataFieldType;
import org.jetel.metadata.DataRecordMetadata;
import org.jetel.sequence.PrimitiveSequence;
import org.jetel.util.AutoFilling;
import org.jetel.util.ExceptionUtils;
import org.jetel.util.SourceIterator;
import org.jetel.util.XmlUtils;
import org.jetel.util.file.FileUtils;
import org.jetel.util.property.ComponentXMLAttributes;
import org.jetel.util.property.RefResFlag;
import org.jetel.util.string.StringUtils;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
/**
* @author lkrejci ([email protected]) (c) Javlin, a.s. (www.cloveretl.com)
*
* @created 19 Jan 2012
*/
public abstract class TreeReader extends Node implements DataRecordProvider, DataRecordReceiver, XPathSequenceProvider {
/**
* TreeReader works in several processing modes. Chosen processing mode depends on provided
* {@link TreeReaderParserProvider} and mapping complexity. The priority of modes:
* <ol>
* <li>{@link ProcessingMode#STREAM}</li>
* <li>{@link ProcessingMode#XPATH_DIRECT}</li>
* <li>{@link ProcessingMode#XPATH_CONVERT_STREAM}</li>
* </ol>
*
* @author krejcil ([email protected]) (c) Javlin, a.s. (www.cloveretl.com)
*/
private static enum ProcessingMode {
/**
* #NOT IMPLEMENTED# {@link TreeReaderParserProvider} provides {@link TreeStreamParser} and mapping is simple
* enough input is processed in SAX-like manner
*/
STREAM,
/**
* {@link TreeReaderParserProvider} provides {@link XPathEvaluator} xpath expressions are evaluated directly on
* input
*/
XPATH_DIRECT,
/**
* {@link TreeReaderParserProvider} provides {@link TreeReaderParserProvider} -- input is converted to xml and
* xml xpath evaluator is used to resolve xpath expressions on converted input
*/
XPATH_CONVERT_STREAM
}
private static final Log LOG = LogFactory.getLog(TreeReader.class);
private static final int INPUT_PORT_INDEX = 0;
// this attribute is not used at runtime right now
public static final String XML_SCHEMA_ATTRIBUTE = "schema";
protected final static String XML_FILE_URL_ATTRIBUTE = "fileURL";
public final static String XML_MAPPING_URL_ATTRIBUTE = "mappingURL";
public final static String XML_MAPPING_ATTRIBUTE = "mapping";
public final static String XML_DATAPOLICY_ATTRIBUTE = "dataPolicy";
public static final String XML_CHARSET_ATTRIBUTE = "charset";
public static final String XML_IMPLICIT_MAPPING_ATTRIBUTE = "implicitMapping";
protected static void readCommonAttributes(TreeReader treeReader, ComponentXMLAttributes xattribs)
throws XMLConfigurationException, AttributeNotFoundException {
treeReader.setFileURL(xattribs.getStringEx(XML_FILE_URL_ATTRIBUTE, null, RefResFlag.URL));
if (xattribs.exists(XML_CHARSET_ATTRIBUTE)) {
treeReader.setCharset(xattribs.getString(XML_CHARSET_ATTRIBUTE));
}
treeReader.setPolicyType(xattribs.getString(XML_DATAPOLICY_ATTRIBUTE, null));
String mappingURL = xattribs.getStringEx(XML_MAPPING_URL_ATTRIBUTE, null, RefResFlag.URL);
String mapping = xattribs.getString(XML_MAPPING_ATTRIBUTE, null);
if (mappingURL != null) {
treeReader.setMappingURL(mappingURL);
} else {
treeReader.setMappingString(mapping);
}
treeReader.setImplicitMapping(xattribs.getBoolean(XML_IMPLICIT_MAPPING_ATTRIBUTE, false));
}
// DataRecordProvider, DataRecordReceiver, XPathSequenceProvider properties
private DataRecord outputRecords[];
private OutputPort outputPorts[];
private boolean recordReadWithException[];
private String defaultSequenceId;
protected String fileURL;
protected String charset;
private SourceIterator sourceIterator;
private String policyTypeStr;
private PolicyType policyType;
private String mappingString;
private String mappingURL;
private boolean implicitMapping;
private TreeReaderParserProvider parserProvider;
private TreeProcessor treeProcessor;
private AutoFilling autoFilling = new AutoFilling();
private int[] sourcePortRecordCounters; // counters of records written to particular ports per source
private boolean errorPortLogging;
private DataRecord errorLogRecord;
private int maxErrors = -1;
private int errorsCount;
public TreeReader(String id) {
super(id);
}
protected abstract TreeReaderParserProvider getTreeReaderParserProvider();
protected FieldNameEncoder getFieldNameEncoder() {
// no encoding by default
return null;
}
protected ConfigurationStatus disallowEmptyCharsetOnDictionaryAndPort(ConfigurationStatus status) {
ConfigurationStatus configStatus = super.checkConfig(status);
for (String fileUrlEntry : this.getFileUrl().split(";")) {
if ((fileUrlEntry.startsWith("dict:") || fileUrlEntry.startsWith("port:")) && charset == null) {
status.add(new ConfigurationProblem("Charset cannot be auto-detected for input from a port or dictionary. Define it in the \"Charset\" attribute explicitly.", ConfigurationStatus.Severity.ERROR, this, ConfigurationStatus.Priority.NORMAL));
}
}
return configStatus;
}
@Override
public ConfigurationStatus checkConfig(ConfigurationStatus status) {
super.checkConfig(status);
if (!checkInputPorts(status, 0, 1) || !checkOutputPorts(status, 1, Integer.MAX_VALUE)) {
return status;
}
if (!PolicyType.isPolicyType(policyTypeStr)) {
status.add("Invalid data policy: " + policyTypeStr, Severity.ERROR, this, Priority.NORMAL, XML_DATAPOLICY_ATTRIBUTE);
} else {
policyType = PolicyType.valueOfIgnoreCase(policyTypeStr);
}
if (StringUtils.isEmpty(this.getFileUrl())) {
status.add(new ConfigurationProblem("Missing required attribute 'File URL'", ConfigurationStatus.Severity.ERROR, this, ConfigurationStatus.Priority.NORMAL, XML_FILE_URL_ATTRIBUTE));
}
if (StringUtils.isEmpty(mappingURL) && StringUtils.isEmpty(mappingString)) {
status.add(new ConfigurationProblem("Missing required attribute 'Mapping'", ConfigurationStatus.Severity.ERROR, this, ConfigurationStatus.Priority.NORMAL));
}
if (charset != null && !Charset.isSupported(charset)) {
status.add(new ConfigurationProblem("Charset " + charset + " not supported!", ConfigurationStatus.Severity.ERROR, this, ConfigurationStatus.Priority.NORMAL, XML_CHARSET_ATTRIBUTE));
}
/*
* TODO validate mapping model in checkConfig with respect to port metadata i.e. that there are all fields
* available and all mentioned ports are connected
*/
return status;
}
@Override
public void init() throws ComponentNotReadyException {
if (isInitialized()) {
return;
}
super.init();
policyType = PolicyType.valueOfIgnoreCase(policyTypeStr);
this.parserProvider = getTreeReaderParserProvider();
recordProviderReceiverInit();
for (OutputPort outPort : outPortsArray) {
autoFilling.addAutoFillingFields(outPort.getMetadata());
}
sourcePortRecordCounters = new int[outPortsSize];
sourceIterator = createSourceIterator();
// FIXME: mapping should not be initialized here in init if is passed via external file, since it is possible
// that mapping file does not exist at this moment, or its content can change
MappingContext rootContext = createMapping();
if (implicitMapping) {
MappingVisitor implicitMappingVisitor = new ImplicitMappingAddingVisitor(getOutMetadata(), getFieldNameEncoder());
rootContext.acceptVisitor(implicitMappingVisitor);
}
XPathPushParser pushParser;
ProcessingMode processingMode = resolveProcessingMode();
switch (processingMode) {
case XPATH_CONVERT_STREAM:
pushParser = new XPathPushParser(this, this, new XmlXPathEvaluator(), parserProvider.getValueHandler(), this);
treeProcessor = new StreamConvertingXPathProcessor(parserProvider, pushParser, rootContext, charset);
break;
case XPATH_DIRECT:
pushParser = new XPathPushParser(this, this, parserProvider.getXPathEvaluator(), parserProvider.getValueHandler(), this);
InputAdapter inputAdapter = parserProvider.getInputAdapter();
treeProcessor = new XPathProcessor(pushParser, rootContext, inputAdapter);
break;
default:
throw new UnsupportedOperationException("Processing mode " + processingMode + " is not supported");
}
errorPortLogging = isErrorPortLogging(rootContext);
if (errorPortLogging) {
LOG.info("Using port " + getErrorPortIndex() + " as error logging port");
errorLogRecord = DataRecordFactory.newRecord(getOutputPort(getErrorPortIndex()).getMetadata());
}
}
private void recordProviderReceiverInit() {
int portCount = getOutPorts().size();
outputRecords = new DataRecord[portCount];
outputPorts = new OutputPort[portCount];
recordReadWithException = new boolean[portCount];
for (int i = 0; i < portCount; ++i) {
OutputPort port = getOutputPort(i);
outputPorts[i] = port;
DataRecord record = DataRecordFactory.newRecord(port.getMetadata());
outputRecords[i] = record;
}
}
private ProcessingMode resolveProcessingMode() {
if (parserProvider.providesXPathEvaluator()) {
return ProcessingMode.XPATH_DIRECT;
} else if (parserProvider.providesTreeStreamParser()) {
return ProcessingMode.XPATH_CONVERT_STREAM;
} else {
throw new IllegalStateException("Invalid parser provider configuration");
}
}
protected MappingContext createMapping() throws ComponentNotReadyException {
Document mappingDocument;
try {
if (mappingURL != null) {
ReadableByteChannel ch = FileUtils.getReadableChannel(getContextURL(), mappingURL);
mappingDocument = XmlUtils.createDocumentFromChannel(ch);
} else {
mappingDocument = XmlUtils.createDocumentFromString(mappingString);
}
} catch (IOException e) {
throw new ComponentNotReadyException("Mapping parameter parse error occured.", e);
} catch (JetelException e) {
throw new ComponentNotReadyException("Mapping parameter parse error occured.", e);
}
try {
return new MappingElementFactory().readMapping(mappingDocument);
} catch (MalformedMappingException e) {
throw new ComponentNotReadyException("Input mapping is not valid.", e);
}
}
protected SourceIterator createSourceIterator() {
TransformationGraph graph = getGraph();
URL projectURL = getContextURL();
SourceIterator iterator = new SourceIterator(getInputPort(INPUT_PORT_INDEX), projectURL, fileURL);
iterator.setCharset(charset);
iterator.setPropertyRefResolver(getPropertyRefResolver());
iterator.setDictionary(graph.getDictionary());
return iterator;
}
/**
* @return true iff the last out port is not used in the mapping and it has prescribed metadata
*/
private boolean isErrorPortLogging(MappingContext rootContext) {
OutputPort errorPortCandidate = outPortsArray[getErrorPortIndex()];
if (isPortUsed(errorPortCandidate.getOutputPortNumber(), rootContext)) {
return false;
} else {
if (hasErrorLoggingMetadata(errorPortCandidate)) {
return true;
} else {
LOG.warn("If the last output port is intended for error logging, metadata should be: "
+ "integer (out port number), integer (record number per source and port), integer (field number), "
+ "string (field name), string (value which caused the error), string (error message), string (source name - optional field)");
return false;
}
}
}
private int getErrorPortIndex() {
return outPortsSize - 1;
}
private boolean hasErrorLoggingMetadata(OutputPort errorPort) {
DataRecordMetadata metadata = errorPort.getMetadata();
int errorNumFields = metadata.getNumFields();
return (errorNumFields == 6 || errorNumFields == 7)
&& metadata.getField(0).getDataType() == DataFieldType.INTEGER // port number
&& metadata.getField(1).getDataType() == DataFieldType.INTEGER // port record number per source
&& metadata.getField(2).getDataType() == DataFieldType.INTEGER // field number
&& isStringOrByte(metadata.getField(3)) // field name
&& isStringOrByte(metadata.getField(4)) // offending value
&& isStringOrByte(metadata.getField(5)) // error message
&& (errorNumFields == 6 || isStringOrByte(metadata.getField(6))); // optional source name
}
private boolean isStringOrByte(DataFieldMetadata field) {
return field.getDataType() == DataFieldType.STRING || field.getDataType() == DataFieldType.BYTE || field.getDataType() == DataFieldType.CBYTE;
}
private static boolean isPortUsed(int portIndex, MappingContext rootContext) {
PortUsageMappingVisitor portUsageMappingVisitor = new PortUsageMappingVisitor();
rootContext.acceptVisitor(portUsageMappingVisitor);
return portUsageMappingVisitor.isPortUsed(portIndex);
}
@Override
public void preExecute() throws ComponentNotReadyException {
super.preExecute();
// FIXME: init of source iterator is not implemented well right now, so it has to be called here in preExecute!
sourceIterator.init();
sourceIterator.preExecute();
}
@Override
public Result execute() throws Exception {
Object inputData = getNextSource();
while (inputData != null) {
try {
treeProcessor.processInput(inputData, sourceIterator.getCurrenRecord());
} catch (AbortParsingException e) {
if (!runIt) {
return Result.ABORTED;
} else if (e.getCause() instanceof MaxErrorsCountExceededException) {
return Result.ERROR;
} else if (e.getCause() instanceof Exception) { // TODO BadDataFormatException / Exception ?
throw (Exception) e.getCause();
}
} finally {
if (inputData instanceof Closeable) {
try {
((Closeable) inputData).close();
} catch (Exception ex) {
LOG.error("Failed to close input");
}
}
}
inputData = getNextSource();
}
return runIt ? Result.FINISHED_OK : Result.ABORTED;
}
@Override
public void postExecute() throws ComponentNotReadyException {
super.postExecute();
}
@Override
public String[] getUsedUrls() {
return new String[] { fileURL };
}
private Object getNextSource() throws JetelException {
Object input = null;
while (sourceIterator.hasNext()) {
input = sourceIterator.next();
if (input == null) {
continue; // if record no record found
}
autoFilling.resetSourceCounter();
autoFilling.resetGlobalSourceCounter();
autoFilling.setFilename(sourceIterator.getCurrentFileName());
if (!sourceIterator.isGraphDependentSource()) {
long fileSize = 0;
Date fileTimestamp = null;
if (autoFilling.getFilename() != null &&
FileUtils.isLocalFile(null, autoFilling.getFilename()) &&
!sourceIterator.isGraphDependentSource()) {
File tmpFile = new File(autoFilling.getFilename());
long timestamp = tmpFile.lastModified();
fileTimestamp = timestamp == 0 ? null : new Date(timestamp);
fileSize = tmpFile.length();
}
autoFilling.setFileSize(fileSize);
autoFilling.setFileTimestamp(fileTimestamp);
}
Arrays.fill(sourcePortRecordCounters, 0);
return input;
}
sourceIterator.blankRead();
return input;
}
public String getFileUrl() {
return fileURL;
}
public void setFileURL(String fileURL) {
this.fileURL = fileURL;
}
private void setCharset(String charset) {
this.charset = charset;
}
public void setPolicyType(String policyTypeStr) {
this.policyTypeStr = policyTypeStr;
}
public void setMappingString(String mappingString) {
this.mappingString = mappingString;
}
public void setMappingURL(String mappingURL) {
this.mappingURL = mappingURL;
}
public void setImplicitMapping(boolean implicitMapping) {
this.implicitMapping = implicitMapping;
}
@Override
public void receive(DataRecord record, int port) throws AbortParsingException {
if (runIt) {
try {
sourcePortRecordCounters[port]++;
autoFilling.incGlobalCounter();
autoFilling.incSourceCounter();
// FIXME: some autofilling fields should be filled sooner - so that it can be used with combination of
// generated key pointing at autofilled field
autoFilling.setAutoFillingFields(record);
outputPorts[port].writeRecord(record);
} catch (Exception e) {
throw new RuntimeException(e);
}
} else {
throw new AbortParsingException();
}
}
@Override
public void exceptionOccurred(FieldFillingException e) throws AbortParsingException {
if (policyType == PolicyType.STRICT) {
LOG.error("Could not assign data field \"" + e.getFieldMetadata().getName() + "\" ("
+ e.getFieldMetadata().getDataType().getName() + ") on port " + e.getPortIndex(), e.getCause());
throw new AbortParsingException(e);
} else if (policyType == PolicyType.CONTROLLED) {
if (!recordReadWithException[e.getPortIndex()]) {
recordReadWithException[e.getPortIndex()] = true;
sourcePortRecordCounters[e.getPortIndex()]++;
}
if (errorPortLogging) {
writeErrorLogRecord(e);
} else {
BadDataFormatException bdfe = e.getCause();
bdfe.setRecordNumber(sourcePortRecordCounters[e.getPortIndex()]);
bdfe.setFieldNumber(e.getFieldMetadata().getNumber());
bdfe.setFieldName(e.getFieldMetadata().getName());
bdfe.setRecordName(e.getFieldMetadata().getDataRecordMetadata().getName());
String errorMsg = ExceptionUtils.getMessage(bdfe) + "; output port: " + e.getPortIndex();
if (!sourceIterator.isSingleSource()) {
errorMsg += "; input source: " + sourceIterator.getCurrentFileName();
}
LOG.error(errorMsg);
}
if (maxErrors != -1 && ++errorsCount > maxErrors) {
LOG.error("Max errors count exceeded.", e);
throw new AbortParsingException(new MaxErrorsCountExceededException());
}
}
}
private void writeErrorLogRecord(FieldFillingException e) {
int i = 0;
errorLogRecord.getField(i++).setValue(e.getPortIndex());
errorLogRecord.getField(i++).setValue(sourcePortRecordCounters[e.getPortIndex()]);
errorLogRecord.getField(i++).setValue(e.getFieldMetadata().getNumber() + 1);
setCharSequenceToField(e.getFieldMetadata().getName(), errorLogRecord.getField(i++));
setCharSequenceToField(e.getCause().getOffendingValue(), errorLogRecord.getField(i++));
setCharSequenceToField(ExceptionUtils.getMessage(e.getCause()), errorLogRecord.getField(i++));
if (errorLogRecord.getNumFields() > i) {
setCharSequenceToField(sourceIterator.getCurrentFileName(), errorLogRecord.getField(i++));
}
try {
outputPorts[getErrorPortIndex()].writeRecord(errorLogRecord);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
private void setCharSequenceToField(CharSequence charSeq, DataField field) {
if (charSeq == null) {
field.setNull(true);
} else {
field.setNull(false);
if (field.getMetadata().getDataType() == DataFieldType.STRING) {
field.setValue(charSeq);
} else if (field.getMetadata().getDataType() == DataFieldType.BYTE || field.getMetadata().getDataType() == DataFieldType.CBYTE) {
String cs;
if (charset != null) {
cs = charset;
} else {
cs = Defaults.DataParser.DEFAULT_CHARSET_DECODER;
}
try {
field.setValue(charSeq.toString().getBytes(cs));
} catch (UnsupportedEncodingException e) {
LOG.error(getId() + ": failed to write log record", e);
}
} else {
throw new IllegalArgumentException("Type of field \""+ field.getMetadata().getName() +"\" has to be string, byte or cbyte");
}
}
}
@Override
public DataRecord getDataRecord(int port) throws AbortParsingException {
if (runIt) {
recordReadWithException[port] = false;
/*
* answer copy of record instead of re-usage because
* parser could ask for new record without previous record
* having been written
*/
return outputRecords[port].duplicate();
} else {
throw new AbortParsingException();
}
}
@Override
public Sequence getSequence(MappingContext context) {
if (context.getSequenceId() != null) {
Sequence result = getGraph().getSequence(context.getSequenceId());
if (result == null) {
throw new JetelRuntimeException("Could not find sequence: " + context.getSequenceId());
}
return result;
} else {
if (defaultSequenceId == null) {
String id = getId() + "_DefaultSequence";
Sequence defaultSequence = SequenceFactory.createSequence(getGraph(), PrimitiveSequence.SEQUENCE_TYPE,
new Object[] {id, getGraph(), id}, new Class[] {String.class, TransformationGraph.class, String.class});
try {
PrimitiveSequence ps = (PrimitiveSequence)defaultSequence;
ps.setGraph(getGraph());
ps.init();
ps.setStart(1);
} catch (ComponentNotReadyException e) {
throw new JetelRuntimeException(e);
}
getGraph().addSequence(defaultSequence);
defaultSequenceId = id;
}
return getGraph().getSequence(defaultSequenceId);
}
}
/**
* Interface for classes encapsulating the functionality of one {@link ProcessingMode} of TreeReader
*
* @author krejcil ([email protected]) (c) Javlin, a.s. (www.cloveretl.com)
*
* @created 10.3.2012
*/
private interface TreeProcessor {
void processInput(Object input, DataRecord inputRecord) throws Exception;
}
/**
* TreeProcessor implementing {@link ProcessingMode#XPATH_DIRECT} mode
*
* @author krejcil ([email protected]) (c) Javlin, a.s. (www.cloveretl.com)
*
* @created 10.3.2012
*/
private static class XPathProcessor implements TreeProcessor {
private XPathPushParser pushParser;
private MappingContext rootContext;
private InputAdapter inputAdapter;
private XPathProcessor(XPathPushParser pushParser, MappingContext rootContext, InputAdapter inputAdapter) {
this.pushParser = pushParser;
this.rootContext = rootContext;
this.inputAdapter = inputAdapter;
}
@Override
public void processInput(Object input, DataRecord inputRecord) throws AbortParsingException {
pushParser.parse(rootContext, inputAdapter.adapt(input), inputRecord);
}
}
/**
* TreeProcessor implementing {@link ProcessingMode#XPATH_CONVERT_STREAM} mode.
*
* @author krejcil ([email protected]) (c) Javlin, a.s. (www.cloveretl.com)
*
* @created 14.3.2012
*/
private class StreamConvertingXPathProcessor implements TreeProcessor {
private PipeTransformer pipeTransformer;
private PipeParser pipeParser;
boolean killIt = false;
TreeReaderParserProvider parserProvider;
XPathPushParser pushParser;
MappingContext rootContext;
private String charset;
public StreamConvertingXPathProcessor(TreeReaderParserProvider parserProvider, XPathPushParser pushParser,
MappingContext rootContext, String charset) {
this.charset = charset;
this.parserProvider = parserProvider;
this.pushParser = pushParser;
this.rootContext = rootContext;
}
@Override
public void processInput(Object input, DataRecord inputRecord) throws Exception {
if (input instanceof ReadableByteChannel) {
/*
* Convert input stream to XML
*/
InputSource source = new InputSource(Channels.newInputStream((ReadableByteChannel) input));
if (charset != null) {
source.setEncoding(charset);
}
Pipe pipe = null;
try {
pipe = Pipe.open();
try {
TreeStreamParser treeStreamParser = parserProvider.getTreeStreamParser();
treeStreamParser.setTreeContentHandler(new TreeXmlContentHandlerAdapter());
XMLReader treeXmlReader = new TreeXMLReaderAdaptor(treeStreamParser);
pipeTransformer = new PipeTransformer(TreeReader.this, treeXmlReader);
pipeTransformer.setInputOutput(Channels.newWriter(pipe.sink(), "UTF-8"), source);
pipeParser = new PipeParser(TreeReader.this, pushParser, rootContext);
pipeParser.setInput(Channels.newReader(pipe.source(), "UTF-8"));
pipeParser.setInputDataRecord(inputRecord);
} catch (TransformerFactoryConfigurationError e) {
throw new JetelRuntimeException("Failed to instantiate transformer", e);
}
FutureOfRunnable<PipeTransformer> pipeTransformerFuture = CloverWorker.startWorker(pipeTransformer);
FutureOfRunnable<PipeParser> pipeParserFuture = CloverWorker.startWorker(pipeParser);
pipeTransformerFuture.get();
pipeParserFuture.get();
if (pipeTransformerFuture.getRunnable().getException() != null) {
throw new JetelRuntimeException("Pipe transformer failed.", pipeTransformerFuture.getRunnable().getException());
}
if (pipeParserFuture.getRunnable().getException() != null) {
throw new JetelRuntimeException("Pipe parser failed.", pipeParserFuture.getRunnable().getException());
}
} finally {
if (pipe != null) {
closeQuietly(pipe.sink());
closeQuietly(pipe.source());
}
}
} else {
throw new JetelRuntimeException("Could not read input " + input);
}
}
private void closeQuietly(Closeable c) {
if (c != null) {
try {
c.close();
} catch (Exception e) {
// ignore
}
}
}
private class PipeTransformer extends CloverWorker {
private XMLReader treeXmlReader;
private Transformer transformer;
private Writer pipedWriter;
private InputSource source;
public PipeTransformer(Node node, XMLReader treeXmlReader) {
super(node, "PipeTransformer");
try {
this.transformer = TransformerFactory.newInstance().newTransformer();
this.treeXmlReader = treeXmlReader;
} catch (TransformerConfigurationException e) {
throw new JetelRuntimeException("Failed to instantiate transformer", e);
} catch (TransformerFactoryConfigurationError e) {
throw new JetelRuntimeException("Failed to instantiate transformer", e);
}
}
@Override
public void work() throws TransformerException {
javax.xml.transform.Result result = new StreamResult(pipedWriter);
try {
transformer.transform(new SAXSource(treeXmlReader, source), result);
} finally {
IOUtils.closeQuietly(pipedWriter);
}
}
public void setInputOutput(Writer pipedWriter, InputSource source) {
this.pipedWriter = pipedWriter;
this.source = source;
}
}
private class PipeParser extends CloverWorker {
private XPathPushParser pushParser;
private MappingContext rootContext;
private Reader pipedReader;
private DataRecord inputRecord;
public PipeParser(Node node, XPathPushParser parser, MappingContext root) {
super(node, "PipeParser");
this.pushParser = parser;
this.rootContext = root;
}
public void setInputDataRecord(DataRecord inputRecord) {
this.inputRecord = inputRecord;
}
@Override
public void work() throws InterruptedException, AbortParsingException {
try {
pushParser.parse(rootContext, new SAXSource(new InputSource(pipedReader)), inputRecord);
} finally {
IOUtils.closeQuietly(pipedReader);
}
}
private void setInput(Reader pipedReader) {
this.pipedReader = pipedReader;
}
}
}
private static class MaxErrorsCountExceededException extends RuntimeException {
private static final long serialVersionUID = -3499614028763254366L;
}
private static class PortUsageMappingVisitor implements MappingVisitor {
private Set<Integer> usedPortIndexes = new HashSet<Integer>();
@Override
public void visitBegin(MappingContext context) {
Integer port = context.getOutputPort();
if (port != null) {
usedPortIndexes.add(port);
}
}
@Override
public void visitEnd(MappingContext context) { }
@Override
public void visit(FieldMapping mapping) { }
public boolean isPortUsed(int portIndex) {
return usedPortIndexes.contains(portIndex);
}
}
} | UPDATE: ignored FB warning on ignored exception
git-svn-id: 72eb86817c4084ae38a704908f4ff04d3865072b@19342 a09ad3ba-1a0f-0410-b1b9-c67202f10d70
| cloveretl.component/src/org/jetel/component/TreeReader.java | UPDATE: ignored FB warning on ignored exception |
|
Java | lgpl-2.1 | bd98423ba5bd891f4d92095ce84bf750fc1c2a31 | 0 | IDgis/geo-publisher,IDgis/geo-publisher,IDgis/geo-publisher,IDgis/geo-publisher | package controllers;
import static models.Domain.from;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import models.Domain.Constant;
import models.Domain.Function;
import models.Domain.Function2;
import models.Domain.Function4;
import nl.idgis.publisher.domain.job.ConfirmNotificationResult;
import nl.idgis.publisher.domain.query.DomainQuery;
import nl.idgis.publisher.domain.query.ListDatasetColumnDiff;
import nl.idgis.publisher.domain.query.ListDatasetColumns;
import nl.idgis.publisher.domain.query.ListDatasets;
import nl.idgis.publisher.domain.query.ListSourceDatasetColumns;
import nl.idgis.publisher.domain.query.ListSourceDatasets;
import nl.idgis.publisher.domain.query.PutNotificationResult;
import nl.idgis.publisher.domain.query.RefreshDataset;
import nl.idgis.publisher.domain.response.Page;
import nl.idgis.publisher.domain.response.Response;
import nl.idgis.publisher.domain.service.Column;
import nl.idgis.publisher.domain.service.ColumnDiff;
import nl.idgis.publisher.domain.service.CrudOperation;
import nl.idgis.publisher.domain.service.CrudResponse;
import nl.idgis.publisher.domain.web.Category;
import nl.idgis.publisher.domain.web.DataSource;
import nl.idgis.publisher.domain.web.Dataset;
import nl.idgis.publisher.domain.web.Filter;
import nl.idgis.publisher.domain.web.Filter.OperatorType;
import nl.idgis.publisher.domain.web.PutDataset;
import nl.idgis.publisher.domain.web.SourceDataset;
import nl.idgis.publisher.domain.web.SourceDatasetStats;
import play.Logger;
import play.Play;
import play.data.Form;
import play.data.validation.Constraints;
import play.data.validation.ValidationError;
import play.libs.Akka;
import play.libs.F.Promise;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Result;
import play.mvc.Security;
import views.html.datasets.columns;
import views.html.datasets.form;
import views.html.datasets.list;
import views.html.datasets.show;
import views.html.datasets.status;
import actions.DefaultAuthenticator;
import actors.Database;
import akka.actor.ActorSelection;
import com.fasterxml.jackson.databind.node.ObjectNode;
@Security.Authenticated (DefaultAuthenticator.class)
public class Datasets extends Controller {
private final static String databaseRef = Play.application().configuration().getString("publisher.database.actorRef");
private final static String ID="#CREATE_DATASET#";
public static Promise<Result> list (long page) {
return listByCategoryAndMessages(null, false, page);
}
public static Promise<Result> listWithMessages (long page) {
return listByCategoryAndMessages(null, true, page);
}
public static Promise<Result> listByCategory (String categoryId, long page) {
return listByCategoryAndMessages(categoryId, false, page);
}
public static Promise<Result> listByCategoryWithMessages (String categoryId, long page) {
return listByCategoryAndMessages(categoryId, true, page);
}
public static Promise<Result> show (final String datasetId) {
final ActorSelection database = Akka.system().actorSelection (databaseRef);
return from (database)
.get (Dataset.class, datasetId)
.query (new ListDatasetColumnDiff (datasetId))
.execute (new Function2<Dataset, List<ColumnDiff>, Result> () {
@Override
public Result apply (final Dataset dataset, final List<ColumnDiff> diffs) throws Throwable {
return ok (show.render (dataset, diffs));
}
});
}
public static Promise<Result> status (final String datasetId) {
final ActorSelection database = Akka.system().actorSelection (databaseRef);
return from (database)
.get (Dataset.class, datasetId)
.execute (new Function<Dataset, Result> () {
@Override
public Result apply (final Dataset dataset) throws Throwable {
return ok (status.render (dataset));
}
});
}
public static Promise<Result> setNotificationResult (final String datasetId, final String notificationId) {
final String[] resultString = request ().body ().asFormUrlEncoded ().get ("result");
if (resultString == null || resultString.length != 1 || resultString[0] == null) {
return Promise.pure ((Result) redirect (controllers.routes.Datasets.show (datasetId)));
}
final ConfirmNotificationResult result = ConfirmNotificationResult.valueOf (resultString[0]);
Logger.debug ("Conform notification: " + notificationId + ", " + result);
final ActorSelection database = Akka.system().actorSelection (databaseRef);
return from (database)
.query (new PutNotificationResult (notificationId, result))
.execute (new Function<Response<?>, Result> () {
@Override
public Result apply (final Response<?> response) throws Throwable {
if (response.getOperationResponse ().equals (CrudResponse.OK)) {
flash ("success", "Resultaat van de structuurwijziging is opgeslagen");
} else {
flash ("danger", "Resultaat van de structuurwijziging kon niet worden opgeslagen");
}
return redirect (controllers.routes.Datasets.show (datasetId));
}
});
}
public static Promise<Result> scheduleRefresh(String datasetId) {
final ActorSelection database = Akka.system().actorSelection (databaseRef);
return from(database)
.query(new RefreshDataset(datasetId))
.execute(new Function<Boolean, Result>() {
@Override
public Result apply(Boolean b) throws Throwable {
final ObjectNode result = Json.newObject ();
if (b) {
result.put ("result", "ok");
return ok (result);
} else {
result.put ("result", "failed");
return internalServerError (result);
}
}
});
}
public static Promise<Result> delete(final String datasetId){
System.out.println("delete dataset " + datasetId);
final ActorSelection database = Akka.system().actorSelection (databaseRef);
return from (database)
.delete (Dataset.class, datasetId)
.execute (new Function<Response<?>, Result> () {
@Override
public Result apply (final Response<?> response) throws Throwable {
if (CrudResponse.OK.equals (response.getOperationResponse ())) {
flash ("success", "De dataset is verwijderd");
} else {
flash ("danger", "De dataset kon niet worden verwijderd");
}
return redirect (routes.Datasets.list (1));
}
});
}
private static DomainQuery<Page<SourceDatasetStats>> listSourceDatasets (final String dataSourceId, final String categoryId) {
if (dataSourceId == null || categoryId == null || dataSourceId.isEmpty () || categoryId.isEmpty ()) {
return new Constant<Page<SourceDatasetStats>> (new Page.Builder<SourceDatasetStats> ().build ());
}
return new ListSourceDatasets (dataSourceId, categoryId, null, null, null);
}
private static DomainQuery<List<Column>> listSourceDatasetColumns (final String dataSourceId, final String sourceDatasetId) {
if (dataSourceId == null || sourceDatasetId == null || dataSourceId.isEmpty () || sourceDatasetId.isEmpty ()) {
return new Constant<List<Column>> (Collections.<Column>emptyList ());
}
return new ListSourceDatasetColumns (dataSourceId, sourceDatasetId);
}
private static DomainQuery<List<Column>> listDatasetColumns (final String datasetId) {
if (datasetId == null || datasetId.isEmpty ()) {
return new Constant<List<Column>> (Collections.<Column>emptyList ());
}
return new ListDatasetColumns (datasetId);
}
private static Promise<Result> renderCreateForm (final Form<DatasetForm> datasetForm) {
final ActorSelection database = Akka.system().actorSelection (databaseRef);
return from(database)
.list(DataSource.class)
.list(Category.class)
.query (listSourceDatasets (datasetForm.field ("dataSourceId").value (), datasetForm.field ("categoryId").value ()))
.query (listSourceDatasetColumns (datasetForm.field ("dataSourceId").value (), datasetForm.field ("sourceDatasetId").value ()))
.execute(new Function4<Page<DataSource>, Page<Category>, Page<SourceDatasetStats>, List<Column>, Result>() {
@Override
public Result apply(Page<DataSource> dataSources, Page<Category> categories, final Page<SourceDatasetStats> sourceDatasets, final List<Column> columns) throws Throwable {
Logger.debug ("Create form: #datasources=" + dataSources.pageCount() +
", #categories=" + categories.pageCount() +
", #sourcedatasets=" + sourceDatasets.pageCount() +
", #columns: " + columns.size () +
", datasetForm: " + datasetForm);
return ok (form.render (dataSources, categories, sourceDatasets, columns, datasetForm, true));
}
});
}
public static Promise<Result> createForm () {
Logger.debug ("createForm");
final Form<DatasetForm> datasetForm = Form.form (DatasetForm.class).fill (new DatasetForm ());
return renderCreateForm (datasetForm);
}
public static Promise<Result> createFormForSourceDataset (final String sourceDatasetId) {
final ActorSelection database = Akka.system().actorSelection (databaseRef);
return from (database)
.get (SourceDataset.class, sourceDatasetId)
.executeFlat (new Function<SourceDataset, Promise<Result>> () {
@Override
public Promise<Result> apply (final SourceDataset sourceDataset) throws Throwable {
if (sourceDataset == null) {
return Promise.pure ((Result) notFound ());
}
final DatasetForm form = new DatasetForm ();
form.setName (sourceDataset.name ());
form.setSourceDatasetId (sourceDatasetId);
form.setDataSourceId (sourceDataset.dataSource ().id ());
form.setCategoryId (sourceDataset.category ().id ());
return renderCreateForm (Form.form (DatasetForm.class).fill (form));
}
});
}
public static Promise<Result> submitCreate () {
Logger.debug ("submitCreate");
final ActorSelection database = Akka.system().actorSelection (databaseRef);
final Form<DatasetForm> datasetForm = Form.form (DatasetForm.class).bindFromRequest ();
if (datasetForm.hasErrors ()) {
return renderCreateForm (datasetForm);
}
final DatasetForm dataset = datasetForm.get ();
return from (database)
.get (DataSource.class, dataset.getDataSourceId ())
.get (Category.class, dataset.getCategoryId ())
.get (SourceDataset.class, dataset.getSourceDatasetId ())
.query (new ListSourceDatasetColumns (dataset.getDataSourceId (), dataset.getSourceDatasetId ()))
.executeFlat (new Function4<DataSource, Category, SourceDataset, List<Column>, Promise<Result>> () {
@Override
public Promise<Result> apply (final DataSource dataSource, final Category category, final SourceDataset sourceDataset, final List<Column> sourceColumns) throws Throwable {
Logger.debug ("dataSource: " + dataSource);
Logger.debug ("category: " + category);
Logger.debug ("sourceDataset: " + sourceDataset);
// TODO: Validate dataSource, category, sourceDataset and columns!
// Validate the filter:
if (!dataset.getFilterConditions ().isValid (sourceColumns)) {
datasetForm.reject (new ValidationError ("filterConditions", "Het opgegeven filter is ongeldig"));
return renderCreateForm (datasetForm);
}
// Create the list of selected columns:
final List<Column> columns = new ArrayList<> ();
for (final Column column: sourceColumns) {
if (dataset.getColumns ().containsKey (column.getName ())) {
columns.add (column);
}
}
final PutDataset putDataset = new PutDataset (CrudOperation.CREATE,
ID,
dataset.getName (),
sourceDataset.id (),
columns,
dataset.getFilterConditions ()
);
Logger.debug ("create dataset " + putDataset);
return from (database)
.put(putDataset)
.executeFlat (new Function<Response<?>, Promise<Result>> () {
@Override
public Promise<Result> apply (final Response<?> response) throws Throwable {
if (CrudResponse.NOK.equals (response.getOperationResponse ())) {
datasetForm.reject ("Er bestaat al een dataset met tabelnaam " + dataset.getId ());
return renderCreateForm (datasetForm);
}
flash ("success", "Dataset " + dataset.getName () + " is toegevoegd.");
return Promise.pure (redirect (routes.Datasets.list (routes.Datasets.list$default$1())));
}
});
}
});
}
private static Promise<Result> renderEditForm (final Form<DatasetForm> datasetForm) {
//TODO
final ActorSelection database = Akka.system().actorSelection (databaseRef);
return from(database)
.list(DataSource.class)
.list(Category.class)
.query (listSourceDatasets (datasetForm.field ("dataSourceId").value (), datasetForm.field ("categoryId").value ()))
// .query (listDatasetColumns (datasetForm.field ("id").value ()))
.query (listSourceDatasetColumns (datasetForm.field ("dataSourceId").value (), datasetForm.field ("sourceDatasetId").value ()))
.execute(new Function4<Page<DataSource>, Page<Category>, Page<SourceDatasetStats>, List<Column>, Result>() {
@Override
public Result apply(Page<DataSource> dataSources, Page<Category> categories, final Page<SourceDatasetStats> sourceDatasets, final List<Column> columns) throws Throwable {
Logger.debug ("Edit form: #datasources=" + dataSources.pageCount() +
", #categories=" + categories.pageCount() +
", #sourcedatasets=" + sourceDatasets.pageCount() +
", #columns: " + columns.size ());
return ok (form.render (dataSources, categories, sourceDatasets, columns, datasetForm, false));
}
});
}
public static Promise<Result> editForm (final String datasetId) {
//TODO
Logger.debug ("editForm");
final ActorSelection database = Akka.system().actorSelection (databaseRef);
return from (database)
.get (Dataset.class, datasetId)
.query (listDatasetColumns (datasetId))
.executeFlat (new Function2<Dataset, List<Column>, Promise<Result>> () {
@Override
public Promise<Result> apply (final Dataset ds, final List<Column> columns) throws Throwable {
return from (database)
.get (SourceDataset.class, ds.sourceDataset().id())
.executeFlat (new Function<SourceDataset, Promise<Result>> () {
@Override
public Promise<Result> apply (final SourceDataset sds) throws Throwable {
final Form<DatasetForm> datasetForm = Form
.form (DatasetForm.class)
.fill (new DatasetForm (ds, sds.dataSource().id(), columns));
Logger.debug ("Edit datasetForm: " + datasetForm);
return renderEditForm (datasetForm);
}
});
}
});
// return Promise.pure ((Result) ok ());
}
public static Promise<Result> submitEdit (final String datasetId) {
Logger.debug ("submitEdit");
final ActorSelection database = Akka.system().actorSelection (databaseRef);
final Form<DatasetForm> datasetForm = Form.form (DatasetForm.class).bindFromRequest ();
if (datasetForm.hasErrors ()) {
Logger.debug("errors: {}", datasetForm.errors());
return renderEditForm (datasetForm);
}
final DatasetForm dataset = datasetForm.get ();
return from (database)
.get (DataSource.class, dataset.getDataSourceId ())
.get (Category.class, dataset.getCategoryId ())
.get (SourceDataset.class, dataset.getSourceDatasetId ())
.query (new ListSourceDatasetColumns (dataset.getDataSourceId (), dataset.getSourceDatasetId ()))
.executeFlat (new Function4<DataSource, Category, SourceDataset, List<Column>, Promise<Result>> () {
@Override
public Promise<Result> apply (final DataSource dataSource, final Category category, final SourceDataset sourceDataset, final List<Column> sourceColumns) throws Throwable {
Logger.debug ("dataSource: " + dataSource);
Logger.debug ("category: " + category);
Logger.debug ("sourceDataset: " + sourceDataset);
// TODO: Validate dataSource, category, sourceDataset!
// Validate the columns used by the filter:
if (!dataset.getFilterConditions ().isValid (sourceColumns)) {
datasetForm.reject (new ValidationError ("filterConditions", "Het opgegeven filter is ongeldig"));
return renderEditForm (datasetForm);
}
// Create the list of selected columns:
final List<Column> columns = new ArrayList<> ();
for (final Column column: sourceColumns) {
if (dataset.getColumns ().containsKey (column.getName ())) {
columns.add (column);
}
}
final PutDataset putDataset = new PutDataset (CrudOperation.UPDATE,
dataset.getId (),
dataset.getName (),
sourceDataset.id (),
columns,
dataset.getFilterConditions ()
);
Logger.debug ("update dataset " + putDataset);
return from (database)
.put(putDataset)
.executeFlat (new Function<Response<?>, Promise<Result>> () {
@Override
public Promise<Result> apply (final Response<?> response) throws Throwable {
if (CrudResponse.NOK.equals (response.getOperationResponse ())) {
datasetForm.reject ("dataset kon niet worden geupdate: " + dataset.getName ());
return renderEditForm (datasetForm);
}
flash ("success", "Dataset " + dataset.getName () + " is aangepast.");
return Promise.pure (redirect (routes.Datasets.list (routes.Datasets.list$default$1())));
}
});
}
});
}
public static Promise<Result> listByCategoryAndMessages (final String categoryId, final boolean listWithMessages, final long page) {
// Hack: force the database actor to be loaded:
if (Database.instance == null) {
throw new NullPointerException ();
}
final ActorSelection database = Akka.system().actorSelection (databaseRef);
return from (database)
.list (Category.class)
.get (Category.class, categoryId)
.executeFlat (new Function2<Page<Category>, Category, Promise<Result>> () {
@Override
public Promise<Result> apply (final Page<Category> categories, final Category currentCategory) throws Throwable {
return from (database)
.query (new ListDatasets (currentCategory, page))
.execute (new Function<Page<Dataset>, Result> () {
@Override
public Result apply (final Page<Dataset> datasets) throws Throwable {
// return ok (list.render (listWithMessages));
return ok (list.render (datasets, categories.values (), currentCategory, listWithMessages));
}
});
}
});
}
public static Promise<Result> listColumnsAction (final String dataSourceId, final String sourceDatasetId) {
final ActorSelection database = Akka.system().actorSelection (databaseRef);
return
from(database)
.query(new ListSourceDatasetColumns(dataSourceId, sourceDatasetId))
.execute(new Function<List<Column>, Result>() {
@Override
public Result apply(List<Column> c) throws Throwable {
return ok(columns.render(c, null, false));
}
});
}
public static Promise<Result> getDatasetJson (final String datasetId) {
final ActorSelection database = Akka.system().actorSelection (databaseRef);
Logger.debug ("getDatasetJson: " + datasetId);
return from (database)
.get (Dataset.class, datasetId)
.execute (new Function<Dataset, Result> () {
@Override
public Result apply (final Dataset ds) throws Throwable {
final ObjectNode result = Json.newObject ();
result.put ("id", datasetId);
if (ds == null) {
result.put ("status", "notfound");
return ok (result);
}
result.put ("status", "ok");
result.put ("dataset", Json.toJson (ds));
return ok (result);
}
});
}
private static Filter emptyFilter () {
final Filter.OperatorExpression andExpression = new Filter.OperatorExpression (OperatorType.AND, Collections.<Filter.FilterExpression>emptyList ());
final Filter.OperatorExpression orExpression = new Filter.OperatorExpression (OperatorType.OR, Arrays.<Filter.FilterExpression>asList (new Filter.FilterExpression[] { andExpression }));
return new Filter (orExpression);
}
public static class DatasetForm {
@Constraints.Required
@Constraints.MinLength (1)
private String name;
@Constraints.Required
private String dataSourceId;
@Constraints.Required
private String categoryId;
@Constraints.Required
private String sourceDatasetId;
@Constraints.Required
private Map<String, String> columns;
@Constraints.Required
private String id;
@Constraints.Required
private Filter filterConditions;
public DatasetForm () {
filterConditions = emptyFilter ();
}
public DatasetForm (final Dataset ds, String dataSourceId, List<Column> columns) {
setName (ds.name ());
setDataSourceId (dataSourceId);
setCategoryId (ds.category ().id ());
setSourceDatasetId (ds.sourceDataset ().id ());
Map<String, String> map = new HashMap<String, String>();
for (Column column : columns) {
map.put(column.getName(), column.getDataType().toString());
}
setColumns (map);
setId (ds.id ());
setFilterConditions (ds.filterConditions ());
}
public String getName() {
return name;
}
public void setName (final String name) {
this.name = name;
}
public String getDataSourceId () {
return dataSourceId;
}
public void setDataSourceId (final String dataSourceId) {
this.dataSourceId = dataSourceId;
}
public String getCategoryId() {
return categoryId;
}
public void setCategoryId (final String categoryId) {
this.categoryId = categoryId;
}
public String getSourceDatasetId () {
return sourceDatasetId;
}
public void setSourceDatasetId (final String sourceDatasetId) {
this.sourceDatasetId = sourceDatasetId;
}
public Map<String, String> getColumns () {
return columns;
}
public void setColumns (final Map<String, String> columns) {
this.columns = columns;
}
public String getId () {
return id;
}
public void setId (final String id) {
this.id = id;
}
public Filter getFilterConditions () {
return filterConditions;
}
public void setFilterConditions (final Filter filterConditions) {
this.filterConditions = filterConditions;
}
@Override
public String toString() {
return "DatasetForm [name=" + name + ", dataSourceId="
+ dataSourceId + ", categoryId=" + categoryId
+ ", sourceDatasetId=" + sourceDatasetId + ", columns="
+ columns + ", id=" + id + "]";
}
}
}
| publisher-web/app/controllers/Datasets.java | package controllers;
import static models.Domain.from;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import models.Domain.Constant;
import models.Domain.Function;
import models.Domain.Function2;
import models.Domain.Function4;
import nl.idgis.publisher.domain.job.ConfirmNotificationResult;
import nl.idgis.publisher.domain.query.DomainQuery;
import nl.idgis.publisher.domain.query.ListDatasetColumnDiff;
import nl.idgis.publisher.domain.query.ListDatasetColumns;
import nl.idgis.publisher.domain.query.ListDatasets;
import nl.idgis.publisher.domain.query.ListSourceDatasetColumns;
import nl.idgis.publisher.domain.query.ListSourceDatasets;
import nl.idgis.publisher.domain.query.PutNotificationResult;
import nl.idgis.publisher.domain.query.RefreshDataset;
import nl.idgis.publisher.domain.response.Page;
import nl.idgis.publisher.domain.response.Response;
import nl.idgis.publisher.domain.service.Column;
import nl.idgis.publisher.domain.service.ColumnDiff;
import nl.idgis.publisher.domain.service.CrudOperation;
import nl.idgis.publisher.domain.service.CrudResponse;
import nl.idgis.publisher.domain.web.Category;
import nl.idgis.publisher.domain.web.DataSource;
import nl.idgis.publisher.domain.web.Dataset;
import nl.idgis.publisher.domain.web.Filter;
import nl.idgis.publisher.domain.web.Filter.OperatorType;
import nl.idgis.publisher.domain.web.PutDataset;
import nl.idgis.publisher.domain.web.SourceDataset;
import nl.idgis.publisher.domain.web.SourceDatasetStats;
import play.Logger;
import play.Play;
import play.data.Form;
import play.data.validation.Constraints;
import play.data.validation.ValidationError;
import play.libs.Akka;
import play.libs.F.Promise;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Result;
import play.mvc.Security;
import views.html.datasets.columns;
import views.html.datasets.form;
import views.html.datasets.list;
import views.html.datasets.show;
import views.html.datasets.status;
import actions.DefaultAuthenticator;
import actors.Database;
import akka.actor.ActorSelection;
import com.fasterxml.jackson.databind.node.ObjectNode;
@Security.Authenticated (DefaultAuthenticator.class)
public class Datasets extends Controller {
private final static String databaseRef = Play.application().configuration().getString("publisher.database.actorRef");
private final static String ID="#CREATE_DATASET#";
public static Promise<Result> list (long page) {
return listByCategoryAndMessages(null, false, page);
}
public static Promise<Result> listWithMessages (long page) {
return listByCategoryAndMessages(null, true, page);
}
public static Promise<Result> listByCategory (String categoryId, long page) {
return listByCategoryAndMessages(categoryId, false, page);
}
public static Promise<Result> listByCategoryWithMessages (String categoryId, long page) {
return listByCategoryAndMessages(categoryId, true, page);
}
public static Promise<Result> show (final String datasetId) {
final ActorSelection database = Akka.system().actorSelection (databaseRef);
return from (database)
.get (Dataset.class, datasetId)
.query (new ListDatasetColumnDiff (datasetId))
.execute (new Function2<Dataset, List<ColumnDiff>, Result> () {
@Override
public Result apply (final Dataset dataset, final List<ColumnDiff> diffs) throws Throwable {
return ok (show.render (dataset, diffs));
}
});
}
public static Promise<Result> status (final String datasetId) {
final ActorSelection database = Akka.system().actorSelection (databaseRef);
return from (database)
.get (Dataset.class, datasetId)
.execute (new Function<Dataset, Result> () {
@Override
public Result apply (final Dataset dataset) throws Throwable {
return ok (status.render (dataset));
}
});
}
public static Promise<Result> setNotificationResult (final String datasetId, final String notificationId) {
final String[] resultString = request ().body ().asFormUrlEncoded ().get ("result");
if (resultString == null || resultString.length != 1 || resultString[0] == null) {
return Promise.pure ((Result) redirect (controllers.routes.Datasets.show (datasetId)));
}
final ConfirmNotificationResult result = ConfirmNotificationResult.valueOf (resultString[0]);
Logger.debug ("Conform notification: " + notificationId + ", " + result);
final ActorSelection database = Akka.system().actorSelection (databaseRef);
return from (database)
.query (new PutNotificationResult (notificationId, result))
.execute (new Function<Response<?>, Result> () {
@Override
public Result apply (final Response<?> response) throws Throwable {
if (response.getOperationResponse ().equals (CrudResponse.OK)) {
flash ("success", "Resultaat van de structuurwijziging is opgeslagen");
} else {
flash ("danger", "Resultaat van de structuurwijziging kon niet worden opgeslagen");
}
return redirect (controllers.routes.Datasets.show (datasetId));
}
});
}
public static Promise<Result> scheduleRefresh(String datasetId) {
final ActorSelection database = Akka.system().actorSelection (databaseRef);
return from(database)
.query(new RefreshDataset(datasetId))
.execute(new Function<Boolean, Result>() {
@Override
public Result apply(Boolean b) throws Throwable {
final ObjectNode result = Json.newObject ();
if (b) {
result.put ("result", "ok");
return ok (result);
} else {
result.put ("result", "failed");
return internalServerError (result);
}
}
});
}
public static Promise<Result> delete(final String datasetId){
System.out.println("delete dataset " + datasetId);
final ActorSelection database = Akka.system().actorSelection (databaseRef);
return from (database)
.delete (Dataset.class, datasetId)
.execute (new Function<Response<?>, Result> () {
@Override
public Result apply (final Response<?> response) throws Throwable {
if (CrudResponse.OK.equals (response.getOperationResponse ())) {
flash ("success", "De dataset is verwijderd");
} else {
flash ("danger", "De dataset kon niet worden verwijderd");
}
return redirect (routes.Datasets.list (1));
}
});
}
private static DomainQuery<Page<SourceDatasetStats>> listSourceDatasets (final String dataSourceId, final String categoryId) {
if (dataSourceId == null || categoryId == null || dataSourceId.isEmpty () || categoryId.isEmpty ()) {
return new Constant<Page<SourceDatasetStats>> (new Page.Builder<SourceDatasetStats> ().build ());
}
return new ListSourceDatasets (dataSourceId, categoryId, null, null, null);
}
private static DomainQuery<List<Column>> listSourceDatasetColumns (final String dataSourceId, final String sourceDatasetId) {
if (dataSourceId == null || sourceDatasetId == null || dataSourceId.isEmpty () || sourceDatasetId.isEmpty ()) {
return new Constant<List<Column>> (Collections.<Column>emptyList ());
}
return new ListSourceDatasetColumns (dataSourceId, sourceDatasetId);
}
private static DomainQuery<List<Column>> listDatasetColumns (final String datasetId) {
if (datasetId == null || datasetId.isEmpty ()) {
return new Constant<List<Column>> (Collections.<Column>emptyList ());
}
return new ListDatasetColumns (datasetId);
}
private static Promise<Result> renderCreateForm (final Form<DatasetForm> datasetForm) {
final ActorSelection database = Akka.system().actorSelection (databaseRef);
return from(database)
.list(DataSource.class)
.list(Category.class)
.query (listSourceDatasets (datasetForm.field ("dataSourceId").value (), datasetForm.field ("categoryId").value ()))
.query (listSourceDatasetColumns (datasetForm.field ("dataSourceId").value (), datasetForm.field ("sourceDatasetId").value ()))
.execute(new Function4<Page<DataSource>, Page<Category>, Page<SourceDatasetStats>, List<Column>, Result>() {
@Override
public Result apply(Page<DataSource> dataSources, Page<Category> categories, final Page<SourceDatasetStats> sourceDatasets, final List<Column> columns) throws Throwable {
Logger.debug ("Create form: #datasources=" + dataSources.pageCount() +
", #categories=" + categories.pageCount() +
", #sourcedatasets=" + sourceDatasets.pageCount() +
", #columns: " + columns.size () +
", datasetForm: " + datasetForm);
return ok (form.render (dataSources, categories, sourceDatasets, columns, datasetForm, true));
}
});
}
public static Promise<Result> createForm () {
Logger.debug ("createForm");
final Form<DatasetForm> datasetForm = Form.form (DatasetForm.class).fill (new DatasetForm ());
return renderCreateForm (datasetForm);
}
public static Promise<Result> createFormForSourceDataset (final String sourceDatasetId) {
final ActorSelection database = Akka.system().actorSelection (databaseRef);
return from (database)
.get (SourceDataset.class, sourceDatasetId)
.executeFlat (new Function<SourceDataset, Promise<Result>> () {
@Override
public Promise<Result> apply (final SourceDataset sourceDataset) throws Throwable {
if (sourceDataset == null) {
return Promise.pure ((Result) notFound ());
}
final DatasetForm form = new DatasetForm ();
form.setName (sourceDataset.name ());
form.setSourceDatasetId (sourceDatasetId);
form.setDataSourceId (sourceDataset.dataSource ().id ());
form.setCategoryId (sourceDataset.category ().id ());
return renderCreateForm (Form.form (DatasetForm.class).fill (form));
}
});
}
public static Promise<Result> submitCreate () {
Logger.debug ("submitCreate");
final ActorSelection database = Akka.system().actorSelection (databaseRef);
final Form<DatasetForm> datasetForm = Form.form (DatasetForm.class).bindFromRequest ();
if (datasetForm.hasErrors ()) {
return renderCreateForm (datasetForm);
}
final DatasetForm dataset = datasetForm.get ();
return from (database)
.get (DataSource.class, dataset.getDataSourceId ())
.get (Category.class, dataset.getCategoryId ())
.get (SourceDataset.class, dataset.getSourceDatasetId ())
.query (new ListSourceDatasetColumns (dataset.getDataSourceId (), dataset.getSourceDatasetId ()))
.executeFlat (new Function4<DataSource, Category, SourceDataset, List<Column>, Promise<Result>> () {
@Override
public Promise<Result> apply (final DataSource dataSource, final Category category, final SourceDataset sourceDataset, final List<Column> sourceColumns) throws Throwable {
Logger.debug ("dataSource: " + dataSource);
Logger.debug ("category: " + category);
Logger.debug ("sourceDataset: " + sourceDataset);
// TODO: Validate dataSource, category, sourceDataset and columns!
// Validate the filter:
if (!dataset.getFilterConditions ().isValid (sourceColumns)) {
datasetForm.reject (new ValidationError ("filterConditions", "Het opgegeven filter is ongeldig"));
return renderCreateForm (datasetForm);
}
// Create the list of selected columns:
final List<Column> columns = new ArrayList<> ();
for (final Column column: sourceColumns) {
if (dataset.getColumns ().containsKey (column.getName ())) {
columns.add (column);
}
}
final PutDataset putDataset = new PutDataset (CrudOperation.CREATE,
ID,
dataset.getName (),
sourceDataset.id (),
columns,
dataset.getFilterConditions ()
);
Logger.debug ("create dataset " + putDataset);
return from (database)
.put(putDataset)
.executeFlat (new Function<Response<?>, Promise<Result>> () {
@Override
public Promise<Result> apply (final Response<?> response) throws Throwable {
if (CrudResponse.NOK.equals (response.getOperationResponse ())) {
datasetForm.reject ("Er bestaat al een dataset met tabelnaam " + dataset.getId ());
return renderCreateForm (datasetForm);
}
flash ("success", "Dataset " + dataset.getName () + " is toegevoegd.");
return Promise.pure (redirect (routes.Datasets.list (routes.Datasets.list$default$1())));
}
});
}
});
}
private static Promise<Result> renderEditForm (final Form<DatasetForm> datasetForm) {
//TODO
final ActorSelection database = Akka.system().actorSelection (databaseRef);
return from(database)
.list(DataSource.class)
.list(Category.class)
.query (listSourceDatasets (datasetForm.field ("dataSourceId").value (), datasetForm.field ("categoryId").value ()))
// .query (listDatasetColumns (datasetForm.field ("id").value ()))
.query (listSourceDatasetColumns (datasetForm.field ("dataSourceId").value (), datasetForm.field ("sourceDatasetId").value ()))
.execute(new Function4<Page<DataSource>, Page<Category>, Page<SourceDatasetStats>, List<Column>, Result>() {
@Override
public Result apply(Page<DataSource> dataSources, Page<Category> categories, final Page<SourceDatasetStats> sourceDatasets, final List<Column> columns) throws Throwable {
Logger.debug ("Edit form: #datasources=" + dataSources.pageCount() +
", #categories=" + categories.pageCount() +
", #sourcedatasets=" + sourceDatasets.pageCount() +
", #columns: " + columns.size ());
return ok (form.render (dataSources, categories, sourceDatasets, columns, datasetForm, false));
}
});
}
public static Promise<Result> editForm (final String datasetId) {
//TODO
Logger.debug ("editForm");
final ActorSelection database = Akka.system().actorSelection (databaseRef);
return from (database)
.get (Dataset.class, datasetId)
.query (listDatasetColumns (datasetId))
.executeFlat (new Function2<Dataset, List<Column>, Promise<Result>> () {
@Override
public Promise<Result> apply (final Dataset ds, final List<Column> columns) throws Throwable {
return from (database)
.get (SourceDataset.class, ds.sourceDataset().id())
.executeFlat (new Function<SourceDataset, Promise<Result>> () {
@Override
public Promise<Result> apply (final SourceDataset sds) throws Throwable {
final Form<DatasetForm> datasetForm = Form
.form (DatasetForm.class)
.fill (new DatasetForm (ds, sds.dataSource().id(), columns));
Logger.debug ("Edit datasetForm: " + datasetForm);
return renderEditForm (datasetForm);
}
});
}
});
// return Promise.pure ((Result) ok ());
}
public static Promise<Result> submitEdit (final String datasetId) {
Logger.debug ("submitEdit");
final ActorSelection database = Akka.system().actorSelection (databaseRef);
final Form<DatasetForm> datasetForm = Form.form (DatasetForm.class).bindFromRequest ();
if (datasetForm.hasErrors ()) {
Logger.debug("errors: {}", datasetForm.errors());
return renderEditForm (datasetForm);
}
final DatasetForm dataset = datasetForm.get ();
return from (database)
.get (DataSource.class, dataset.getDataSourceId ())
.get (Category.class, dataset.getCategoryId ())
.get (SourceDataset.class, dataset.getSourceDatasetId ())
.query (new ListSourceDatasetColumns (dataset.getDataSourceId (), dataset.getSourceDatasetId ()))
.executeFlat (new Function4<DataSource, Category, SourceDataset, List<Column>, Promise<Result>> () {
@Override
public Promise<Result> apply (final DataSource dataSource, final Category category, final SourceDataset sourceDataset, final List<Column> sourceColumns) throws Throwable {
Logger.debug ("dataSource: " + dataSource);
Logger.debug ("category: " + category);
Logger.debug ("sourceDataset: " + sourceDataset);
// TODO: Validate dataSource, category, sourceDataset!
// Validate the columns used by the filter:
if (!dataset.getFilterConditions ().isValid (sourceColumns)) {
datasetForm.reject (new ValidationError ("filterConditions", "Het opgegeven filter is ongeldig"));
return renderEditForm (datasetForm);
}
// Create the list of selected columns:
final List<Column> columns = new ArrayList<> ();
for (final Column column: sourceColumns) {
if (dataset.getColumns ().containsKey (column.getName ())) {
columns.add (column);
}
}
final PutDataset putDataset = new PutDataset (CrudOperation.UPDATE,
dataset.getId (),
dataset.getName (),
sourceDataset.id (),
columns,
dataset.getFilterConditions ()
);
Logger.debug ("update dataset " + putDataset);
return from (database)
.put(putDataset)
.executeFlat (new Function<Response<?>, Promise<Result>> () {
@Override
public Promise<Result> apply (final Response<?> response) throws Throwable {
if (CrudResponse.NOK.equals (response.getOperationResponse ())) {
datasetForm.reject ("dataset kon niet worden geupdate: " + dataset.getName ());
return renderEditForm (datasetForm);
}
flash ("success", "Dataset " + dataset.getName () + " is aangepast.");
return Promise.pure (redirect (routes.Datasets.list (0)));
}
});
}
});
}
public static Promise<Result> listByCategoryAndMessages (final String categoryId, final boolean listWithMessages, final long page) {
// Hack: force the database actor to be loaded:
if (Database.instance == null) {
throw new NullPointerException ();
}
final ActorSelection database = Akka.system().actorSelection (databaseRef);
return from (database)
.list (Category.class)
.get (Category.class, categoryId)
.executeFlat (new Function2<Page<Category>, Category, Promise<Result>> () {
@Override
public Promise<Result> apply (final Page<Category> categories, final Category currentCategory) throws Throwable {
return from (database)
.query (new ListDatasets (currentCategory, page))
.execute (new Function<Page<Dataset>, Result> () {
@Override
public Result apply (final Page<Dataset> datasets) throws Throwable {
// return ok (list.render (listWithMessages));
return ok (list.render (datasets, categories.values (), currentCategory, listWithMessages));
}
});
}
});
}
public static Promise<Result> listColumnsAction (final String dataSourceId, final String sourceDatasetId) {
final ActorSelection database = Akka.system().actorSelection (databaseRef);
return
from(database)
.query(new ListSourceDatasetColumns(dataSourceId, sourceDatasetId))
.execute(new Function<List<Column>, Result>() {
@Override
public Result apply(List<Column> c) throws Throwable {
return ok(columns.render(c, null, false));
}
});
}
public static Promise<Result> getDatasetJson (final String datasetId) {
final ActorSelection database = Akka.system().actorSelection (databaseRef);
Logger.debug ("getDatasetJson: " + datasetId);
return from (database)
.get (Dataset.class, datasetId)
.execute (new Function<Dataset, Result> () {
@Override
public Result apply (final Dataset ds) throws Throwable {
final ObjectNode result = Json.newObject ();
result.put ("id", datasetId);
if (ds == null) {
result.put ("status", "notfound");
return ok (result);
}
result.put ("status", "ok");
result.put ("dataset", Json.toJson (ds));
return ok (result);
}
});
}
private static Filter emptyFilter () {
final Filter.OperatorExpression andExpression = new Filter.OperatorExpression (OperatorType.AND, Collections.<Filter.FilterExpression>emptyList ());
final Filter.OperatorExpression orExpression = new Filter.OperatorExpression (OperatorType.OR, Arrays.<Filter.FilterExpression>asList (new Filter.FilterExpression[] { andExpression }));
return new Filter (orExpression);
}
public static class DatasetForm {
@Constraints.Required
@Constraints.MinLength (1)
private String name;
@Constraints.Required
private String dataSourceId;
@Constraints.Required
private String categoryId;
@Constraints.Required
private String sourceDatasetId;
@Constraints.Required
private Map<String, String> columns;
@Constraints.Required
private String id;
@Constraints.Required
private Filter filterConditions;
public DatasetForm () {
filterConditions = emptyFilter ();
}
public DatasetForm (final Dataset ds, String dataSourceId, List<Column> columns) {
setName (ds.name ());
setDataSourceId (dataSourceId);
setCategoryId (ds.category ().id ());
setSourceDatasetId (ds.sourceDataset ().id ());
Map<String, String> map = new HashMap<String, String>();
for (Column column : columns) {
map.put(column.getName(), column.getDataType().toString());
}
setColumns (map);
setId (ds.id ());
setFilterConditions (ds.filterConditions ());
}
public String getName() {
return name;
}
public void setName (final String name) {
this.name = name;
}
public String getDataSourceId () {
return dataSourceId;
}
public void setDataSourceId (final String dataSourceId) {
this.dataSourceId = dataSourceId;
}
public String getCategoryId() {
return categoryId;
}
public void setCategoryId (final String categoryId) {
this.categoryId = categoryId;
}
public String getSourceDatasetId () {
return sourceDatasetId;
}
public void setSourceDatasetId (final String sourceDatasetId) {
this.sourceDatasetId = sourceDatasetId;
}
public Map<String, String> getColumns () {
return columns;
}
public void setColumns (final Map<String, String> columns) {
this.columns = columns;
}
public String getId () {
return id;
}
public void setId (final String id) {
this.id = id;
}
public Filter getFilterConditions () {
return filterConditions;
}
public void setFilterConditions (final Filter filterConditions) {
this.filterConditions = filterConditions;
}
@Override
public String toString() {
return "DatasetForm [name=" + name + ", dataSourceId="
+ dataSourceId + ", categoryId=" + categoryId
+ ", sourceDatasetId=" + sourceDatasetId + ", columns="
+ columns + ", id=" + id + "]";
}
}
}
| return to default page # | publisher-web/app/controllers/Datasets.java | return to default page # |
|
Java | lgpl-2.1 | c141fc5a832b2210f9ece630a4039970286383aa | 0 | pentaho/pentaho-commons-xul | package org.pentaho.ui.xul.gwt.tags;
import com.allen_sauer.gwt.dnd.client.DragContext;
import com.allen_sauer.gwt.dnd.client.VetoDragException;
import com.allen_sauer.gwt.dnd.client.drop.AbstractPositioningDropController;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.widgetideas.table.client.SelectionGrid.SelectionPolicy;
import com.google.gwt.widgetideas.table.client.SourceTableSelectionEvents;
import com.google.gwt.widgetideas.table.client.TableSelectionListener;
import org.pentaho.gwt.widgets.client.buttons.ImageButton;
import org.pentaho.gwt.widgets.client.listbox.CustomListBox;
import org.pentaho.gwt.widgets.client.table.BaseTable;
import org.pentaho.gwt.widgets.client.table.ColumnComparators.BaseColumnComparator;
import org.pentaho.gwt.widgets.client.ui.Draggable;
import org.pentaho.gwt.widgets.client.utils.string.StringUtils;
import org.pentaho.ui.xul.XulComponent;
import org.pentaho.ui.xul.XulDomContainer;
import org.pentaho.ui.xul.XulEventSource;
import org.pentaho.ui.xul.XulException;
import org.pentaho.ui.xul.binding.Binding;
import org.pentaho.ui.xul.binding.BindingConvertor;
import org.pentaho.ui.xul.binding.InlineBindingExpression;
import org.pentaho.ui.xul.components.XulTreeCell;
import org.pentaho.ui.xul.components.XulTreeCol;
import org.pentaho.ui.xul.containers.*;
import org.pentaho.ui.xul.dnd.DataTransfer;
import org.pentaho.ui.xul.dnd.DropEvent;
import org.pentaho.ui.xul.dnd.DropPosition;
import org.pentaho.ui.xul.dom.Document;
import org.pentaho.ui.xul.dom.Element;
import org.pentaho.ui.xul.gwt.AbstractGwtXulContainer;
import org.pentaho.ui.xul.gwt.GwtXulHandler;
import org.pentaho.ui.xul.gwt.GwtXulParser;
import org.pentaho.ui.xul.gwt.binding.GwtBinding;
import org.pentaho.ui.xul.gwt.binding.GwtBindingContext;
import org.pentaho.ui.xul.gwt.binding.GwtBindingMethod;
import org.pentaho.ui.xul.gwt.tags.util.TreeItemWidget;
import org.pentaho.ui.xul.gwt.util.Resizable;
import org.pentaho.ui.xul.gwt.util.XulDragController;
import org.pentaho.ui.xul.impl.XulEventHandler;
import org.pentaho.ui.xul.stereotype.Bindable;
import org.pentaho.ui.xul.util.TreeCellEditor;
import org.pentaho.ui.xul.util.TreeCellEditorCallback;
import org.pentaho.ui.xul.util.TreeCellRenderer;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
public class GwtTree extends AbstractGwtXulContainer implements XulTree, Resizable {
/**
* Cached elements.
*/
private Collection elements;
private GwtBindingMethod dropVetoerMethod;
private XulEventHandler dropVetoerController;
public static void register() {
GwtXulParser.registerHandler("tree",
new GwtXulHandler() {
public Element newInstance() {
return new GwtTree();
}
});
}
XulTreeCols columns = null;
XulTreeChildren rootChildren = null;
private XulDomContainer domContainer;
private Tree tree;
private boolean suppressEvents = false;
private boolean editable = false;
private boolean visible = true;
private String command;
private Map<String, TreeCellEditor> customEditors = new HashMap<String, TreeCellEditor>();
private Map<String, TreeCellRenderer> customRenderers = new HashMap<String, TreeCellRenderer>();
private List<Binding> elementBindings = new ArrayList<Binding>();
private List<Binding> expandBindings = new ArrayList<Binding>();
private DropPositionIndicator dropPosIndicator = new DropPositionIndicator();
private boolean showAllEditControls = true;
@Bindable
public boolean isVisible() {
return visible;
}
@Bindable
public void setVisible(boolean visible) {
this.visible = visible;
if(simplePanel != null) {
simplePanel.setVisible(visible);
}
}
/**
* Used when this widget is a tree. Not used when this widget is a table.
*/
private FlowPanel scrollPanel = new FlowPanel();
{
scrollPanel.setStylePrimaryName("scroll-panel");
}
/**
* The managed object. If this widget is a tree, then the tree is added to the scrollPanel, which is added to this
* simplePanel. If this widget is a table, then the table is added directly to this simplePanel.
*/
private SimplePanel simplePanel = new SimplePanel();
/**
* Clears the parent panel and adds the given widget.
* @param widget tree or table to set in parent panel
*/
protected void setWidgetInPanel(final Widget widget) {
if (isHierarchical()) {
scrollPanel.clear();
simplePanel.add(scrollPanel);
scrollPanel.add(widget);
scrollPanel.add(dropPosIndicator);
} else {
simplePanel.clear();
simplePanel.add(widget);
}
}
public GwtTree() {
super("tree");
// managedObject is neither a native GWT tree nor a table since the entire native GWT object is thrown away each
// time we call setup{Tree|Table}; because the widget is thrown away, we need to reconnect the new widget to the
// simplePanel, which is the managedObject
setManagedObject(simplePanel);
}
public void init(com.google.gwt.xml.client.Element srcEle, XulDomContainer container) {
super.init(srcEle, container);
setOnselect(srcEle.getAttribute("onselect"));
setOnedit(srcEle.getAttribute("onedit"));
setSeltype(srcEle.getAttribute("seltype"));
if (StringUtils.isEmpty(srcEle.getAttribute("pen:ondrop")) == false) {
setOndrop(srcEle.getAttribute("pen:ondrop"));
}
if (StringUtils.isEmpty(srcEle.getAttribute("pen:ondrag")) == false) {
setOndrag(srcEle.getAttribute("pen:ondrag"));
}
if (StringUtils.isEmpty(srcEle.getAttribute("pen:drageffect")) == false) {
setDrageffect(srcEle.getAttribute("pen:drageffect"));
}
setDropvetoer(srcEle.getAttribute("pen:dropvetoer"));
if(StringUtils.isEmpty(srcEle.getAttribute("pen:showalleditcontrols")) == false){
this.setShowalleditcontrols(srcEle.getAttribute("pen:showalleditcontrols").equals("true"));
}
this.setEditable("true".equals(srcEle.getAttribute("editable")));
this.domContainer = container;
}
private List<TreeItemDropController> dropHandlers = new ArrayList<TreeItemDropController>();
public void addChild(Element element) {
super.addChild(element);
if (element.getName().equals("treecols")) {
columns = (XulTreeCols)element;
} else if (element.getName().equals("treechildren")) {
rootChildren = (XulTreeChildren)element;
}
}
public void addTreeRow(XulTreeRow row) {
GwtTreeItem item = new GwtTreeItem();
item.setRow(row);
this.rootChildren.addItem(item);
// update UI
updateUI();
}
private BaseTable table;
private boolean isHierarchical = false;
private boolean firstLayout = true;
private Object[][] currentData;
// need to handle layouting
public void layout() {
if(this.getRootChildren() == null){
//most likely an overlay
return;
}
if(firstLayout){
XulTreeItem item = (XulTreeItem) this.getRootChildren().getFirstChild();
if(item != null && item.getAttributeValue("container") != null && item.getAttributeValue("container").equals("true")){
isHierarchical = true;
}
firstLayout = false;
}
if(isHierarchical()){
setupTree();
} else {
setupTable();
}
setVisible(visible);
}
private int prevSelectionPos = -1;
private void setupTree(){
if(tree == null){
tree = new Tree();
setWidgetInPanel(tree);
}
scrollPanel.setWidth("100%"); //$NON-NLS-1$
scrollPanel.setHeight("100%"); //$NON-NLS-1$
scrollPanel.getElement().getStyle().setProperty("backgroundColor", "white"); //$NON-NLS-1$//$NON-NLS-2$
if (getWidth() > 0){
scrollPanel.setWidth(getWidth()+"px"); //$NON-NLS-1$
}
if (getHeight() > 0) {
scrollPanel.setHeight(getHeight()+"px"); //$NON-NLS-1$
}
tree.addTreeListener(new TreeListener(){
public void onTreeItemSelected(TreeItem arg0) {
int pos = -1;
int curPos = 0;
for(int i=0; i < tree.getItemCount(); i++){
TreeItem tItem = tree.getItem(i);
TreeCursor cursor = GwtTree.this.findPosition(tItem, arg0, curPos);
pos = cursor.foundPosition;
curPos = cursor.curPos+1;
if(pos > -1){
break;
}
}
if(pos > -1 && GwtTree.this.suppressEvents == false && prevSelectionPos != pos){
GwtTree.this.changeSupport.firePropertyChange("selectedRows",null,new int[]{pos});
GwtTree.this.changeSupport.firePropertyChange("absoluteSelectedRows",null,new int[]{pos});
GwtTree.this.fireSelectedItems();
}
prevSelectionPos = pos;
}
public void onTreeItemStateChanged(TreeItem item) {
((TreeItemWidget) item.getWidget()).getTreeItem().setExpanded(item.getState());
}
});
updateUI();
}
private class TreeCursor{
int foundPosition = -1;
int curPos;
TreeItem itemToFind;
public TreeCursor(int curPos, TreeItem itemToFind, int foundPosition){
this.foundPosition = foundPosition;
this.curPos = curPos;
this.itemToFind = itemToFind;
}
}
private TreeCursor findPosition(TreeItem curItem, TreeItem itemToFind, int curPos){
if(curItem == itemToFind){
TreeCursor p = new TreeCursor(curPos, itemToFind, curPos);
return p;
// } else if(curItem.getChildIndex(itemToFind) > -1) {
// curPos = curPos+1;
// return new TreeCursor(curPos+curItem.getChildIndex(itemToFind) , itemToFind, curPos+curItem.getChildIndex(itemToFind));
} else {
for(int i=1; i-1<curItem.getChildCount(); i++){
TreeCursor p = findPosition(curItem.getChild(i-1), itemToFind, curPos +1);
curPos = p.curPos;
if(p.foundPosition > -1){
return p;
}
}
//curPos += curItem.getChildCount() ;
return new TreeCursor(curPos, itemToFind, -1);
}
}
private void populateTree(){
tree.removeItems();
TreeItem topNode = new TreeItem("placeholder");
if(this.rootChildren == null){
this.rootChildren = (XulTreeChildren) this.children.get(1);
}
for (XulComponent c : this.rootChildren.getChildNodes()){
XulTreeItem item = (XulTreeItem) c;
TreeItem node = createNode(item);
tree.addItem(node);
}
if(StringUtils.isEmpty(this.ondrag) == false){
for (int i = 0; i < tree.getItemCount(); i++) {
madeDraggable(tree.getItem(i));
}
}
}
private void madeDraggable(TreeItem item){
XulDragController.getInstance().makeDraggable(item.getWidget());
for (int i = 0; i < item.getChildCount(); i++) {
madeDraggable(item.getChild(i));
}
}
private List<XulComponent> colCollection = new ArrayList<XulComponent>();
private void populateTable(){
int rowCount = getRootChildren().getItemCount();
// Getting column editors ends up calling getChildNodes several times. we're going to cache the column collections
// for the duration of the operation then clear it out.
colCollection = getColumns().getChildNodes();
int colCount = colCollection.size();
currentData = new Object[rowCount][colCount];
for (int i = 0; i < rowCount; i++) {
for (int j = 0; j < colCount; j++) {
currentData[i][j] = getColumnEditor(j,i);
}
}
table.populateTable(currentData);
int totalFlex = 0;
for (int i = 0; i < colCount; i++) {
totalFlex += colCollection.get(i).getFlex();
}
if(totalFlex > 0){
table.fillWidth();
}
colCollection = new ArrayList<XulComponent>();
if(this.selectedRows != null && this.selectedRows.length > 0){
for(int i=0; i<this.selectedRows.length; i++){
int idx = this.selectedRows[i];
if(idx > -1 && idx < currentData.length){
table.selectRow(idx);
}
}
}
}
private TreeItem createNode(final XulTreeItem item){
TreeItem node = new TreeItem("empty"){
@Override
public void setSelected( boolean selected ) {
super.setSelected(selected);
if(selected){
this.getWidget().addStyleDependentName("selected");
} else {
this.getWidget().removeStyleDependentName("selected");
}
}
};
item.setManagedObject(node);
if(item == null || item.getRow() == null || item.getRow().getChildNodes().size() == 0){
return node;
}
final TreeItemWidget tWidget = new TreeItemWidget(item);
PropertyChangeListener listener = new PropertyChangeListener(){
public void propertyChange(PropertyChangeEvent evt) {
if(evt.getPropertyName().equals("image") && item.getImage() != null){
tWidget.setImage(new Image(GWT.getModuleBaseURL() + item.getImage()));
} else if(evt.getPropertyName().equals("label")){
tWidget.setLabel(item.getRow().getCell(0).getLabel());
}
}
};
((GwtTreeItem) item).addPropertyChangeListener("image", listener);
((GwtTreeCell) item.getRow().getCell(0)).addPropertyChangeListener("label", listener);;
if (item.getImage() != null) {
tWidget.setImage(new Image(GWT.getModuleBaseURL() + item.getImage()));
}
tWidget.setLabel(item.getRow().getCell(0).getLabel());
if(this.ondrop != null){
TreeItemDropController controller = new TreeItemDropController(item, tWidget);
XulDragController.getInstance().registerDropController(controller);
this.dropHandlers.add(controller);
}
node.setWidget(tWidget);
if(item.getChildNodes().size() > 1){
//has children
//TODO: make this more defensive
XulTreeChildren children = (XulTreeChildren) item.getChildNodes().get(1);
for(XulComponent c : children.getChildNodes()){
TreeItem childNode = createNode((XulTreeItem) c);
node.addItem(childNode);
}
}
return node;
}
private String extractDynamicColType(Object row, int columnPos) {
GwtBindingMethod method = GwtBindingContext.typeController.findGetMethod(row, this.columns.getColumn(columnPos).getColumntypebinding());
try{
return (String) method.invoke(row, new Object[]{});
} catch (Exception e){
System.out.println("Could not extract column type from binding");
}
return "text"; // default //$NON-NLS-1$
}
private Binding createBinding(XulEventSource source, String prop1, XulEventSource target, String prop2){
if(bindingProvider != null){
return bindingProvider.getBinding(source, prop1, target, prop2);
}
return new GwtBinding(source, prop1, target, prop2);
}
private Widget getColumnEditor(final int x, final int y){
final XulTreeCol column = (XulTreeCol) colCollection.get(x);
String colType = ((XulTreeCol) colCollection.get(x)).getType();
final GwtTreeCell cell = (GwtTreeCell) getRootChildren().getItem(y).getRow().getCell(x);
String val = cell.getLabel();
// If collection bound, bindings may need to be updated for runtime changes in column types.
if(this.elements != null){
try {
this.addBindings(column, cell, this.elements.toArray()[y]);
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (XulException e) {
e.printStackTrace();
}
}
if(StringUtils.isEmpty(colType) == false && colType.equalsIgnoreCase("dynamic")){
Object row = elements.toArray()[y];
colType = extractDynamicColType(row, x);
}
int[] selectedRows = getSelectedRows();
if((StringUtils.isEmpty(colType) || !column.isEditable()) || ((showAllEditControls == false && (selectedRows.length != 1 || selectedRows[0] != y)) && !colType.equals("checkbox"))){
if(colType != null && (colType.equalsIgnoreCase("combobox") || colType.equalsIgnoreCase("editablecombobox"))){
Vector vals = (Vector) cell.getValue();
int idx = cell.getSelectedIndex();
if(colType.equalsIgnoreCase("editablecombobox")){
return new HTML(cell.getLabel());
} else if(idx < vals.size()){
return new HTML(""+vals.get(idx));
} else {
return new HTML("");
}
} else {
return new HTML(val);
}
} else if(colType.equalsIgnoreCase("text")){
try{
GwtTextbox b = (GwtTextbox) this.domContainer.getDocumentRoot().createElement("textbox");
b.setDisabled(!column.isEditable());
b.layout();
b.setValue(val);
Binding bind = createBinding(cell, "label", b, "value");
bind.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(bind);
bind.fireSourceChanged();
bind = createBinding(cell, "disabled", b, "disabled");
bind.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(bind);
bind.fireSourceChanged();
return (Widget) b.getManagedObject();
} catch(Exception e){
System.out.println("error creating textbox, fallback");
e.printStackTrace();
final TextBox b = new TextBox();
b.addKeyboardListener(new KeyboardListener(){
public void onKeyDown(Widget arg0, char arg1, int arg2) {}
public void onKeyPress(Widget arg0, char arg1, int arg2) {}
public void onKeyUp(Widget arg0, char arg1, int arg2) {
getRootChildren().getItem(y).getRow().getCell(x).setLabel(b.getText());
}
});
b.setText(val);
return b;
}
} else if (colType.equalsIgnoreCase("checkbox")) {
try {
GwtCheckbox checkBox = (GwtCheckbox) this.domContainer.getDocumentRoot().createElement("checkbox");
checkBox.setDisabled(!column.isEditable());
checkBox.layout();
checkBox.setChecked(Boolean.parseBoolean(val));
Binding bind = createBinding(cell, "value", checkBox, "checked");
bind.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(bind);
bind.fireSourceChanged();
bind = createBinding(cell, "disabled", checkBox, "disabled");
bind.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(bind);
bind.fireSourceChanged();
return (Widget)checkBox.getManagedObject();
} catch (Exception e) {
final CheckBox cb = new CheckBox();
return cb;
}
} else if(colType.equalsIgnoreCase("combobox") || colType.equalsIgnoreCase("editablecombobox")){
try{
final GwtMenuList glb = (GwtMenuList) this.domContainer.getDocumentRoot().createElement("menulist");
final CustomListBox lb = glb.getNativeListBox();
lb.setWidth("100%");
final String fColType = colType;
// Binding to elements of listbox not giving us the behavior we want. Menulists select the first available
// item by default. We don't want anything selected by default in these cell editors
PropertyChangeListener listener = new PropertyChangeListener(){
public void propertyChange(PropertyChangeEvent evt) {
Vector vals = (Vector) cell.getValue();
lb.clear();
lb.setSuppressLayout(true);
for(Object label : vals){
lb.addItem(label.toString());
}
lb.setSuppressLayout(false);
int idx = cell.getSelectedIndex();
if(idx < 0){
idx = 0;
}
if(idx < vals.size()){
lb.setSelectedIndex(idx);
}
if(fColType.equalsIgnoreCase("editablecombobox")){
lb.setValue("");
}
}
};
listener.propertyChange(null);
cell.addPropertyChangeListener("value", listener);
lb.addChangeListener(new ChangeListener(){
public void onChange(Widget arg0) {
if(fColType.equalsIgnoreCase("editablecombobox")){
cell.setLabel(lb.getValue());
} else {
cell.setSelectedIndex(lb.getSelectedIndex());
}
}
});
if(colType.equalsIgnoreCase("editablecombobox")){
lb.setEditable(true);
Binding bind = createBinding(cell, "selectedIndex", glb, "selectedIndex");
bind.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(bind);
if(cell.getLabel() == null){
bind.fireSourceChanged();
}
bind = createBinding(cell, "label", glb, "value");
bind.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(bind);
bind.fireSourceChanged();
} else {
Binding bind = createBinding(cell, "selectedIndex", glb, "selectedIndex");
bind.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(bind);
bind.fireSourceChanged();
}
Binding bind = createBinding(cell, "disabled", glb, "disabled");
bind.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(bind);
bind.fireSourceChanged();
return lb;
} catch(Exception e){
System.out.println("error creating menulist, fallback");
final String fColType = colType;
e.printStackTrace();
final CustomListBox lb = new CustomListBox();
lb.setWidth("100%");
Vector vals = (Vector) cell.getValue();
lb.setSuppressLayout(true);
for(Object label : vals){
lb.addItem(label.toString());
}
lb.setSuppressLayout(false);
lb.addChangeListener(new ChangeListener(){
public void onChange(Widget arg0) {
if(fColType.equalsIgnoreCase("editablecombobox")){
cell.setLabel(lb.getValue());
} else {
cell.setSelectedIndex(lb.getSelectedIndex());
}
}
});
int idx = cell.getSelectedIndex();
if(idx < 0){
idx = 0;
}
if(idx < vals.size()){
lb.setSelectedIndex(idx);
}
if(fColType.equalsIgnoreCase("editablecombobox")){
lb.setEditable(true);
}
lb.setValue(cell.getLabel());
return lb;
}
} else if (colType != null && customEditors.containsKey(colType)){
if(this.customRenderers.containsKey(colType)){
return new CustomCellEditorWrapper(cell, customEditors.get(colType), customRenderers.get(colType));
} else {
return new CustomCellEditorWrapper(cell, customEditors.get(colType));
}
} else {
if(val == null || val.equals("")){
return new HTML(" ");
}
return new HTML(val);
}
}
private int curSelectedRow = -1;
private void setupTable(){
List<XulComponent> colCollection = getColumns().getChildNodes();
String cols[] = new String[colCollection.size()];
SelectionPolicy selectionPolicy = null;
if ("single".equals(getSeltype())) {
selectionPolicy = SelectionPolicy.ONE_ROW;
} else if ("multiple".equals(getSeltype())) {
selectionPolicy = SelectionPolicy.MULTI_ROW;
}
int[] widths = new int[cols.length];
int totalFlex = 0;
for (int i = 0; i < cols.length; i++) {
totalFlex += colCollection.get(i).getFlex();
}
for (int i = 0; i < cols.length; i++) {
cols[i] = ((XulTreeCol) colCollection.get(i)).getLabel();
if(totalFlex > 0 && getWidth() > 0){
widths[i] = (int) (getWidth() * ((double) colCollection.get(i).getFlex() / totalFlex));
} else if(getColumns().getColumn(i).getWidth() > 0){
widths[i] = getColumns().getColumn(i).getWidth();
}
}
table = new BaseTable(cols, widths, new BaseColumnComparator[cols.length], selectionPolicy);
if (getHeight() != 0) {
table.setHeight(getHeight() + "px");
} else {
table.setHeight("100%");
}
if (getWidth() != 0) {
table.setWidth(getWidth() + "px");
} else {
table.setWidth("100%");
}
table.addTableSelectionListener(new TableSelectionListener() {
public void onAllRowsDeselected(SourceTableSelectionEvents sender) {
}
public void onCellHover(SourceTableSelectionEvents sender, int row, int cell) {
}
public void onCellUnhover(SourceTableSelectionEvents sender, int row, int cell) {
}
public void onRowDeselected(SourceTableSelectionEvents sender, int row) {
}
public void onRowHover(SourceTableSelectionEvents sender, int row) {
}
public void onRowUnhover(SourceTableSelectionEvents sender, int row) {
}
public void onRowsSelected(SourceTableSelectionEvents sender, int firstRow, int numRows) {
try {
if (getOnselect() != null && getOnselect().trim().length() > 0) {
getXulDomContainer().invoke(getOnselect(), new Object[]{});
}
Integer[] selectedRows = table.getSelectedRows().toArray(new Integer[table.getSelectedRows().size()]);
//set.toArray(new Integer[]) doesn't unwrap ><
int[] rows = new int[selectedRows.length];
for(int i=0; i<selectedRows.length; i++){
rows[i] = selectedRows[i];
}
GwtTree.this.setSelectedRows(rows);
GwtTree.this.colCollection = getColumns().getChildNodes();
if(GwtTree.this.isShowalleditcontrols() == false){
if(curSelectedRow > -1){
Object[] curSelectedRowOriginal = new Object[getColumns().getColumnCount()];
for (int j = 0; j < getColumns().getColumnCount(); j++) {
curSelectedRowOriginal[j] = getColumnEditor(j,curSelectedRow);
}
table.replaceRow(curSelectedRow, curSelectedRowOriginal);
}
curSelectedRow = rows[0];
Object[] newRow = new Object[getColumns().getColumnCount()];
for (int j = 0; j < getColumns().getColumnCount(); j++) {
newRow[j] = getColumnEditor(j,rows[0]);
}
table.replaceRow(rows[0], newRow);
}
} catch (XulException e) {
e.printStackTrace();
}
}
});
setWidgetInPanel(table);
updateUI();
}
public void updateUI() {
if(this.suppressLayout) {
return;
}
if(this.isHierarchical()){
populateTree();
for(Binding expBind : expandBindings){
try {
expBind.fireSourceChanged();
} catch (Exception e) {
e.printStackTrace();
}
}
// expandBindings.clear();
} else {
populateTable();
};
}
public void afterLayout() {
updateUI();
}
public void clearSelection() {
this.setSelectedRows(new int[]{});
}
public int[] getActiveCellCoordinates() {
// TODO Auto-generated method stub
return null;
}
public XulTreeCols getColumns() {
return columns;
}
public Object getData() {
// TODO Auto-generated method stub
return null;
}
@Bindable
public <T> Collection<T> getElements() {
return this.elements;
}
public String getOnedit() {
return getAttributeValue("onedit");
}
public String getOnselect() {
return getAttributeValue("onselect");
}
public XulTreeChildren getRootChildren() {
return rootChildren;
}
@Bindable
public int getRows() {
if (rootChildren == null) {
return 0;
} else {
return rootChildren.getItemCount();
}
}
@Bindable
public int[] getSelectedRows() {
if(this.isHierarchical()){
TreeItem item = tree.getSelectedItem();
for(int i=0; i <tree.getItemCount(); i++){
if(tree.getItem(i) == item){
return new int[]{i};
}
}
return new int[]{};
} else {
if (table == null) {
return new int[0];
}
Set<Integer> rows = table.getSelectedRows();
int rarr[] = new int[rows.size()];
int i = 0;
for (Integer v : rows) {
rarr[i++] = v;
}
return rarr;
}
}
public int[] getAbsoluteSelectedRows() {
return getSelectedRows();
}
private int[] selectedRows;
public void setSelectedRows(int[] rows) {
if (table == null || Arrays.equals(selectedRows, rows)) {
// this only works after the table has been materialized
return;
}
int[] prevSelected = selectedRows;
selectedRows = rows;
table.deselectRows();
for (int r : rows) {
if(this.rootChildren.getChildNodes().size() > r){
table.selectRow(r);
}
}
if(this.suppressEvents == false && Arrays.equals(selectedRows, prevSelected) == false){
this.changeSupport.firePropertyChange("selectedRows", prevSelected, rows);
this.changeSupport.firePropertyChange("absoluteSelectedRows", prevSelected, rows);
}
}
public String getSeltype() {
return getAttributeValue("seltype");
}
public Object[][] getValues() {
Object[][] data = new Object[getRootChildren().getChildNodes().size()][getColumns().getColumnCount()];
int y = 0;
for (XulComponent component : getRootChildren().getChildNodes()) {
XulTreeItem item = (XulTreeItem)component;
for (XulComponent childComp : item.getChildNodes()) {
XulTreeRow row = (XulTreeRow)childComp;
for (int x = 0; x < getColumns().getColumnCount(); x++) {
XulTreeCell cell = row.getCell(x);
switch (columns.getColumn(x).getColumnType()) {
case CHECKBOX:
Boolean flag = (Boolean) cell.getValue();
if (flag == null) {
flag = Boolean.FALSE;
}
data[y][x] = flag;
break;
case COMBOBOX:
Vector values = (Vector) cell.getValue();
int idx = cell.getSelectedIndex();
data[y][x] = values.get(idx);
break;
default: //label
data[y][x] = cell.getLabel();
break;
}
}
y++;
}
}
return data;
}
@Bindable
public boolean isEditable() {
return editable;
}
public boolean isEnableColumnDrag() {
return false;
}
public boolean isHierarchical() {
return isHierarchical;
}
public void removeTreeRows(int[] rows) {
// sort the rows high to low
ArrayList<Integer> rowArray = new ArrayList<Integer>();
for (int i = 0; i < rows.length; i++) {
rowArray.add(rows[i]);
}
Collections.sort(rowArray, Collections.reverseOrder());
// remove the items in that order
for (int i = 0; i < rowArray.size(); i++) {
int item = rowArray.get(i);
if (item >= 0 && item < rootChildren.getItemCount()) {
this.rootChildren.removeItem(item);
}
}
updateUI();
}
public void setActiveCellCoordinates(int row, int column) {
// TODO Auto-generated method stub
}
public void setColumns(XulTreeCols columns) {
if (getColumns() != null) {
this.removeChild(getColumns());
}
addChild(columns);
}
public void setData(Object data) {
// TODO Auto-generated method stub
}
@Bindable
public void setEditable(boolean edit) {
this.editable = edit;
}
@Bindable
public <T> void setElements(Collection<T> elements) {
try{
this.elements = elements;
suppressEvents = true;
prevSelectionPos = -1;
this.getRootChildren().removeAll();
for(Binding b : expandBindings){
b.destroyBindings();
}
this.expandBindings.clear();
for(TreeItemDropController d : this.dropHandlers){
XulDragController.getInstance().unregisterDropController(d);
}
dropHandlers.clear();
if(elements == null || elements.size() == 0){
suppressEvents = false;
updateUI();
return;
}
try {
if(table != null){
for (T o : elements) {
XulTreeRow row = this.getRootChildren().addNewRow();
int colSize = this.getColumns().getChildNodes().size();
for (int x=0; x< colSize; x++) {
XulComponent col = this.getColumns().getColumn(x);
XulTreeCol column = ((XulTreeCol) col);
final XulTreeCell cell = (XulTreeCell) getDocument().createElement("treecell");
addBindings(column, (GwtTreeCell) cell, o);
row.addCell(cell);
}
}
} else { //tree
for (T o : elements) {
XulTreeRow row = this.getRootChildren().addNewRow();
((XulTreeItem) row.getParent()).setBoundObject(o);
addTreeChild(o, row);
}
}
//treat as a selection change
} catch (XulException e) {
Window.alert("error adding elements "+e);
System.out.println(e.getMessage());
e.printStackTrace();
} catch (Exception e) {
Window.alert("error adding elements "+e);
System.out.println(e.getMessage());
e.printStackTrace();
}
suppressEvents = false;
this.clearSelection();
updateUI();
} catch(Exception e){
System.out.println(e.getMessage());
e.printStackTrace();
}
}
private <T> void addTreeChild(T element, XulTreeRow row){
try{
GwtTreeCell cell = (GwtTreeCell) getDocument().createElement("treecell");
for (InlineBindingExpression exp : ((XulTreeCol) this.getColumns().getChildNodes().get(0)).getBindingExpressions()) {
Binding binding = createBinding((XulEventSource) element, exp.getModelAttr(), cell, exp.getXulCompAttr());
binding.setBindingType(Binding.Type.ONE_WAY);
domContainer.addBinding(binding);
binding.fireSourceChanged();
}
XulTreeCol column = (XulTreeCol) this.getColumns().getChildNodes().get(0);
String expBind = column.getExpandedbinding();
if(expBind != null){
Binding binding = createBinding((XulEventSource) element, expBind, row.getParent(), "expanded");
elementBindings.add(binding);
binding.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(binding);
expandBindings.add(binding);
}
String imgBind = column.getImagebinding();
if(imgBind != null){
Binding binding = createBinding((XulEventSource) element, imgBind, row.getParent(), "image");
elementBindings.add(binding);
binding.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(binding);
binding.fireSourceChanged();
}
row.addCell(cell);
//find children
String property = ((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding();
GwtBindingMethod childrenMethod = GwtBindingContext.typeController.findGetMethod(element, property);
Collection<T> children = null;
if(childrenMethod != null){
children = (Collection<T>) childrenMethod.invoke(element, new Object[] {});
} else if(element instanceof Collection ){
children = (Collection<T>) element;
}
XulTreeChildren treeChildren = null;
if(children != null && children.size() > 0){
treeChildren = (XulTreeChildren) getDocument().createElement("treechildren");
row.getParent().addChild(treeChildren);
}
if (children == null) {
return;
}
for(T child : children){
row = treeChildren.addNewRow();
((XulTreeItem) row.getParent()).setBoundObject(child);
addTreeChild(child, row);
}
} catch (Exception e) {
Window.alert("error adding elements "+e.getMessage());
e.printStackTrace();
}
}
public void setEnableColumnDrag(boolean drag) {
// TODO Auto-generated method stub
}
public void setOnedit(String onedit) {
this.setAttribute("onedit", onedit);
}
public void setOnselect(String select) {
this.setAttribute("onselect", select);
}
public void setRootChildren(XulTreeChildren rootChildren) {
if (getRootChildren() != null) {
this.removeChild(getRootChildren());
}
addChild(rootChildren);
}
public void setRows(int rows) {
// TODO Auto-generated method stub
}
public void setSeltype(String type) {
// TODO Auto-generated method stub
// SINGLE, CELL, MULTIPLE, NONE
this.setAttribute("seltype", type);
}
public void update() {
layout();
}
public void adoptAttributes(XulComponent component) {
super.adoptAttributes(component);
layout();
}
public void registerCellEditor(String key, TreeCellEditor editor){
customEditors.put(key, editor);
}
public void registerCellRenderer(String key, TreeCellRenderer renderer) {
customRenderers.put(key, renderer);
}
private void addBindings(final XulTreeCol col, final GwtTreeCell cell, final Object o) throws InvocationTargetException, XulException{
for (InlineBindingExpression exp : col.getBindingExpressions()) {
String colType = col.getType();
if(StringUtils.isEmpty(colType) == false && colType.equalsIgnoreCase("dynamic")){
colType = extractDynamicColType(o, col.getParent().getChildNodes().indexOf(col));
}
if(colType != null && (colType.equalsIgnoreCase("combobox") || colType.equalsIgnoreCase("editablecombobox"))){
// Only add bindings if they haven't been already applied.
if(cell.valueBindingsAdded() == false){
Binding binding = createBinding((XulEventSource) o, col.getCombobinding(), cell, "value");
binding.setBindingType(Binding.Type.ONE_WAY);
domContainer.addBinding(binding);
binding.fireSourceChanged();
cell.setValueBindingsAdded(true);
}
if(cell.selectedIndexBindingsAdded() == false){
Binding binding = createBinding((XulEventSource) o, ((XulTreeCol) col).getBinding(), cell, "selectedIndex");
binding.setBindingType(Binding.Type.BI_DIRECTIONAL);
binding.setConversion(new BindingConvertor<Object, Integer>(){
@Override
public Integer sourceToTarget(Object value) {
int index = ((Vector) cell.getValue()).indexOf(value);
return index > -1 ? index : 0;
}
@Override
public Object targetToSource(Integer value) {
return ((Vector)cell.getValue()).get(value);
}
});
domContainer.addBinding(binding);
binding.fireSourceChanged();
cell.setSelectedIndexBindingsAdded(true);
}
if(cell.labelBindingsAdded() == false && colType.equalsIgnoreCase("editablecombobox")){
Binding binding = createBinding((XulEventSource) o, exp.getModelAttr(), cell, "label");
binding.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(binding);
binding.fireSourceChanged();
cell.setLabelBindingsAdded(true);
}
} else if(colType != null && this.customEditors.containsKey(colType)){
Binding binding = createBinding((XulEventSource) o, exp.getModelAttr(), cell, "value");
binding.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(binding);
binding.fireSourceChanged();
cell.setValueBindingsAdded(true);
} else if(colType != null && colType.equalsIgnoreCase("checkbox")) {
Binding binding = createBinding((XulEventSource) o, exp.getModelAttr(), cell, "value");
if(col.isEditable() == false){
binding.setBindingType(Binding.Type.ONE_WAY);
} else {
binding.setBindingType(Binding.Type.BI_DIRECTIONAL);
}
domContainer.addBinding(binding);
binding.fireSourceChanged();
cell.setValueBindingsAdded(true);
} else if(o instanceof XulEventSource && StringUtils.isEmpty(exp.getModelAttr()) == false){
Binding binding = createBinding((XulEventSource) o, exp.getModelAttr(), cell, exp.getXulCompAttr());
if(col.isEditable() == false){
binding.setBindingType(Binding.Type.ONE_WAY);
} else {
binding.setBindingType(Binding.Type.BI_DIRECTIONAL);
}
domContainer.addBinding(binding);
binding.fireSourceChanged();
cell.setLabelBindingsAdded(true);
} else {
cell.setLabel(o.toString());
}
}
if(StringUtils.isEmpty(col.getDisabledbinding()) == false){
String prop = col.getDisabledbinding();
Binding bind = createBinding((XulEventSource) o, col.getDisabledbinding(), cell, "disabled");
bind.setBindingType(Binding.Type.ONE_WAY);
// the default string to string was causing issues, this is really a boolean to boolean, no conversion necessary
bind.setConversion(null);
domContainer.addBinding(bind);
bind.fireSourceChanged();
}
}
@Deprecated
public void onResize() {
// if(table != null){
// table.onResize();
// }
}
public class CustomCellEditorWrapper extends SimplePanel implements TreeCellEditorCallback{
private TreeCellEditor editor;
private TreeCellRenderer renderer;
private Label label = new Label();
private XulTreeCell cell;
public CustomCellEditorWrapper(XulTreeCell cell, TreeCellEditor editor){
super();
this.sinkEvents(Event.MOUSEEVENTS);
this.editor = editor;
this.cell = cell;
HorizontalPanel hPanel = new HorizontalPanel();
hPanel.setStylePrimaryName("slimTable");
SimplePanel labelWrapper = new SimplePanel();
labelWrapper.getElement().getStyle().setProperty("overflow", "hidden");
labelWrapper.setWidth("100%");
labelWrapper.add(label);
hPanel.add(labelWrapper);
hPanel.setCellWidth(labelWrapper, "100%");
ImageButton btn = new ImageButton(GWT.getModuleBaseURL() + "/images/open_new.png", GWT.getModuleBaseURL() + "/images/open_new.png", "", 29, 24);
btn.getElement().getStyle().setProperty("margin", "0px");
hPanel.add(btn);
hPanel.setSpacing(0);
hPanel.setBorderWidth(0);
hPanel.setWidth("100%");
labelWrapper.getElement().getParentElement().getStyle().setProperty("padding", "0px");
labelWrapper.getElement().getParentElement().getStyle().setProperty("border", "0px");
btn.getElement().getParentElement().getStyle().setProperty("padding", "0px");
btn.getElement().getParentElement().getStyle().setProperty("border", "0px");
this.add( hPanel );
if(cell.getValue() != null) {
this.label.setText((cell.getValue() != null) ? cell.getValue().toString() : " ");
}
}
public CustomCellEditorWrapper(XulTreeCell cell, TreeCellEditor editor, TreeCellRenderer renderer){
this(cell, editor);
this.renderer = renderer;
if(this.renderer.supportsNativeComponent()){
this.clear();
this.add((Widget) this.renderer.getNativeComponent());
} else {
this.label.setText((this.renderer.getText(cell.getValue()) != null) ? this.renderer.getText(cell.getValue()) : " ");
}
}
public void onCellEditorClosed(Object value) {
cell.setValue(value);
if(this.renderer == null){
this.label.setText(value.toString());
} else if(this.renderer.supportsNativeComponent()){
this.clear();
this.add((Widget) this.renderer.getNativeComponent());
} else {
this.label.setText((this.renderer.getText(cell.getValue()) != null) ? this.renderer.getText(cell.getValue()) : " ");
}
}
@Override
public void onBrowserEvent(Event event) {
int code = event.getTypeInt();
switch(code){
case Event.ONMOUSEUP:
editor.setValue(cell.getValue());
int col = cell.getParent().getChildNodes().indexOf(cell);
XulTreeItem item = (XulTreeItem) cell.getParent().getParent();
int row = item.getParent().getChildNodes().indexOf(item);
Object boundObj = (GwtTree.this.getElements() != null) ? GwtTree.this.getElements().toArray()[row] : null;
String columnBinding = GwtTree.this.getColumns().getColumn(col).getBinding();
editor.show(row, col, boundObj, columnBinding, this);
default:
break;
}
super.onBrowserEvent(event);
}
}
public void setBoundObjectExpanded(Object o, boolean expanded) {
throw new UnsupportedOperationException("not implemented");
}
public void setTreeItemExpanded(XulTreeItem item, boolean expanded) {
((TreeItem) item.getManagedObject()).setState(expanded);
}
public void collapseAll() {
if (this.isHierarchical()){
for (XulComponent c : this.rootChildren.getChildNodes()){
XulTreeItem item = (XulTreeItem) c;
item.setExpanded(false);
expandChildren(item, false);
}
}
}
public void expandAll() {
if (this.isHierarchical()){
for (XulComponent c : this.rootChildren.getChildNodes()){
XulTreeItem item = (XulTreeItem) c;
item.setExpanded(true);
expandChildren(item, true);
}
}
}
private void expandChildren(XulTreeItem parent, boolean expanded) {
if (parent == null || parent.getChildNodes() == null || parent.getChildNodes().size() == 0) {
return;
}
for (XulComponent c : parent.getChildNodes()) {
if (c instanceof XulTreeChildren) {
XulTreeChildren treeChildren = (XulTreeChildren)c;
for (XulComponent child : treeChildren.getChildNodes()) {
if (child instanceof XulTreeItem) {
XulTreeItem item = (XulTreeItem) child;
item.setExpanded(expanded);
expandChildren(item, expanded);
}
}
}
}
}
@Bindable
public <T> Collection<T> getSelectedItems() {
// TODO Auto-generated method stub
return null;
}
@Bindable
public <T> void setSelectedItems(Collection<T> items) {
// TODO Auto-generated method stub
}
public boolean isHiddenrootnode() {
// TODO Auto-generated method stub
return false;
}
public void setHiddenrootnode(boolean hidden) {
// TODO Auto-generated method stub
}
public String getCommand() {
return command;
}
public void setCommand(String command) {
this.command = command;
}
public boolean isPreserveexpandedstate() {
return false;
}
public void setPreserveexpandedstate(boolean preserve) {
}
public boolean isSortable() {
// TODO Auto-generated method stub
return false;
}
public void setSortable(boolean sort) {
// TODO Auto-generated method stub
}
public boolean isTreeLines() {
// TODO Auto-generated method stub
return false;
}
public void setTreeLines(boolean visible) {
// TODO Auto-generated method stub
}
public void setNewitembinding(String binding){
}
public String getNewitembinding(){
return null;
}
public void setAutocreatenewrows(boolean auto){
}
public boolean getAutocreatenewrows(){
return false;
}
public boolean isPreserveselection() {
// TODO This method is not fully implemented. We need to completely implement this in this class
return false;
}
public void setPreserveselection(boolean preserve) {
// TODO This method is not fully implemented. We need to completely implement this in this class
}
private void fireSelectedItems( ) {
Object selected = getSelectedItem();
this.changeSupport.firePropertyChange("selectedItem", null, selected);
}
@Bindable
public Object getSelectedItem() {
if (this.isHierarchical && this.elements != null) {
int pos = -1;
int curPos = 0;
for(int i=0; i < tree.getItemCount(); i++){
TreeItem tItem = tree.getItem(i);
TreeCursor cursor = GwtTree.this.findPosition(tItem, tree.getSelectedItem(), curPos);
pos = cursor.foundPosition;
curPos = cursor.curPos+1;
if(pos > -1){
break;
}
}
int[] vals = new int[]{pos};
String property = ((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding();
FindSelectedItemTuple tuple = findSelectedItem(this.elements, property, new FindSelectedItemTuple(vals[0]));
return tuple != null ? tuple.selectedItem : null;
}
return null;
}
private static class FindSelectedItemTuple {
Object selectedItem = null;
int curpos = -1; // ignores first element (root)
int selectedIndex;
public FindSelectedItemTuple(int selectedIndex) {
this.selectedIndex = selectedIndex;
}
}
private FindSelectedItemTuple findSelectedItem(Object parent, String childrenMethodProperty,
FindSelectedItemTuple tuple) {
if (tuple.curpos == tuple.selectedIndex) {
tuple.selectedItem = parent;
return tuple;
}
Collection children = getChildCollection(parent, childrenMethodProperty);
if (children == null || children.size() == 0) {
return null;
}
for (Object child : children) {
tuple.curpos++;
findSelectedItem(child, childrenMethodProperty, tuple);
if (tuple.selectedItem != null) {
return tuple;
}
}
return null;
}
private static Collection getChildCollection(Object obj, String childrenMethodProperty) {
Collection children = null;
GwtBindingMethod childrenMethod = GwtBindingContext.typeController.findGetMethod(obj, childrenMethodProperty);
try {
if (childrenMethod != null) {
children = (Collection) childrenMethod.invoke(obj, new Object[] {});
} else if(obj instanceof Collection ){
children = (Collection) obj;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return children;
}
public boolean isShowalleditcontrols() {
return showAllEditControls;
}
public void setShowalleditcontrols(boolean showAllEditControls) {
this.showAllEditControls = showAllEditControls;
}
@Override
public void setOndrag(String ondrag) {
super.setOndrag(ondrag);
}
@Override
public void setOndrop(String ondrop) {
super.setOndrop(ondrop);
}
@Override
public void setDropvetoer(String dropVetoMethod) {
if(StringUtils.isEmpty(dropVetoMethod)){
return;
}
super.setDropvetoer(dropVetoMethod);
}
private void resolveDropVetoerMethod(){
if(dropVetoerMethod == null && !StringUtils.isEmpty(getDropvetoer())){
String id = getDropvetoer().substring(0, getDropvetoer().indexOf("."));
try {
XulEventHandler controller = getXulDomContainer().getEventHandler(id);
this.dropVetoerMethod = GwtBindingContext.typeController.findMethod(controller, getDropvetoer().substring(getDropvetoer().indexOf(".")+1, getDropvetoer().indexOf("(")));
this.dropVetoerController = controller;
} catch (XulException e) {
e.printStackTrace();
}
}
}
private class TreeItemDropController extends AbstractPositioningDropController {
private XulTreeItem xulItem;
private TreeItemWidget item;
private DropPosition curPos;
private long lasPositionPoll = 0;
public TreeItemDropController(XulTreeItem xulItem, TreeItemWidget item){
super(item);
this.xulItem = xulItem;
this.item = item;
}
@Override
public void onEnter(DragContext context) {
super.onEnter(context);
resolveDropVetoerMethod();
if(dropVetoerMethod != null){
Object objToMove = ((XulDragController) context.dragController).getDragObject();
DropEvent event = new DropEvent();
DataTransfer dataTransfer = new DataTransfer();
dataTransfer.setData(Collections.singletonList(objToMove));
event.setDataTransfer(dataTransfer);
event.setAccepted(true);
event.setDropPosition(curPos);
if(curPos == DropPosition.MIDDLE){
event.setDropParent(xulItem.getBoundObject());
} else {
XulComponent parent = xulItem.getParent().getParent();
Object parentObj;
if(parent instanceof GwtTree){
parentObj = GwtTree.this.elements;
} else {
parentObj = ((XulTreeItem) parent).getBoundObject();
}
event.setDropParent(parentObj);
}
try {
// Consult Vetoer method to see if this is a valid drop operation
dropVetoerMethod.invoke(dropVetoerController, new Object[]{event});
//Check to see if this drop candidate should be rejected.
if(event.isAccepted() == false){
return;
}
} catch (XulException e) {
e.printStackTrace();
}
}
((Draggable) XulDragController.getInstance().getProxy()).setDropValid(true);
}
@Override
public void onLeave(DragContext context) {
super.onLeave(context);
item.getElement().getStyle().setProperty("border", "");
item.highLightDrop(false);
dropPosIndicator.setVisible(false);
Widget proxy = XulDragController.getInstance().getProxy();
if(proxy != null){
((Draggable) proxy).setDropValid(false);
}
}
@Override
public void onMove(DragContext context) {
super.onMove(context);
int scrollPanelX = 0;
int scrollPanelY = 0;
int scrollPanelScrollTop = 0;
int scrollPanelScrollLeft = 0;
if(System.currentTimeMillis() > lasPositionPoll+3000){
scrollPanelX = scrollPanel.getElement().getAbsoluteLeft();
scrollPanelScrollLeft = scrollPanel.getElement().getScrollLeft();
scrollPanelY = scrollPanel.getElement().getAbsoluteTop();
scrollPanelScrollTop = scrollPanel.getElement().getScrollTop();
}
int x = item.getAbsoluteLeft();
int y = item.getAbsoluteTop();
int height = item.getOffsetHeight();
int middleGround = height/4;
if(context.mouseY < (y+height/2)-middleGround){
curPos = DropPosition.ABOVE;
} else if(context.mouseY > (y+height/2)+middleGround){
curPos = DropPosition.BELOW;
} else {
curPos = DropPosition.MIDDLE;
}
resolveDropVetoerMethod();
if(dropVetoerMethod != null){
Object objToMove = ((XulDragController) context.dragController).getDragObject();
DropEvent event = new DropEvent();
DataTransfer dataTransfer = new DataTransfer();
dataTransfer.setData(Collections.singletonList(objToMove));
event.setDataTransfer(dataTransfer);
event.setAccepted(true);
event.setDropPosition(curPos);
if(curPos == DropPosition.MIDDLE){
event.setDropParent(xulItem.getBoundObject());
} else {
XulComponent parent = xulItem.getParent().getParent();
Object parentObj;
if(parent instanceof GwtTree){
parentObj = GwtTree.this.elements;
} else {
parentObj = ((XulTreeItem) parent).getBoundObject();
}
event.setDropParent(parentObj);
}
try {
// Consult Vetoer method to see if this is a valid drop operation
dropVetoerMethod.invoke(dropVetoerController, new Object[]{event});
//Check to see if this drop candidate should be rejected.
if(event.isAccepted() == false){
((Draggable) XulDragController.getInstance().getProxy()).setDropValid(false);
dropPosIndicator.setVisible(false);
return;
}
} catch (XulException e) {
e.printStackTrace();
}
}
((Draggable) XulDragController.getInstance().getProxy()).setDropValid(true);
switch (curPos) {
case ABOVE:
item.highLightDrop(false);
int posX = item.getElement().getAbsoluteLeft()
- scrollPanelX
+ scrollPanelScrollLeft;
int posY = item.getElement().getAbsoluteTop()
- scrollPanelY
+ scrollPanelScrollTop
-4;
dropPosIndicator.setPosition(posX, posY, item.getOffsetWidth());
break;
case MIDDLE:
item.highLightDrop(true);
dropPosIndicator.setVisible(false);
break;
case BELOW:
item.highLightDrop(false);
posX = item.getElement().getAbsoluteLeft()
- scrollPanelX
+ scrollPanelScrollLeft;
posY = item.getElement().getAbsoluteTop()
+ item.getElement().getOffsetHeight()
- scrollPanelY
+ scrollPanelScrollTop
-4;
dropPosIndicator.setPosition(posX, posY, item.getOffsetWidth());
break;
}
}
@Override
public void onPreviewDrop(DragContext context) throws VetoDragException {
int i=0;
}
@Override
public void onDrop(DragContext context) {
super.onDrop(context);
Object objToMove = ((XulDragController) context.dragController).getDragObject();
DropEvent event = new DropEvent();
DataTransfer dataTransfer = new DataTransfer();
dataTransfer.setData(Collections.singletonList(objToMove));
event.setDataTransfer(dataTransfer);
event.setAccepted(true);
if(curPos == DropPosition.MIDDLE){
event.setDropParent(xulItem.getBoundObject());
} else {
XulComponent parent = xulItem.getParent().getParent();
Object parentObj;
if(parent instanceof GwtTree){
parentObj = GwtTree.this.elements;
} else {
parentObj = ((XulTreeItem) parent).getBoundObject();
}
event.setDropParent(parentObj);
}
//event.setDropIndex(index);
final String method = getOndrop();
if (method != null) {
try{
Document doc = getDocument();
XulRoot window = (XulRoot) doc.getRootElement();
final XulDomContainer con = window.getXulDomContainer();
con.invoke(method, new Object[]{event});
} catch (XulException e){
e.printStackTrace();
System.out.println("Error calling ondrop event: "+ method); //$NON-NLS-1$
}
}
if (!event.isAccepted()) {
return;
}
// ==============
((Draggable) context.draggable).notifyDragFinished();
if(curPos == DropPosition.MIDDLE){
String property = ((XulTreeCol) GwtTree.this.getColumns().getChildNodes().get(0)).getChildrenbinding();
GwtBindingMethod childrenMethod = GwtBindingContext.typeController.findGetMethod(xulItem.getBoundObject(), property);
Collection children = null;
try {
if(childrenMethod != null){
children = (Collection) childrenMethod.invoke(xulItem.getBoundObject(), new Object[] {});
} else if(xulItem.getBoundObject() instanceof Collection ){
children = (Collection) xulItem.getBoundObject();
}
for(Object o : event.getDataTransfer().getData()){
children.add(o);
}
} catch (XulException e) {
e.printStackTrace();
}
} else {
XulComponent parent = xulItem.getParent().getParent();
List parentList;
if(parent instanceof GwtTree){
parentList = (List) GwtTree.this.elements;
} else {
parentList = (List) ((XulTreeItem) parent).getBoundObject();
}
int idx = parentList.indexOf(xulItem.getBoundObject());
if (curPos == DropPosition.BELOW){
idx++;
}
for(Object o : event.getDataTransfer().getData()){
parentList.add(idx, o);
}
}
}
}
public void notifyDragFinished(XulTreeItem xulItem){
if(this.drageffect.equalsIgnoreCase("copy")){
return;
}
XulComponent parent = xulItem.getParent().getParent();
List parentList;
if(parent instanceof GwtTree){
parentList = (List) GwtTree.this.elements;
} else {
parentList = (List) ((XulTreeItem) parent).getBoundObject();
}
parentList.remove(xulItem.getBoundObject());
}
private class DropPositionIndicator extends SimplePanel{
public DropPositionIndicator(){
setStylePrimaryName("tree-drop-indicator-symbol");
SimplePanel line = new SimplePanel();
line.setStylePrimaryName("tree-drop-indicator");
add(line);
setVisible(false);
}
public void setPosition(int scrollLeft, int scrollTop, int offsetWidth) {
this.setVisible(true);
setWidth(offsetWidth+"px");
getElement().getStyle().setProperty("top", scrollTop+"px");
getElement().getStyle().setProperty("left", (scrollLeft -4)+"px");
}
}
}
| pentaho-xul-gwt/src/org/pentaho/ui/xul/gwt/tags/GwtTree.java | package org.pentaho.ui.xul.gwt.tags;
import com.allen_sauer.gwt.dnd.client.DragContext;
import com.allen_sauer.gwt.dnd.client.VetoDragException;
import com.allen_sauer.gwt.dnd.client.drop.AbstractPositioningDropController;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.widgetideas.table.client.SelectionGrid.SelectionPolicy;
import com.google.gwt.widgetideas.table.client.SourceTableSelectionEvents;
import com.google.gwt.widgetideas.table.client.TableSelectionListener;
import org.pentaho.gwt.widgets.client.buttons.ImageButton;
import org.pentaho.gwt.widgets.client.listbox.CustomListBox;
import org.pentaho.gwt.widgets.client.table.BaseTable;
import org.pentaho.gwt.widgets.client.table.ColumnComparators.BaseColumnComparator;
import org.pentaho.gwt.widgets.client.ui.Draggable;
import org.pentaho.gwt.widgets.client.utils.string.StringUtils;
import org.pentaho.ui.xul.XulComponent;
import org.pentaho.ui.xul.XulDomContainer;
import org.pentaho.ui.xul.XulEventSource;
import org.pentaho.ui.xul.XulException;
import org.pentaho.ui.xul.binding.Binding;
import org.pentaho.ui.xul.binding.BindingConvertor;
import org.pentaho.ui.xul.binding.InlineBindingExpression;
import org.pentaho.ui.xul.components.XulTreeCell;
import org.pentaho.ui.xul.components.XulTreeCol;
import org.pentaho.ui.xul.containers.*;
import org.pentaho.ui.xul.dnd.DataTransfer;
import org.pentaho.ui.xul.dnd.DropEvent;
import org.pentaho.ui.xul.dnd.DropPosition;
import org.pentaho.ui.xul.dom.Document;
import org.pentaho.ui.xul.dom.Element;
import org.pentaho.ui.xul.gwt.AbstractGwtXulContainer;
import org.pentaho.ui.xul.gwt.GwtXulHandler;
import org.pentaho.ui.xul.gwt.GwtXulParser;
import org.pentaho.ui.xul.gwt.binding.GwtBinding;
import org.pentaho.ui.xul.gwt.binding.GwtBindingContext;
import org.pentaho.ui.xul.gwt.binding.GwtBindingMethod;
import org.pentaho.ui.xul.gwt.tags.util.TreeItemWidget;
import org.pentaho.ui.xul.gwt.util.Resizable;
import org.pentaho.ui.xul.gwt.util.XulDragController;
import org.pentaho.ui.xul.impl.XulEventHandler;
import org.pentaho.ui.xul.stereotype.Bindable;
import org.pentaho.ui.xul.util.TreeCellEditor;
import org.pentaho.ui.xul.util.TreeCellEditorCallback;
import org.pentaho.ui.xul.util.TreeCellRenderer;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
public class GwtTree extends AbstractGwtXulContainer implements XulTree, Resizable {
/**
* Cached elements.
*/
private Collection elements;
private GwtBindingMethod dropVetoerMethod;
private XulEventHandler dropVetoerController;
public static void register() {
GwtXulParser.registerHandler("tree",
new GwtXulHandler() {
public Element newInstance() {
return new GwtTree();
}
});
}
XulTreeCols columns = null;
XulTreeChildren rootChildren = null;
private XulDomContainer domContainer;
private Tree tree;
private boolean suppressEvents = false;
private boolean editable = false;
private boolean visible = true;
private String command;
private Map<String, TreeCellEditor> customEditors = new HashMap<String, TreeCellEditor>();
private Map<String, TreeCellRenderer> customRenderers = new HashMap<String, TreeCellRenderer>();
private List<Binding> elementBindings = new ArrayList<Binding>();
private List<Binding> expandBindings = new ArrayList<Binding>();
private DropPositionIndicator dropPosIndicator = new DropPositionIndicator();
private boolean showAllEditControls = true;
@Bindable
public boolean isVisible() {
return visible;
}
@Bindable
public void setVisible(boolean visible) {
this.visible = visible;
if(simplePanel != null) {
simplePanel.setVisible(visible);
}
}
/**
* Used when this widget is a tree. Not used when this widget is a table.
*/
private FlowPanel scrollPanel = new FlowPanel();
{
scrollPanel.setStylePrimaryName("scroll-panel");
}
/**
* The managed object. If this widget is a tree, then the tree is added to the scrollPanel, which is added to this
* simplePanel. If this widget is a table, then the table is added directly to this simplePanel.
*/
private SimplePanel simplePanel = new SimplePanel();
/**
* Clears the parent panel and adds the given widget.
* @param widget tree or table to set in parent panel
*/
protected void setWidgetInPanel(final Widget widget) {
if (isHierarchical()) {
scrollPanel.clear();
simplePanel.add(scrollPanel);
scrollPanel.add(widget);
scrollPanel.add(dropPosIndicator);
} else {
simplePanel.clear();
simplePanel.add(widget);
}
}
public GwtTree() {
super("tree");
// managedObject is neither a native GWT tree nor a table since the entire native GWT object is thrown away each
// time we call setup{Tree|Table}; because the widget is thrown away, we need to reconnect the new widget to the
// simplePanel, which is the managedObject
setManagedObject(simplePanel);
}
public void init(com.google.gwt.xml.client.Element srcEle, XulDomContainer container) {
super.init(srcEle, container);
setOnselect(srcEle.getAttribute("onselect"));
setOnedit(srcEle.getAttribute("onedit"));
setSeltype(srcEle.getAttribute("seltype"));
if (StringUtils.isEmpty(srcEle.getAttribute("pen:ondrop")) == false) {
setOndrop(srcEle.getAttribute("pen:ondrop"));
}
if (StringUtils.isEmpty(srcEle.getAttribute("pen:ondrag")) == false) {
setOndrag(srcEle.getAttribute("pen:ondrag"));
}
if (StringUtils.isEmpty(srcEle.getAttribute("pen:drageffect")) == false) {
setDrageffect(srcEle.getAttribute("pen:drageffect"));
}
setDropvetoer(srcEle.getAttribute("pen:dropvetoer"));
if(StringUtils.isEmpty(srcEle.getAttribute("pen:showalleditcontrols")) == false){
this.setShowalleditcontrols(srcEle.getAttribute("pen:showalleditcontrols").equals("true"));
}
this.setEditable("true".equals(srcEle.getAttribute("editable")));
this.domContainer = container;
}
private List<TreeItemDropController> dropHandlers = new ArrayList<TreeItemDropController>();
public void addChild(Element element) {
super.addChild(element);
if (element.getName().equals("treecols")) {
columns = (XulTreeCols)element;
} else if (element.getName().equals("treechildren")) {
rootChildren = (XulTreeChildren)element;
}
}
public void addTreeRow(XulTreeRow row) {
GwtTreeItem item = new GwtTreeItem();
item.setRow(row);
this.rootChildren.addItem(item);
// update UI
updateUI();
}
private BaseTable table;
private boolean isHierarchical = false;
private boolean firstLayout = true;
private Object[][] currentData;
// need to handle layouting
public void layout() {
if(this.getRootChildren() == null){
//most likely an overlay
return;
}
if(firstLayout){
XulTreeItem item = (XulTreeItem) this.getRootChildren().getFirstChild();
if(item != null && item.getAttributeValue("container") != null && item.getAttributeValue("container").equals("true")){
isHierarchical = true;
}
firstLayout = false;
}
if(isHierarchical()){
setupTree();
} else {
setupTable();
}
setVisible(visible);
}
private int prevSelectionPos = -1;
private void setupTree(){
if(tree == null){
tree = new Tree();
setWidgetInPanel(tree);
}
scrollPanel.setWidth("100%"); //$NON-NLS-1$
scrollPanel.setHeight("100%"); //$NON-NLS-1$
scrollPanel.getElement().getStyle().setProperty("backgroundColor", "white"); //$NON-NLS-1$//$NON-NLS-2$
if (getWidth() > 0){
scrollPanel.setWidth(getWidth()+"px"); //$NON-NLS-1$
}
if (getHeight() > 0) {
scrollPanel.setHeight(getHeight()+"px"); //$NON-NLS-1$
}
tree.addTreeListener(new TreeListener(){
public void onTreeItemSelected(TreeItem arg0) {
int pos = -1;
int curPos = 0;
for(int i=0; i < tree.getItemCount(); i++){
TreeItem tItem = tree.getItem(i);
TreeCursor cursor = GwtTree.this.findPosition(tItem, arg0, curPos);
pos = cursor.foundPosition;
curPos = cursor.curPos+1;
if(pos > -1){
break;
}
}
if(pos > -1 && GwtTree.this.suppressEvents == false && prevSelectionPos != pos){
GwtTree.this.changeSupport.firePropertyChange("selectedRows",null,new int[]{pos});
GwtTree.this.changeSupport.firePropertyChange("absoluteSelectedRows",null,new int[]{pos});
GwtTree.this.fireSelectedItems();
}
prevSelectionPos = pos;
}
public void onTreeItemStateChanged(TreeItem item) {
((TreeItemWidget) item.getWidget()).getTreeItem().setExpanded(item.getState());
}
});
updateUI();
}
private class TreeCursor{
int foundPosition = -1;
int curPos;
TreeItem itemToFind;
public TreeCursor(int curPos, TreeItem itemToFind, int foundPosition){
this.foundPosition = foundPosition;
this.curPos = curPos;
this.itemToFind = itemToFind;
}
}
private TreeCursor findPosition(TreeItem curItem, TreeItem itemToFind, int curPos){
if(curItem == itemToFind){
TreeCursor p = new TreeCursor(curPos, itemToFind, curPos);
return p;
// } else if(curItem.getChildIndex(itemToFind) > -1) {
// curPos = curPos+1;
// return new TreeCursor(curPos+curItem.getChildIndex(itemToFind) , itemToFind, curPos+curItem.getChildIndex(itemToFind));
} else {
for(int i=1; i-1<curItem.getChildCount(); i++){
TreeCursor p = findPosition(curItem.getChild(i-1), itemToFind, curPos +1);
curPos = p.curPos;
if(p.foundPosition > -1){
return p;
}
}
//curPos += curItem.getChildCount() ;
return new TreeCursor(curPos, itemToFind, -1);
}
}
private void populateTree(){
tree.removeItems();
TreeItem topNode = new TreeItem("placeholder");
if(this.rootChildren == null){
this.rootChildren = (XulTreeChildren) this.children.get(1);
}
for (XulComponent c : this.rootChildren.getChildNodes()){
XulTreeItem item = (XulTreeItem) c;
TreeItem node = createNode(item);
tree.addItem(node);
}
if(StringUtils.isEmpty(this.ondrag) == false){
for (int i = 0; i < tree.getItemCount(); i++) {
madeDraggable(tree.getItem(i));
}
}
}
private void madeDraggable(TreeItem item){
XulDragController.getInstance().makeDraggable(item.getWidget());
for (int i = 0; i < item.getChildCount(); i++) {
madeDraggable(item.getChild(i));
}
}
private List<XulComponent> colCollection = new ArrayList<XulComponent>();
private void populateTable(){
int rowCount = getRootChildren().getItemCount();
// Getting column editors ends up calling getChildNodes several times. we're going to cache the column collections
// for the duration of the operation then clear it out.
colCollection = getColumns().getChildNodes();
int colCount = colCollection.size();
currentData = new Object[rowCount][colCount];
for (int i = 0; i < rowCount; i++) {
for (int j = 0; j < colCount; j++) {
currentData[i][j] = getColumnEditor(j,i);
}
}
table.populateTable(currentData);
int totalFlex = 0;
for (int i = 0; i < colCount; i++) {
totalFlex += colCollection.get(i).getFlex();
}
if(totalFlex > 0){
table.fillWidth();
}
colCollection = new ArrayList<XulComponent>();
if(this.selectedRows != null && this.selectedRows.length > 0){
for(int i=0; i<this.selectedRows.length; i++){
int idx = this.selectedRows[i];
if(idx > -1 && idx < currentData.length){
table.selectRow(idx);
}
}
}
}
private TreeItem createNode(final XulTreeItem item){
TreeItem node = new TreeItem("empty"){
@Override
public void setSelected( boolean selected ) {
super.setSelected(selected);
if(selected){
this.getWidget().addStyleDependentName("selected");
} else {
this.getWidget().removeStyleDependentName("selected");
}
}
};
item.setManagedObject(node);
if(item == null || item.getRow() == null || item.getRow().getChildNodes().size() == 0){
return node;
}
final TreeItemWidget tWidget = new TreeItemWidget(item);
PropertyChangeListener listener = new PropertyChangeListener(){
public void propertyChange(PropertyChangeEvent evt) {
if(evt.getPropertyName().equals("image") && item.getImage() != null){
tWidget.setImage(new Image(GWT.getModuleBaseURL() + item.getImage()));
} else if(evt.getPropertyName().equals("label")){
tWidget.setLabel(item.getRow().getCell(0).getLabel());
}
}
};
((GwtTreeItem) item).addPropertyChangeListener("image", listener);
((GwtTreeCell) item.getRow().getCell(0)).addPropertyChangeListener("label", listener);;
if (item.getImage() != null) {
tWidget.setImage(new Image(GWT.getModuleBaseURL() + item.getImage()));
}
tWidget.setLabel(item.getRow().getCell(0).getLabel());
if(this.ondrop != null){
TreeItemDropController controller = new TreeItemDropController(item, tWidget);
XulDragController.getInstance().registerDropController(controller);
this.dropHandlers.add(controller);
}
node.setWidget(tWidget);
if(item.getChildNodes().size() > 1){
//has children
//TODO: make this more defensive
XulTreeChildren children = (XulTreeChildren) item.getChildNodes().get(1);
for(XulComponent c : children.getChildNodes()){
TreeItem childNode = createNode((XulTreeItem) c);
node.addItem(childNode);
}
}
return node;
}
private String extractDynamicColType(Object row, int columnPos) {
GwtBindingMethod method = GwtBindingContext.typeController.findGetMethod(row, this.columns.getColumn(columnPos).getColumntypebinding());
try{
return (String) method.invoke(row, new Object[]{});
} catch (Exception e){
System.out.println("Could not extract column type from binding");
}
return "text"; // default //$NON-NLS-1$
}
private Binding createBinding(XulEventSource source, String prop1, XulEventSource target, String prop2){
if(bindingProvider != null){
return bindingProvider.getBinding(source, prop1, target, prop2);
}
return new GwtBinding(source, prop1, target, prop2);
}
private Widget getColumnEditor(final int x, final int y){
final XulTreeCol column = (XulTreeCol) colCollection.get(x);
String colType = ((XulTreeCol) colCollection.get(x)).getType();
final GwtTreeCell cell = (GwtTreeCell) getRootChildren().getItem(y).getRow().getCell(x);
String val = cell.getLabel();
// If collection bound, bindings may need to be updated for runtime changes in column types.
if(this.elements != null){
try {
this.addBindings(column, cell, this.elements.toArray()[y]);
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (XulException e) {
e.printStackTrace();
}
}
if(StringUtils.isEmpty(colType) == false && colType.equalsIgnoreCase("dynamic")){
Object row = elements.toArray()[y];
colType = extractDynamicColType(row, x);
}
int[] selectedRows = getSelectedRows();
if((StringUtils.isEmpty(colType) || !column.isEditable()) || ((showAllEditControls == false && (selectedRows.length != 1 || selectedRows[0] != y)) && !colType.equals("checkbox"))){
if(colType != null && (colType.equalsIgnoreCase("combobox") || colType.equalsIgnoreCase("editablecombobox"))){
Vector vals = (Vector) cell.getValue();
int idx = cell.getSelectedIndex();
if(colType.equalsIgnoreCase("editablecombobox")){
return new HTML(cell.getLabel());
} else if(idx < vals.size()){
return new HTML(""+vals.get(idx));
} else {
return new HTML("");
}
} else {
return new HTML(val);
}
} else if(colType.equalsIgnoreCase("text")){
try{
GwtTextbox b = (GwtTextbox) this.domContainer.getDocumentRoot().createElement("textbox");
b.setDisabled(!column.isEditable());
b.layout();
b.setValue(val);
Binding bind = createBinding(cell, "label", b, "value");
bind.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(bind);
bind.fireSourceChanged();
bind = createBinding(cell, "disabled", b, "disabled");
bind.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(bind);
bind.fireSourceChanged();
return (Widget) b.getManagedObject();
} catch(Exception e){
System.out.println("error creating textbox, fallback");
e.printStackTrace();
final TextBox b = new TextBox();
b.addKeyboardListener(new KeyboardListener(){
public void onKeyDown(Widget arg0, char arg1, int arg2) {}
public void onKeyPress(Widget arg0, char arg1, int arg2) {}
public void onKeyUp(Widget arg0, char arg1, int arg2) {
getRootChildren().getItem(y).getRow().getCell(x).setLabel(b.getText());
}
});
b.setText(val);
return b;
}
} else if (colType.equalsIgnoreCase("checkbox")) {
try {
GwtCheckbox checkBox = (GwtCheckbox) this.domContainer.getDocumentRoot().createElement("checkbox");
checkBox.setDisabled(!column.isEditable());
checkBox.layout();
checkBox.setChecked(Boolean.parseBoolean(val));
Binding bind = createBinding(cell, "value", checkBox, "checked");
bind.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(bind);
bind.fireSourceChanged();
bind = createBinding(cell, "disabled", checkBox, "disabled");
bind.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(bind);
bind.fireSourceChanged();
return (Widget)checkBox.getManagedObject();
} catch (Exception e) {
final CheckBox cb = new CheckBox();
return cb;
}
} else if(colType.equalsIgnoreCase("combobox") || colType.equalsIgnoreCase("editablecombobox")){
try{
final GwtMenuList glb = (GwtMenuList) this.domContainer.getDocumentRoot().createElement("menulist");
final CustomListBox lb = glb.getNativeListBox();
lb.setWidth("100%");
final String fColType = colType;
// Binding to elements of listbox not giving us the behavior we want. Menulists select the first available
// item by default. We don't want anything selected by default in these cell editors
PropertyChangeListener listener = new PropertyChangeListener(){
public void propertyChange(PropertyChangeEvent evt) {
Vector vals = (Vector) cell.getValue();
lb.clear();
lb.setSuppressLayout(true);
for(Object label : vals){
lb.addItem(label.toString());
}
lb.setSuppressLayout(false);
int idx = cell.getSelectedIndex();
if(idx < 0){
idx = 0;
}
if(idx < vals.size()){
lb.setSelectedIndex(idx);
}
if(fColType.equalsIgnoreCase("editablecombobox")){
lb.setValue("");
}
}
};
listener.propertyChange(null);
cell.addPropertyChangeListener("value", listener);
lb.addChangeListener(new ChangeListener(){
public void onChange(Widget arg0) {
if(fColType.equalsIgnoreCase("editablecombobox")){
cell.setLabel(lb.getValue());
} else {
cell.setSelectedIndex(lb.getSelectedIndex());
}
}
});
if(colType.equalsIgnoreCase("editablecombobox")){
lb.setEditable(true);
Binding bind = createBinding(cell, "selectedIndex", glb, "selectedIndex");
bind.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(bind);
if(cell.getLabel() == null){
bind.fireSourceChanged();
}
bind = createBinding(cell, "label", glb, "value");
bind.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(bind);
bind.fireSourceChanged();
} else {
Binding bind = createBinding(cell, "selectedIndex", glb, "selectedIndex");
bind.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(bind);
bind.fireSourceChanged();
}
Binding bind = createBinding(cell, "disabled", glb, "disabled");
bind.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(bind);
bind.fireSourceChanged();
return lb;
} catch(Exception e){
System.out.println("error creating menulist, fallback");
final String fColType = colType;
e.printStackTrace();
final CustomListBox lb = new CustomListBox();
lb.setWidth("100%");
Vector vals = (Vector) cell.getValue();
lb.setSuppressLayout(true);
for(Object label : vals){
lb.addItem(label.toString());
}
lb.setSuppressLayout(false);
lb.addChangeListener(new ChangeListener(){
public void onChange(Widget arg0) {
if(fColType.equalsIgnoreCase("editablecombobox")){
cell.setLabel(lb.getValue());
} else {
cell.setSelectedIndex(lb.getSelectedIndex());
}
}
});
int idx = cell.getSelectedIndex();
if(idx < 0){
idx = 0;
}
if(idx < vals.size()){
lb.setSelectedIndex(idx);
}
if(fColType.equalsIgnoreCase("editablecombobox")){
lb.setEditable(true);
}
lb.setValue(cell.getLabel());
return lb;
}
} else if (colType != null && customEditors.containsKey(colType)){
if(this.customRenderers.containsKey(colType)){
return new CustomCellEditorWrapper(cell, customEditors.get(colType), customRenderers.get(colType));
} else {
return new CustomCellEditorWrapper(cell, customEditors.get(colType));
}
} else {
if(val == null || val.equals("")){
return new HTML(" ");
}
return new HTML(val);
}
}
private int curSelectedRow = -1;
private void setupTable(){
List<XulComponent> colCollection = getColumns().getChildNodes();
String cols[] = new String[colCollection.size()];
SelectionPolicy selectionPolicy = null;
if ("single".equals(getSeltype())) {
selectionPolicy = SelectionPolicy.ONE_ROW;
} else if ("multiple".equals(getSeltype())) {
selectionPolicy = SelectionPolicy.MULTI_ROW;
}
int[] widths = new int[cols.length];
int totalFlex = 0;
for (int i = 0; i < cols.length; i++) {
totalFlex += colCollection.get(i).getFlex();
}
for (int i = 0; i < cols.length; i++) {
cols[i] = ((XulTreeCol) colCollection.get(i)).getLabel();
if(totalFlex > 0 && getWidth() > 0){
widths[i] = (int) (getWidth() * ((double) colCollection.get(i).getFlex() / totalFlex));
} else if(getColumns().getColumn(i).getWidth() > 0){
widths[i] = getColumns().getColumn(i).getWidth();
}
}
table = new BaseTable(cols, widths, new BaseColumnComparator[cols.length], selectionPolicy);
if (getHeight() != 0) {
table.setHeight(getHeight() + "px");
} else {
table.setHeight("100%");
}
if (getWidth() != 0) {
table.setWidth(getWidth() + "px");
} else {
table.setWidth("100%");
}
table.addTableSelectionListener(new TableSelectionListener() {
public void onAllRowsDeselected(SourceTableSelectionEvents sender) {
}
public void onCellHover(SourceTableSelectionEvents sender, int row, int cell) {
}
public void onCellUnhover(SourceTableSelectionEvents sender, int row, int cell) {
}
public void onRowDeselected(SourceTableSelectionEvents sender, int row) {
}
public void onRowHover(SourceTableSelectionEvents sender, int row) {
}
public void onRowUnhover(SourceTableSelectionEvents sender, int row) {
}
public void onRowsSelected(SourceTableSelectionEvents sender, int firstRow, int numRows) {
try {
if (getOnselect() != null && getOnselect().trim().length() > 0) {
getXulDomContainer().invoke(getOnselect(), new Object[]{});
}
Integer[] selectedRows = table.getSelectedRows().toArray(new Integer[table.getSelectedRows().size()]);
//set.toArray(new Integer[]) doesn't unwrap ><
int[] rows = new int[selectedRows.length];
for(int i=0; i<selectedRows.length; i++){
rows[i] = selectedRows[i];
}
GwtTree.this.setSelectedRows(rows);
GwtTree.this.colCollection = getColumns().getChildNodes();
if(GwtTree.this.isShowalleditcontrols() == false){
if(curSelectedRow > -1){
Object[] curSelectedRowOriginal = new Object[getColumns().getColumnCount()];
for (int j = 0; j < getColumns().getColumnCount(); j++) {
curSelectedRowOriginal[j] = getColumnEditor(j,curSelectedRow);
}
table.replaceRow(curSelectedRow, curSelectedRowOriginal);
}
curSelectedRow = rows[0];
Object[] newRow = new Object[getColumns().getColumnCount()];
for (int j = 0; j < getColumns().getColumnCount(); j++) {
newRow[j] = getColumnEditor(j,rows[0]);
}
table.replaceRow(rows[0], newRow);
}
} catch (XulException e) {
e.printStackTrace();
}
}
});
setWidgetInPanel(table);
updateUI();
}
public void updateUI() {
if(this.suppressLayout) {
return;
}
if(this.isHierarchical()){
populateTree();
for(Binding expBind : expandBindings){
try {
expBind.fireSourceChanged();
} catch (Exception e) {
e.printStackTrace();
}
}
// expandBindings.clear();
} else {
populateTable();
};
}
public void afterLayout() {
updateUI();
}
public void clearSelection() {
this.setSelectedRows(new int[]{});
}
public int[] getActiveCellCoordinates() {
// TODO Auto-generated method stub
return null;
}
public XulTreeCols getColumns() {
return columns;
}
public Object getData() {
// TODO Auto-generated method stub
return null;
}
@Bindable
public <T> Collection<T> getElements() {
return this.elements;
}
public String getOnedit() {
return getAttributeValue("onedit");
}
public String getOnselect() {
return getAttributeValue("onselect");
}
public XulTreeChildren getRootChildren() {
return rootChildren;
}
@Bindable
public int getRows() {
if (rootChildren == null) {
return 0;
} else {
return rootChildren.getItemCount();
}
}
@Bindable
public int[] getSelectedRows() {
if(this.isHierarchical()){
TreeItem item = tree.getSelectedItem();
for(int i=0; i <tree.getItemCount(); i++){
if(tree.getItem(i) == item){
return new int[]{i};
}
}
return new int[]{};
} else {
if (table == null) {
return new int[0];
}
Set<Integer> rows = table.getSelectedRows();
int rarr[] = new int[rows.size()];
int i = 0;
for (Integer v : rows) {
rarr[i++] = v;
}
return rarr;
}
}
public int[] getAbsoluteSelectedRows() {
return getSelectedRows();
}
private int[] selectedRows;
public void setSelectedRows(int[] rows) {
if (table == null || Arrays.equals(selectedRows, rows)) {
// this only works after the table has been materialized
return;
}
int[] prevSelected = selectedRows;
selectedRows = rows;
table.deselectRows();
for (int r : rows) {
if(this.rootChildren.getChildNodes().size() > r){
table.selectRow(r);
}
}
if(this.suppressEvents == false && Arrays.equals(selectedRows, prevSelected) == false){
this.changeSupport.firePropertyChange("selectedRows", prevSelected, rows);
this.changeSupport.firePropertyChange("absoluteSelectedRows", prevSelected, rows);
}
}
public String getSeltype() {
return getAttributeValue("seltype");
}
public Object[][] getValues() {
Object[][] data = new Object[getRootChildren().getChildNodes().size()][getColumns().getColumnCount()];
int y = 0;
for (XulComponent component : getRootChildren().getChildNodes()) {
XulTreeItem item = (XulTreeItem)component;
for (XulComponent childComp : item.getChildNodes()) {
XulTreeRow row = (XulTreeRow)childComp;
for (int x = 0; x < getColumns().getColumnCount(); x++) {
XulTreeCell cell = row.getCell(x);
switch (columns.getColumn(x).getColumnType()) {
case CHECKBOX:
Boolean flag = (Boolean) cell.getValue();
if (flag == null) {
flag = Boolean.FALSE;
}
data[y][x] = flag;
break;
case COMBOBOX:
Vector values = (Vector) cell.getValue();
int idx = cell.getSelectedIndex();
data[y][x] = values.get(idx);
break;
default: //label
data[y][x] = cell.getLabel();
break;
}
}
y++;
}
}
return data;
}
@Bindable
public boolean isEditable() {
return editable;
}
public boolean isEnableColumnDrag() {
return false;
}
public boolean isHierarchical() {
return isHierarchical;
}
public void removeTreeRows(int[] rows) {
// sort the rows high to low
ArrayList<Integer> rowArray = new ArrayList<Integer>();
for (int i = 0; i < rows.length; i++) {
rowArray.add(rows[i]);
}
Collections.sort(rowArray, Collections.reverseOrder());
// remove the items in that order
for (int i = 0; i < rowArray.size(); i++) {
int item = rowArray.get(i);
if (item >= 0 && item < rootChildren.getItemCount()) {
this.rootChildren.removeItem(item);
}
}
updateUI();
}
public void setActiveCellCoordinates(int row, int column) {
// TODO Auto-generated method stub
}
public void setColumns(XulTreeCols columns) {
if (getColumns() != null) {
this.removeChild(getColumns());
}
addChild(columns);
}
public void setData(Object data) {
// TODO Auto-generated method stub
}
@Bindable
public void setEditable(boolean edit) {
this.editable = edit;
}
@Bindable
public <T> void setElements(Collection<T> elements) {
try{
this.elements = elements;
suppressEvents = true;
prevSelectionPos = -1;
this.getRootChildren().removeAll();
for(Binding b : expandBindings){
b.destroyBindings();
}
this.expandBindings.clear();
for(TreeItemDropController d : this.dropHandlers){
XulDragController.getInstance().unregisterDropController(d);
}
dropHandlers.clear();
if(elements == null || elements.size() == 0){
suppressEvents = false;
updateUI();
return;
}
try {
if(table != null){
for (T o : elements) {
XulTreeRow row = this.getRootChildren().addNewRow();
int colSize = this.getColumns().getChildNodes().size();
for (int x=0; x< colSize; x++) {
XulComponent col = this.getColumns().getColumn(x);
XulTreeCol column = ((XulTreeCol) col);
final XulTreeCell cell = (XulTreeCell) getDocument().createElement("treecell");
addBindings(column, (GwtTreeCell) cell, o);
row.addCell(cell);
}
}
} else { //tree
for (T o : elements) {
XulTreeRow row = this.getRootChildren().addNewRow();
((XulTreeItem) row.getParent()).setBoundObject(o);
addTreeChild(o, row);
}
}
//treat as a selection change
} catch (XulException e) {
Window.alert("error adding elements "+e);
System.out.println(e.getMessage());
e.printStackTrace();
} catch (Exception e) {
Window.alert("error adding elements "+e);
System.out.println(e.getMessage());
e.printStackTrace();
}
suppressEvents = false;
this.clearSelection();
updateUI();
} catch(Exception e){
System.out.println(e.getMessage());
e.printStackTrace();
}
}
private <T> void addTreeChild(T element, XulTreeRow row){
try{
GwtTreeCell cell = (GwtTreeCell) getDocument().createElement("treecell");
for (InlineBindingExpression exp : ((XulTreeCol) this.getColumns().getChildNodes().get(0)).getBindingExpressions()) {
Binding binding = createBinding((XulEventSource) element, exp.getModelAttr(), cell, exp.getXulCompAttr());
binding.setBindingType(Binding.Type.ONE_WAY);
domContainer.addBinding(binding);
binding.fireSourceChanged();
}
XulTreeCol column = (XulTreeCol) this.getColumns().getChildNodes().get(0);
String expBind = column.getExpandedbinding();
if(expBind != null){
Binding binding = createBinding((XulEventSource) element, expBind, row.getParent(), "expanded");
elementBindings.add(binding);
binding.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(binding);
expandBindings.add(binding);
}
String imgBind = column.getImagebinding();
if(imgBind != null){
Binding binding = createBinding((XulEventSource) element, imgBind, row.getParent(), "image");
elementBindings.add(binding);
binding.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(binding);
binding.fireSourceChanged();
}
row.addCell(cell);
//find children
String property = ((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding();
GwtBindingMethod childrenMethod = GwtBindingContext.typeController.findGetMethod(element, property);
Collection<T> children = null;
if(childrenMethod != null){
children = (Collection<T>) childrenMethod.invoke(element, new Object[] {});
} else if(element instanceof Collection ){
children = (Collection<T>) element;
}
XulTreeChildren treeChildren = null;
if(children != null && children.size() > 0){
treeChildren = (XulTreeChildren) getDocument().createElement("treechildren");
row.getParent().addChild(treeChildren);
}
if (children == null) {
return;
}
for(T child : children){
row = treeChildren.addNewRow();
((XulTreeItem) row.getParent()).setBoundObject(child);
addTreeChild(child, row);
}
} catch (Exception e) {
Window.alert("error adding elements "+e.getMessage());
e.printStackTrace();
}
}
public void setEnableColumnDrag(boolean drag) {
// TODO Auto-generated method stub
}
public void setOnedit(String onedit) {
this.setAttribute("onedit", onedit);
}
public void setOnselect(String select) {
this.setAttribute("onselect", select);
}
public void setRootChildren(XulTreeChildren rootChildren) {
if (getRootChildren() != null) {
this.removeChild(getRootChildren());
}
addChild(rootChildren);
}
public void setRows(int rows) {
// TODO Auto-generated method stub
}
public void setSeltype(String type) {
// TODO Auto-generated method stub
// SINGLE, CELL, MULTIPLE, NONE
this.setAttribute("seltype", type);
}
public void update() {
layout();
}
public void adoptAttributes(XulComponent component) {
super.adoptAttributes(component);
layout();
}
public void registerCellEditor(String key, TreeCellEditor editor){
customEditors.put(key, editor);
}
public void registerCellRenderer(String key, TreeCellRenderer renderer) {
customRenderers.put(key, renderer);
}
private void addBindings(final XulTreeCol col, final GwtTreeCell cell, final Object o) throws InvocationTargetException, XulException{
for (InlineBindingExpression exp : col.getBindingExpressions()) {
String colType = col.getType();
if(StringUtils.isEmpty(colType) == false && colType.equalsIgnoreCase("dynamic")){
colType = extractDynamicColType(o, col.getParent().getChildNodes().indexOf(col));
}
if(colType != null && (colType.equalsIgnoreCase("combobox") || colType.equalsIgnoreCase("editablecombobox"))){
// Only add bindings if they haven't been already applied.
if(cell.valueBindingsAdded() == false){
Binding binding = createBinding((XulEventSource) o, col.getCombobinding(), cell, "value");
binding.setBindingType(Binding.Type.ONE_WAY);
domContainer.addBinding(binding);
binding.fireSourceChanged();
cell.setValueBindingsAdded(true);
}
if(cell.selectedIndexBindingsAdded() == false){
Binding binding = createBinding((XulEventSource) o, ((XulTreeCol) col).getBinding(), cell, "selectedIndex");
binding.setBindingType(Binding.Type.BI_DIRECTIONAL);
binding.setConversion(new BindingConvertor<Object, Integer>(){
@Override
public Integer sourceToTarget(Object value) {
int index = ((Vector) cell.getValue()).indexOf(value);
return index > -1 ? index : 0;
}
@Override
public Object targetToSource(Integer value) {
return ((Vector)cell.getValue()).get(value);
}
});
domContainer.addBinding(binding);
binding.fireSourceChanged();
cell.setSelectedIndexBindingsAdded(true);
}
if(cell.labelBindingsAdded() == false && colType.equalsIgnoreCase("editablecombobox")){
Binding binding = createBinding((XulEventSource) o, exp.getModelAttr(), cell, "label");
binding.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(binding);
binding.fireSourceChanged();
cell.setLabelBindingsAdded(true);
}
} else if(colType != null && this.customEditors.containsKey(colType)){
Binding binding = createBinding((XulEventSource) o, exp.getModelAttr(), cell, "value");
binding.setBindingType(Binding.Type.BI_DIRECTIONAL);
domContainer.addBinding(binding);
binding.fireSourceChanged();
cell.setValueBindingsAdded(true);
} else if(colType != null && colType.equalsIgnoreCase("checkbox")) {
Binding binding = createBinding((XulEventSource) o, exp.getModelAttr(), cell, "value");
if(col.isEditable() == false){
binding.setBindingType(Binding.Type.ONE_WAY);
} else {
binding.setBindingType(Binding.Type.BI_DIRECTIONAL);
}
domContainer.addBinding(binding);
binding.fireSourceChanged();
cell.setValueBindingsAdded(true);
} else if(o instanceof XulEventSource && StringUtils.isEmpty(exp.getModelAttr()) == false){
Binding binding = createBinding((XulEventSource) o, exp.getModelAttr(), cell, exp.getXulCompAttr());
if(col.isEditable() == false){
binding.setBindingType(Binding.Type.ONE_WAY);
} else {
binding.setBindingType(Binding.Type.BI_DIRECTIONAL);
}
domContainer.addBinding(binding);
binding.fireSourceChanged();
cell.setLabelBindingsAdded(true);
} else {
cell.setLabel(o.toString());
}
}
if(StringUtils.isEmpty(col.getDisabledbinding()) == false){
String prop = col.getDisabledbinding();
Binding bind = createBinding((XulEventSource) o, col.getDisabledbinding(), cell, "disabled");
bind.setBindingType(Binding.Type.ONE_WAY);
// the default string to string was causing issues, this is really a boolean to boolean, no conversion necessary
bind.setConversion(null);
domContainer.addBinding(bind);
bind.fireSourceChanged();
}
}
@Deprecated
public void onResize() {
// if(table != null){
// table.onResize();
// }
}
public class CustomCellEditorWrapper extends SimplePanel implements TreeCellEditorCallback{
private TreeCellEditor editor;
private TreeCellRenderer renderer;
private Label label = new Label();
private XulTreeCell cell;
public CustomCellEditorWrapper(XulTreeCell cell, TreeCellEditor editor){
super();
this.sinkEvents(Event.MOUSEEVENTS);
this.editor = editor;
this.cell = cell;
HorizontalPanel hPanel = new HorizontalPanel();
hPanel.setStylePrimaryName("slimTable");
SimplePanel labelWrapper = new SimplePanel();
labelWrapper.getElement().getStyle().setProperty("overflow", "hidden");
labelWrapper.setWidth("100%");
labelWrapper.add(label);
hPanel.add(labelWrapper);
hPanel.setCellWidth(labelWrapper, "100%");
ImageButton btn = new ImageButton(GWT.getModuleBaseURL() + "/images/open_new.png", GWT.getModuleBaseURL() + "/images/open_new.png", "", 29, 24);
btn.getElement().getStyle().setProperty("margin", "0px");
hPanel.add(btn);
hPanel.setSpacing(0);
hPanel.setBorderWidth(0);
hPanel.setWidth("100%");
labelWrapper.getElement().getParentElement().getStyle().setProperty("padding", "0px");
labelWrapper.getElement().getParentElement().getStyle().setProperty("border", "0px");
btn.getElement().getParentElement().getStyle().setProperty("padding", "0px");
btn.getElement().getParentElement().getStyle().setProperty("border", "0px");
this.add( hPanel );
if(cell.getValue() != null) {
this.label.setText((cell.getValue() != null) ? cell.getValue().toString() : " ");
}
}
public CustomCellEditorWrapper(XulTreeCell cell, TreeCellEditor editor, TreeCellRenderer renderer){
this(cell, editor);
this.renderer = renderer;
if(this.renderer.supportsNativeComponent()){
this.clear();
this.add((Widget) this.renderer.getNativeComponent());
} else {
this.label.setText((this.renderer.getText(cell.getValue()) != null) ? this.renderer.getText(cell.getValue()) : " ");
}
}
public void onCellEditorClosed(Object value) {
cell.setValue(value);
if(this.renderer == null){
this.label.setText(value.toString());
} else if(this.renderer.supportsNativeComponent()){
this.clear();
this.add((Widget) this.renderer.getNativeComponent());
} else {
this.label.setText((this.renderer.getText(cell.getValue()) != null) ? this.renderer.getText(cell.getValue()) : " ");
}
}
@Override
public void onBrowserEvent(Event event) {
int code = event.getTypeInt();
switch(code){
case Event.ONMOUSEUP:
editor.setValue(cell.getValue());
int col = cell.getParent().getChildNodes().indexOf(cell);
XulTreeItem item = (XulTreeItem) cell.getParent().getParent();
int row = item.getParent().getChildNodes().indexOf(item);
Object boundObj = (GwtTree.this.getElements() != null) ? GwtTree.this.getElements().toArray()[row] : null;
String columnBinding = GwtTree.this.getColumns().getColumn(col).getBinding();
editor.show(row, col, boundObj, columnBinding, this);
default:
break;
}
super.onBrowserEvent(event);
}
}
public void setBoundObjectExpanded(Object o, boolean expanded) {
throw new UnsupportedOperationException("not implemented");
}
public void setTreeItemExpanded(XulTreeItem item, boolean expanded) {
((TreeItem) item.getManagedObject()).setState(expanded);
}
public void collapseAll() {
if (this.isHierarchical()){
//TODO: Not yet implemented
}
}
public void expandAll() {
if (this.isHierarchical()){
//TODO: not implemented yet
}
}
@Bindable
public <T> Collection<T> getSelectedItems() {
// TODO Auto-generated method stub
return null;
}
@Bindable
public <T> void setSelectedItems(Collection<T> items) {
// TODO Auto-generated method stub
}
public boolean isHiddenrootnode() {
// TODO Auto-generated method stub
return false;
}
public void setHiddenrootnode(boolean hidden) {
// TODO Auto-generated method stub
}
public String getCommand() {
return command;
}
public void setCommand(String command) {
this.command = command;
}
public boolean isPreserveexpandedstate() {
return false;
}
public void setPreserveexpandedstate(boolean preserve) {
}
public boolean isSortable() {
// TODO Auto-generated method stub
return false;
}
public void setSortable(boolean sort) {
// TODO Auto-generated method stub
}
public boolean isTreeLines() {
// TODO Auto-generated method stub
return false;
}
public void setTreeLines(boolean visible) {
// TODO Auto-generated method stub
}
public void setNewitembinding(String binding){
}
public String getNewitembinding(){
return null;
}
public void setAutocreatenewrows(boolean auto){
}
public boolean getAutocreatenewrows(){
return false;
}
public boolean isPreserveselection() {
// TODO This method is not fully implemented. We need to completely implement this in this class
return false;
}
public void setPreserveselection(boolean preserve) {
// TODO This method is not fully implemented. We need to completely implement this in this class
}
private void fireSelectedItems( ) {
Object selected = getSelectedItem();
this.changeSupport.firePropertyChange("selectedItem", null, selected);
}
@Bindable
public Object getSelectedItem() {
if (this.isHierarchical && this.elements != null) {
int pos = -1;
int curPos = 0;
for(int i=0; i < tree.getItemCount(); i++){
TreeItem tItem = tree.getItem(i);
TreeCursor cursor = GwtTree.this.findPosition(tItem, tree.getSelectedItem(), curPos);
pos = cursor.foundPosition;
curPos = cursor.curPos+1;
if(pos > -1){
break;
}
}
int[] vals = new int[]{pos};
String property = ((XulTreeCol) this.getColumns().getChildNodes().get(0)).getChildrenbinding();
FindSelectedItemTuple tuple = findSelectedItem(this.elements, property, new FindSelectedItemTuple(vals[0]));
return tuple != null ? tuple.selectedItem : null;
}
return null;
}
private static class FindSelectedItemTuple {
Object selectedItem = null;
int curpos = -1; // ignores first element (root)
int selectedIndex;
public FindSelectedItemTuple(int selectedIndex) {
this.selectedIndex = selectedIndex;
}
}
private FindSelectedItemTuple findSelectedItem(Object parent, String childrenMethodProperty,
FindSelectedItemTuple tuple) {
if (tuple.curpos == tuple.selectedIndex) {
tuple.selectedItem = parent;
return tuple;
}
Collection children = getChildCollection(parent, childrenMethodProperty);
if (children == null || children.size() == 0) {
return null;
}
for (Object child : children) {
tuple.curpos++;
findSelectedItem(child, childrenMethodProperty, tuple);
if (tuple.selectedItem != null) {
return tuple;
}
}
return null;
}
private static Collection getChildCollection(Object obj, String childrenMethodProperty) {
Collection children = null;
GwtBindingMethod childrenMethod = GwtBindingContext.typeController.findGetMethod(obj, childrenMethodProperty);
try {
if (childrenMethod != null) {
children = (Collection) childrenMethod.invoke(obj, new Object[] {});
} else if(obj instanceof Collection ){
children = (Collection) obj;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return children;
}
public boolean isShowalleditcontrols() {
return showAllEditControls;
}
public void setShowalleditcontrols(boolean showAllEditControls) {
this.showAllEditControls = showAllEditControls;
}
@Override
public void setOndrag(String ondrag) {
super.setOndrag(ondrag);
}
@Override
public void setOndrop(String ondrop) {
super.setOndrop(ondrop);
}
@Override
public void setDropvetoer(String dropVetoMethod) {
if(StringUtils.isEmpty(dropVetoMethod)){
return;
}
super.setDropvetoer(dropVetoMethod);
}
private void resolveDropVetoerMethod(){
if(dropVetoerMethod == null && !StringUtils.isEmpty(getDropvetoer())){
String id = getDropvetoer().substring(0, getDropvetoer().indexOf("."));
try {
XulEventHandler controller = getXulDomContainer().getEventHandler(id);
this.dropVetoerMethod = GwtBindingContext.typeController.findMethod(controller, getDropvetoer().substring(getDropvetoer().indexOf(".")+1, getDropvetoer().indexOf("(")));
this.dropVetoerController = controller;
} catch (XulException e) {
e.printStackTrace();
}
}
}
private class TreeItemDropController extends AbstractPositioningDropController {
private XulTreeItem xulItem;
private TreeItemWidget item;
private DropPosition curPos;
private long lasPositionPoll = 0;
public TreeItemDropController(XulTreeItem xulItem, TreeItemWidget item){
super(item);
this.xulItem = xulItem;
this.item = item;
}
@Override
public void onEnter(DragContext context) {
super.onEnter(context);
resolveDropVetoerMethod();
if(dropVetoerMethod != null){
Object objToMove = ((XulDragController) context.dragController).getDragObject();
DropEvent event = new DropEvent();
DataTransfer dataTransfer = new DataTransfer();
dataTransfer.setData(Collections.singletonList(objToMove));
event.setDataTransfer(dataTransfer);
event.setAccepted(true);
event.setDropPosition(curPos);
if(curPos == DropPosition.MIDDLE){
event.setDropParent(xulItem.getBoundObject());
} else {
XulComponent parent = xulItem.getParent().getParent();
Object parentObj;
if(parent instanceof GwtTree){
parentObj = GwtTree.this.elements;
} else {
parentObj = ((XulTreeItem) parent).getBoundObject();
}
event.setDropParent(parentObj);
}
try {
// Consult Vetoer method to see if this is a valid drop operation
dropVetoerMethod.invoke(dropVetoerController, new Object[]{event});
//Check to see if this drop candidate should be rejected.
if(event.isAccepted() == false){
return;
}
} catch (XulException e) {
e.printStackTrace();
}
}
((Draggable) XulDragController.getInstance().getProxy()).setDropValid(true);
}
@Override
public void onLeave(DragContext context) {
super.onLeave(context);
item.getElement().getStyle().setProperty("border", "");
item.highLightDrop(false);
dropPosIndicator.setVisible(false);
Widget proxy = XulDragController.getInstance().getProxy();
if(proxy != null){
((Draggable) proxy).setDropValid(false);
}
}
@Override
public void onMove(DragContext context) {
super.onMove(context);
int scrollPanelX = 0;
int scrollPanelY = 0;
int scrollPanelScrollTop = 0;
int scrollPanelScrollLeft = 0;
if(System.currentTimeMillis() > lasPositionPoll+3000){
scrollPanelX = scrollPanel.getElement().getAbsoluteLeft();
scrollPanelScrollLeft = scrollPanel.getElement().getScrollLeft();
scrollPanelY = scrollPanel.getElement().getAbsoluteTop();
scrollPanelScrollTop = scrollPanel.getElement().getScrollTop();
}
int x = item.getAbsoluteLeft();
int y = item.getAbsoluteTop();
int height = item.getOffsetHeight();
int middleGround = height/4;
if(context.mouseY < (y+height/2)-middleGround){
curPos = DropPosition.ABOVE;
} else if(context.mouseY > (y+height/2)+middleGround){
curPos = DropPosition.BELOW;
} else {
curPos = DropPosition.MIDDLE;
}
resolveDropVetoerMethod();
if(dropVetoerMethod != null){
Object objToMove = ((XulDragController) context.dragController).getDragObject();
DropEvent event = new DropEvent();
DataTransfer dataTransfer = new DataTransfer();
dataTransfer.setData(Collections.singletonList(objToMove));
event.setDataTransfer(dataTransfer);
event.setAccepted(true);
event.setDropPosition(curPos);
if(curPos == DropPosition.MIDDLE){
event.setDropParent(xulItem.getBoundObject());
} else {
XulComponent parent = xulItem.getParent().getParent();
Object parentObj;
if(parent instanceof GwtTree){
parentObj = GwtTree.this.elements;
} else {
parentObj = ((XulTreeItem) parent).getBoundObject();
}
event.setDropParent(parentObj);
}
try {
// Consult Vetoer method to see if this is a valid drop operation
dropVetoerMethod.invoke(dropVetoerController, new Object[]{event});
//Check to see if this drop candidate should be rejected.
if(event.isAccepted() == false){
((Draggable) XulDragController.getInstance().getProxy()).setDropValid(false);
dropPosIndicator.setVisible(false);
return;
}
} catch (XulException e) {
e.printStackTrace();
}
}
((Draggable) XulDragController.getInstance().getProxy()).setDropValid(true);
switch (curPos) {
case ABOVE:
item.highLightDrop(false);
int posX = item.getElement().getAbsoluteLeft()
- scrollPanelX
+ scrollPanelScrollLeft;
int posY = item.getElement().getAbsoluteTop()
- scrollPanelY
+ scrollPanelScrollTop
-4;
dropPosIndicator.setPosition(posX, posY, item.getOffsetWidth());
break;
case MIDDLE:
item.highLightDrop(true);
dropPosIndicator.setVisible(false);
break;
case BELOW:
item.highLightDrop(false);
posX = item.getElement().getAbsoluteLeft()
- scrollPanelX
+ scrollPanelScrollLeft;
posY = item.getElement().getAbsoluteTop()
+ item.getElement().getOffsetHeight()
- scrollPanelY
+ scrollPanelScrollTop
-4;
dropPosIndicator.setPosition(posX, posY, item.getOffsetWidth());
break;
}
}
@Override
public void onPreviewDrop(DragContext context) throws VetoDragException {
int i=0;
}
@Override
public void onDrop(DragContext context) {
super.onDrop(context);
Object objToMove = ((XulDragController) context.dragController).getDragObject();
DropEvent event = new DropEvent();
DataTransfer dataTransfer = new DataTransfer();
dataTransfer.setData(Collections.singletonList(objToMove));
event.setDataTransfer(dataTransfer);
event.setAccepted(true);
if(curPos == DropPosition.MIDDLE){
event.setDropParent(xulItem.getBoundObject());
} else {
XulComponent parent = xulItem.getParent().getParent();
Object parentObj;
if(parent instanceof GwtTree){
parentObj = GwtTree.this.elements;
} else {
parentObj = ((XulTreeItem) parent).getBoundObject();
}
event.setDropParent(parentObj);
}
//event.setDropIndex(index);
final String method = getOndrop();
if (method != null) {
try{
Document doc = getDocument();
XulRoot window = (XulRoot) doc.getRootElement();
final XulDomContainer con = window.getXulDomContainer();
con.invoke(method, new Object[]{event});
} catch (XulException e){
e.printStackTrace();
System.out.println("Error calling ondrop event: "+ method); //$NON-NLS-1$
}
}
if (!event.isAccepted()) {
return;
}
// ==============
((Draggable) context.draggable).notifyDragFinished();
if(curPos == DropPosition.MIDDLE){
String property = ((XulTreeCol) GwtTree.this.getColumns().getChildNodes().get(0)).getChildrenbinding();
GwtBindingMethod childrenMethod = GwtBindingContext.typeController.findGetMethod(xulItem.getBoundObject(), property);
Collection children = null;
try {
if(childrenMethod != null){
children = (Collection) childrenMethod.invoke(xulItem.getBoundObject(), new Object[] {});
} else if(xulItem.getBoundObject() instanceof Collection ){
children = (Collection) xulItem.getBoundObject();
}
for(Object o : event.getDataTransfer().getData()){
children.add(o);
}
} catch (XulException e) {
e.printStackTrace();
}
} else {
XulComponent parent = xulItem.getParent().getParent();
List parentList;
if(parent instanceof GwtTree){
parentList = (List) GwtTree.this.elements;
} else {
parentList = (List) ((XulTreeItem) parent).getBoundObject();
}
int idx = parentList.indexOf(xulItem.getBoundObject());
if (curPos == DropPosition.BELOW){
idx++;
}
for(Object o : event.getDataTransfer().getData()){
parentList.add(idx, o);
}
}
}
}
public void notifyDragFinished(XulTreeItem xulItem){
if(this.drageffect.equalsIgnoreCase("copy")){
return;
}
XulComponent parent = xulItem.getParent().getParent();
List parentList;
if(parent instanceof GwtTree){
parentList = (List) GwtTree.this.elements;
} else {
parentList = (List) ((XulTreeItem) parent).getBoundObject();
}
parentList.remove(xulItem.getBoundObject());
}
private class DropPositionIndicator extends SimplePanel{
public DropPositionIndicator(){
setStylePrimaryName("tree-drop-indicator-symbol");
SimplePanel line = new SimplePanel();
line.setStylePrimaryName("tree-drop-indicator");
add(line);
setVisible(false);
}
public void setPosition(int scrollLeft, int scrollTop, int offsetWidth) {
this.setVisible(true);
setWidth(offsetWidth+"px");
getElement().getStyle().setProperty("top", scrollTop+"px");
getElement().getStyle().setProperty("left", (scrollLeft -4)+"px");
}
}
}
| Implemented ExpandAll and CollapseAll in GwtTree to support: BISERVER-5924 - Allow users easy way to expand and collapse Model tree
| pentaho-xul-gwt/src/org/pentaho/ui/xul/gwt/tags/GwtTree.java | Implemented ExpandAll and CollapseAll in GwtTree to support: BISERVER-5924 - Allow users easy way to expand and collapse Model tree |
|
Java | apache-2.0 | 3e3a9442fd3c4189a4e43a767095b07aaaab8793 | 0 | aduprat/james,chibenwa/james,rouazana/james,rouazana/james,aduprat/james,chibenwa/james,chibenwa/james,aduprat/james,chibenwa/james,rouazana/james,rouazana/james,aduprat/james | /*****************************************************************************
* Copyright (C) The Apache Software Foundation. All rights reserved. *
* ------------------------------------------------------------------------- *
* This software is published under the terms of the Apache Software License *
* version 1.1, a copy of which has been included with this distribution in *
* the LICENSE file. *
*****************************************************************************/
package org.apache.james;
import org.apache.avalon.blocks.*;
import org.apache.arch.*;
import org.apache.java.util.*;
import java.util.*;
import java.io.*;
import org.apache.mail.Mail;
import javax.mail.internet.*;
import javax.mail.MessagingException;
/**
* Implementation of a Repository to store Mails.
* @version 1.0.0, 24/04/1999
* @author Federico Barbieri <[email protected]>
*/
public class MailRepository implements Store.Repository {
/**
* Define a STREAM repository. Streams are stored in the specified
* destination.
*/
public final static String MAIL = "MAIL";
private Store.StreamRepository sr;
private Store.ObjectRepository or;
private String path;
private String name;
private String destination;
private String type;
private String model;
private Lock lock;
public MailRepository() {
}
public void setAttributes(String name, String destination, String type, String model) {
this.name = name;
this.destination = destination;
this.model = model;
this.type = type;
}
public void setComponentManager(ComponentManager comp) {
Store store = (Store) comp.getComponent(Interfaces.STORE);
this.sr = (Store.StreamRepository) store.getPrivateRepository(destination, Store.STREAM, model);
this.or = (Store.ObjectRepository) store.getPrivateRepository(destination, Store.OBJECT, model);
lock = new Lock();
}
public String getName() {
return name;
}
public String getType() {
return type;
}
public String getModel() {
return model;
}
public String getChildDestination(String childName) {
return destination + childName.replace ('.', File.pathSeparatorChar) + File.pathSeparator;
}
public synchronized void unlock(Object key) {
if (lock.unlock(key)) {
notifyAll();
} else {
throw new LockException("Your thread do not own the lock of record " + key);
}
}
public synchronized void lock(Object key) {
if (lock.lock(key)) {
notifyAll();
} else {
throw new LockException("Record " + key + " already locked by another thread");
}
}
public synchronized String accept() {
while (true) {
for(Enumeration e = or.list(); e.hasMoreElements(); ) {
Object o = e.nextElement();
if (lock.lock(o)) {
return o.toString();
}
}
try {
wait();
} catch (InterruptedException ignored) {
}
}
}
public synchronized void store(Mail mc) {
try {
String key = mc.getName();
OutputStream out = sr.store(key);
mc.writeMessageTo(out);
out.close();
or.store(key, mc);
notifyAll();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Exception caught while storing Message Container: " + e);
}
}
public synchronized Mail retrieve(String key) {
Mail mc = (Mail) or.get(key);
try {
mc.setMessage(sr.retrieve(key));
} catch (Exception me) {
throw new RuntimeException("Exception while retrieving mail: " + me.getMessage());
}
return mc;
}
public synchronized void remove(Mail mail) {
remove(mail.getName());
}
public synchronized void remove(String key) {
lock(key);
sr.remove(key);
or.remove(key);
unlock(key);
}
public Enumeration list() {
return sr.list();
}
}
| src/org/apache/james/MailRepository.java | /*****************************************************************************
* Copyright (C) The Apache Software Foundation. All rights reserved. *
* ------------------------------------------------------------------------- *
* This software is published under the terms of the Apache Software License *
* version 1.1, a copy of which has been included with this distribution in *
* the LICENSE file. *
*****************************************************************************/
package org.apache.james;
import org.apache.avalon.blocks.*;
import org.apache.arch.*;
import org.apache.java.util.*;
import java.util.*;
import java.io.*;
import org.apache.mail.Mail;
import javax.mail.internet.*;
import javax.mail.MessagingException;
/**
* Implementation of a Repository to store Mails.
* @version 1.0.0, 24/04/1999
* @author Federico Barbieri <[email protected]>
*/
public class MailRepository implements Store.Repository {
/**
* Define a STREAM repository. Streams are stored in the specified
* destination.
*/
public final static String MAIL = "MAIL";
private Store.StreamRepository sr;
private Store.ObjectRepository or;
private String path;
private String name;
private String destination;
private String type;
private String model;
private Lock lock;
public MailRepository() {
}
public void setAttributes(String name, String destination, String type, String model) {
this.name = name;
this.destination = destination;
this.model = model;
this.type = type;
}
public void setComponentManager(ComponentManager comp) {
Store store = (Store) comp.getComponent(Interfaces.STORE);
this.sr = (Store.StreamRepository) store.getPrivateRepository(destination, Store.STREAM, model);
this.or = (Store.ObjectRepository) store.getPrivateRepository(destination, Store.OBJECT, model);
lock = new Lock();
}
public String getName() {
return name;
}
public String getType() {
return type;
}
public String getModel() {
return model;
}
public String getChildDestination(String childName) {
return destination + childName.replace('.', '/') + "/";
}
public synchronized void unlock(Object key) {
if (lock.unlock(key)) {
notifyAll();
} else {
throw new LockException("Your thread do not own the lock of record " + key);
}
}
public synchronized void lock(Object key) {
if (lock.lock(key)) {
notifyAll();
} else {
throw new LockException("Record " + key + " already locked by another thread");
}
}
public synchronized String accept() {
while (true) {
for(Enumeration e = or.list(); e.hasMoreElements(); ) {
Object o = e.nextElement();
if (lock.lock(o)) {
return o.toString();
}
}
try {
wait();
} catch (InterruptedException ignored) {
}
}
}
public synchronized void store(Mail mc) {
try {
String key = mc.getName();
OutputStream out = sr.store(key);
mc.writeMessageTo(out);
out.close();
or.store(key, mc);
notifyAll();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Exception caught while storing Message Container: " + e);
}
}
public synchronized Mail retrieve(String key) {
Mail mc = (Mail) or.get(key);
try {
mc.setMessage(sr.retrieve(key));
} catch (Exception me) {
throw new RuntimeException("Exception while retrieving mail: " + me.getMessage());
}
return mc;
}
public synchronized void remove(Mail mail) {
remove(mail.getName());
}
public synchronized void remove(String key) {
lock(key);
sr.remove(key);
or.remove(key);
unlock(key);
}
public Enumeration list() {
return sr.list();
}
}
| patched to be file system independent
git-svn-id: de9d04cf23151003780adc3e4ddb7078e3680318@107064 13f79535-47bb-0310-9956-ffa450edef68
| src/org/apache/james/MailRepository.java | patched to be file system independent |
|
Java | apache-2.0 | a602dbc07683689fc34186ab9c6194a0d349bc0c | 0 | operasoftware/operaprestodriver,operasoftware/operaprestodriver,operasoftware/operaprestodriver | package com.opera.core.systems;
import java.awt.Dimension;
import java.awt.Point;
import com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo;
import com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect;
import com.opera.core.systems.scope.services.IDesktopWindowManager;
public class QuickWidget {
private final QuickWidgetInfo info;
private final IDesktopWindowManager desktopWindowManager;
public QuickWidget(IDesktopWindowManager wm, QuickWidgetInfo info) {
this.info = info;
this.desktopWindowManager = wm;
}
/**
*
* @return name of widget
*/
public String getName() {
return info.getName();
}
/**
*
* @return text of widget
*/
public String getText() {
return info.getText();
}
/**
* Check if widget text equals the text specified by @param string_id
*
* @return true if text specified by string_id equals widget text
*/
public boolean verifyText(String string_id) {
String text = desktopWindowManager.getString(string_id);
return getText().equals(text);
}
/**
* Check if widget text contains the text specified by @param string_id
*
* @param String string_id - id of string
* @return true if text specified by string_id is contained in widget text
*/
public boolean verifyContainsText(String string_id) {
String text = desktopWindowManager.getString(string_id);
return getText().indexOf(text) >= 0;
}
/**
* @return true if widget is default, else false
*/
public boolean isDefault() {
return info.getDefaultLook();
}
/**
*
* @return
*/
public boolean hasFocusedLook() {
return info.getFocusedLook();
}
/**
* Check if widget is enabled
* @return true if enabled, else false
*/
public boolean isEnabled() {
return info.getEnabled();
}
/**
* @return if widget is selected, else false
*/
public boolean isSelected() {
return info.getValue() == 1;
}
/**
* @return true if widget is visible
*/
// TODO, FIXME: This needs to handle also if the dialog is not expanded, is off_screen etc.
public boolean isVisible(){
return info.getVisible();
}
/*
*/
public boolean toggle() {
// TODO FIXME
return false;
}
/**
* @return DesktopWindowRect of the widget
*/
private DesktopWindowRect getRect() {
return info.getRect();
}
/**
* @return Point describing location of widget
*/
public Point getLocation() {
DesktopWindowRect rect = getRect();
return new Point(rect.getX(), rect.getY());
}
/**
* @return size of widget
*/
public Dimension getSize() {
DesktopWindowRect rect = getRect();
return new Dimension(rect.getWidth(), rect.getHeight());
}
@Override
// TODO: FIXME
public boolean equals(Object obj) {
if(obj instanceof QuickWidget) {
QuickWidget ref = (QuickWidget) obj;
return (ref.getName().equals(this.getName()));
}
return false;
}
@Override
// TODO: Fixme
public int hashCode() {
int result = 42;
result = 31 * result + getName().hashCode();
return result;
}
@Override
public String toString() {
return "QuickWidget " + getName();
}
public String toFullString() {
return "QuickWidget\n" +
" Widget name: " + info.getName() + "\n"
+ " type: " + info.getType() + "\n"
+ " visible: " + info.getVisible() + "\n"
+ " text: " + info.getText() + "\n"
+ " state: " + info.getValue() + "\n"
+ " enabled: " + info.getEnabled() + "\n"
+ " default: " + info.getDefaultLook() + "\n"
+ " focused: " + info.getFocusedLook() + "\n"
+ " x: " + info.getRect().getX() + "\n"
+ " y: " + info.getRect().getY() + "\n"
+ " width: " + info.getRect().getWidth() + "\n"
+ " height: " + info.getRect().getHeight() + " \n";
}
}
| src/com/opera/core/systems/QuickWidget.java | package com.opera.core.systems;
import java.awt.Dimension;
import java.awt.Point;
import com.opera.core.systems.scope.protos.DesktopWmProtos.QuickWidgetInfo;
import com.opera.core.systems.scope.protos.DesktopWmProtos.DesktopWindowRect;
import com.opera.core.systems.scope.services.IDesktopWindowManager;
public class QuickWidget {
private final QuickWidgetInfo info; // or just int objectId
//private final OperaDesktopDriver parent;
private final IDesktopWindowManager desktopWindowManager;
public QuickWidget(IDesktopWindowManager wm, QuickWidgetInfo info) {
this.info = info;
this.desktopWindowManager = wm;
}
public String getName() {
return info.getName();
}
public String getText() {
return info.getText();
}
public boolean verifyText(String string_id) {
String text = desktopWindowManager.getString(string_id);
return getText().equals(text);
}
public boolean verifyContainsText(String string_id) {
String text = desktopWindowManager.getString(string_id);
return getText().indexOf(text) >= 0;
}
/* (non-Javadoc)
* @see com.opera.core.systems.IOperaWidget#isEnabled()
*/
public boolean isDefault() {
return info.getDefaultLook();
}
// TODO: FIXME .
public boolean hasFocusedLook() {
return info.getFocusedLook();
}
public boolean isEnabled() {
return info.getEnabled();
}
/* (non-Javadoc)
* @see com.opera.core.systems.IOperaWidget#isSelected()
*/
public boolean isSelected() {
return info.getValue() == 1;
}
/* (non-Javadoc)
* @see com.opera.core.systems.IOperaWidget#isVisible()
* TODO, FIXME: This needs to handle also if the dialog is not expanded, is off_screen etc.
*/
public boolean isVisible(){
return info.getVisible();
}
/* (non-Javadoc)
* @see com.opera.core.systems.IOperaWidget#toggle()
*/
public boolean toggle() {
// TODO FIXME
return false;
}
private DesktopWindowRect getRect() {
return info.getRect();
}
public Point getLocation() {
DesktopWindowRect rect = getRect();
return new Point(rect.getX(), rect.getY());
}
/* (non-Javadoc)
* @see com.opera.core.systems.IOperaWidget#getSize()
*/
public Dimension getSize() {
DesktopWindowRect rect = getRect();
return new Dimension(rect.getWidth(), rect.getHeight());
}
@Override
public boolean equals(Object obj) {
if(obj instanceof QuickWidget) {
QuickWidget ref = (QuickWidget) obj;
return (ref.getName().equals(this.getName()));
}
return false;
}
@Override
public int hashCode() {
int result = 42;
result = 31 * result + getName().hashCode();
return result;
}
@Override
public String toString() {
return "QuickWidget " + getName();
}
public String toFullString() {
return "QuickWidget\n" +
" Widget name: " + info.getName() + "\n"
+ " type: " + info.getType() + "\n"
+ " visible: " + info.getVisible() + "\n"
+ " text: " + info.getText() + "\n"
+ " state: " + info.getValue() + "\n"
+ " enabled: " + info.getEnabled() + "\n"
+ " default: " + info.getDefaultLook() + "\n"
+ " focused: " + info.getFocusedLook() + "\n"
+ " x: " + info.getRect().getX() + "\n"
+ " y: " + info.getRect().getY() + "\n"
+ " width: " + info.getRect().getWidth() + "\n"
+ " height: " + info.getRect().getHeight() + " \n";
}
}
| Cleanup and documentation
| src/com/opera/core/systems/QuickWidget.java | Cleanup and documentation |
|
Java | apache-2.0 | dba3aa2d4f59b6d7a93cb1fcaee61cd83e3342e7 | 0 | fengshao0907/netty,yonglehou/netty-1,mcobrien/netty,BrunoColin/netty,MediumOne/netty,hepin1989/netty,balaprasanna/netty,Squarespace/netty,liyang1025/netty,niuxinghua/netty,afds/netty,brennangaunce/netty,tbrooks8/netty,hgl888/netty,skyao/netty,zxhfirefox/netty,clebertsuconic/netty,lugt/netty,windie/netty,bob329/netty,firebase/netty,louxiu/netty,duqiao/netty,purplefox/netty-4.0.2.8-hacked,jchambers/netty,seetharamireddy540/netty,eonezhang/netty,lukw00/netty,johnou/netty,mway08/netty,mikkokar/netty,lugt/netty,Squarespace/netty,purplefox/netty-4.0.2.8-hacked,Alwayswithme/netty,LuminateWireless/netty,olupotd/netty,liuciuse/netty,nayato/netty,codevelop/netty,CodingFabian/netty,louxiu/netty,tempbottle/netty,huuthang1993/netty,NiteshKant/netty,woshilaiceshide/netty,Apache9/netty,chanakaudaya/netty,joansmith/netty,ichaki5748/netty,hepin1989/netty,tempbottle/netty,fengshao0907/netty,sunbeansoft/netty,liyang1025/netty,jovezhougang/netty,sameira/netty,purplefox/netty-4.0.2.8-hacked,kyle-liu/netty4study,IBYoung/netty,ejona86/netty,fengshao0907/netty,Mounika-Chirukuri/netty,Scottmitch/netty,yrcourage/netty,Apache9/netty,f7753/netty,f7753/netty,LuminateWireless/netty,AnselQiao/netty,phlizik/netty,junjiemars/netty,silvaran/netty,yawkat/netty,zer0se7en/netty,jongyeol/netty,yrcourage/netty,nkhuyu/netty,carlbai/netty,zer0se7en/netty,Apache9/netty,NiteshKant/netty,alkemist/netty,DavidAlphaFox/netty,imangry/netty-zh,lightsocks/netty,drowning/netty,fengjiachun/netty,orika/netty,sja/netty,idelpivnitskiy/netty,jdivy/netty,windie/netty,AchinthaReemal/netty,yonglehou/netty-1,KatsuraKKKK/netty,joansmith/netty,huanyi0723/netty,skyao/netty,orika/netty,altihou/netty,NiteshKant/netty,youprofit/netty,kyle-liu/netty4study,sverkera/netty,x1957/netty,eincs/netty,lugt/netty,fengjiachun/netty,yipen9/netty,yonglehou/netty-1,chanakaudaya/netty,jdivy/netty,liuciuse/netty,jongyeol/netty,djchen/netty,zer0se7en/netty,kiril-me/netty,nkhuyu/netty,blucas/netty,BrunoColin/netty,eonezhang/netty,kiril-me/netty,Techcable/netty,nadeeshaan/netty,andsel/netty,zhoffice/netty,mcobrien/netty,tempbottle/netty,shenguoquan/netty,xingguang2013/netty,xiexingguang/netty,imangry/netty-zh,CodingFabian/netty,BrunoColin/netty,ejona86/netty,jenskordowski/netty,smayoorans/netty,kjniemi/netty,niuxinghua/netty,hyangtack/netty,seetharamireddy540/netty,kjniemi/netty,ngocdaothanh/netty,hyangtack/netty,kvr000/netty,orika/netty,gigold/netty,slandelle/netty,mcanthony/netty,louiscryan/netty,JungMinu/netty,s-gheldd/netty,serioussam/netty,Mounika-Chirukuri/netty,sameira/netty,pengzj/netty,Kingson4Wu/netty,bob329/netty,balaprasanna/netty,niuxinghua/netty,phlizik/netty,seetharamireddy540/netty,shuangqiuan/netty,moyiguket/netty,Squarespace/netty,gigold/netty,shenguoquan/netty,wangyikai/netty,mikkokar/netty,bigheary/netty,lightsocks/netty,sverkera/netty,xiexingguang/netty,hgl888/netty,smayoorans/netty,afds/netty,qingsong-xu/netty,xingguang2013/netty,shism/netty,johnou/netty,shelsonjava/netty,purplefox/netty-4.0.2.8-hacked,mubarak/netty,s-gheldd/netty,mikkokar/netty,zhujingling/netty,Spikhalskiy/netty,danny200309/netty,alkemist/netty,fenik17/netty,kiril-me/netty,orika/netty,KatsuraKKKK/netty,johnou/netty,daschl/netty,junjiemars/netty,nat2013/netty,zhoffice/netty,nadeeshaan/netty,clebertsuconic/netty,eonezhang/netty,jdivy/netty,lukw00/netty,chinayin/netty,DavidAlphaFox/netty,codevelop/netty,normanmaurer/netty,shism/netty,doom369/netty,castomer/netty,duqiao/netty,bigheary/netty,JungMinu/netty,mcanthony/netty,huuthang1993/netty,kvr000/netty,djchen/netty,nadeeshaan/netty,nat2013/netty,WangJunTYTL/netty,zhujingling/netty,alkemist/netty,brennangaunce/netty,mcobrien/netty,hyangtack/netty,andsel/netty,develar/netty,niuxinghua/netty,silvaran/netty,blucas/netty,serioussam/netty,Mounika-Chirukuri/netty,chrisprobst/netty,youprofit/netty,alkemist/netty,moyiguket/netty,smayoorans/netty,fantayeneh/netty,SinaTadayon/netty,wangyikai/netty,f7753/netty,Techcable/netty,tbrooks8/netty,shism/netty,ioanbsu/netty,chanakaudaya/netty,mosoft521/netty,mubarak/netty,Mounika-Chirukuri/netty,cnoldtree/netty,danbev/netty,MediumOne/netty,tempbottle/netty,doom369/netty,fantayeneh/netty,kiril-me/netty,artgon/netty,LuminateWireless/netty,imangry/netty-zh,cnoldtree/netty,WangJunTYTL/netty,nat2013/netty,ichaki5748/netty,wangyikai/netty,johnou/netty,timboudreau/netty,golovnin/netty,gigold/netty,Apache9/netty,yipen9/netty,Kingson4Wu/netty,tbrooks8/netty,jenskordowski/netty,firebase/netty,daschl/netty,joansmith/netty,slandelle/netty,satishsaley/netty,Kalvar/netty,djchen/netty,bob329/netty,jdivy/netty,ioanbsu/netty,qingsong-xu/netty,brennangaunce/netty,golovnin/netty,exinguu/netty,afredlyj/learn-netty,brennangaunce/netty,zhujingling/netty,kjniemi/netty,danbev/netty,ioanbsu/netty,nkhuyu/netty,bryce-anderson/netty,zzcclp/netty,nkhuyu/netty,Kingson4Wu/netty,bigheary/netty,joansmith/netty,hyangtack/netty,maliqq/netty,altihou/netty,SinaTadayon/netty,caoyanwei/netty,chanakaudaya/netty,sverkera/netty,netty/netty,MediumOne/netty,exinguu/netty,AchinthaReemal/netty,caoyanwei/netty,buchgr/netty,fenik17/netty,lznhust/netty,moyiguket/netty,danbev/netty,hgl888/netty,ijuma/netty,serioussam/netty,buchgr/netty,rovarga/netty,netty/netty,carl-mastrangelo/netty,ninja-/netty,louiscryan/netty,golovnin/netty,chinayin/netty,dongjiaqiang/netty,CodingFabian/netty,liuciuse/netty,timboudreau/netty,nadeeshaan/netty,ichaki5748/netty,gerdriesselmann/netty,netty/netty,JungMinu/netty,clebertsuconic/netty,DolphinZhao/netty,castomer/netty,olupotd/netty,ajaysarda/netty,huanyi0723/netty,lukw00/netty,qingsong-xu/netty,DolphinZhao/netty,zxhfirefox/netty,ngocdaothanh/netty,louiscryan/netty,fengjiachun/netty,ninja-/netty,x1957/netty,fenik17/netty,lukehutch/netty,silvaran/netty,sunbeansoft/netty,f7753/netty,fantayeneh/netty,DolphinZhao/netty,mosoft521/netty,yonglehou/netty-1,ejona86/netty,pengzj/netty,idelpivnitskiy/netty,idelpivnitskiy/netty,IBYoung/netty,ioanbsu/netty,louiscryan/netty,danbev/netty,pengzj/netty,maliqq/netty,jchambers/netty,shism/netty,wuyinxian124/netty,moyiguket/netty,lznhust/netty,ijuma/netty,caoyanwei/netty,mcanthony/netty,huanyi0723/netty,xiongzheng/netty,satishsaley/netty,zxhfirefox/netty,DolphinZhao/netty,louxiu/netty,lukehutch/netty,shelsonjava/netty,andsel/netty,qingsong-xu/netty,maliqq/netty,louxiu/netty,ichaki5748/netty,Techcable/netty,mx657649013/netty,ejona86/netty,chinayin/netty,DolphinZhao/netty,hgl888/netty,carl-mastrangelo/netty,sunbeansoft/netty,shelsonjava/netty,WangJunTYTL/netty,mubarak/netty,jongyeol/netty,lukw00/netty,kvr000/netty,drowning/netty,zzcclp/netty,yrcourage/netty,x1957/netty,junjiemars/netty,moyiguket/netty,ninja-/netty,fengjiachun/netty,Squarespace/netty,huanyi0723/netty,IBYoung/netty,jchambers/netty,zhoffice/netty,duqiao/netty,zhoffice/netty,ijuma/netty,xiongzheng/netty,duqiao/netty,yonglehou/netty-1,xiexingguang/netty,afredlyj/learn-netty,gigold/netty,hepin1989/netty,wangyikai/netty,drowning/netty,jdivy/netty,develar/netty,Spikhalskiy/netty,niuxinghua/netty,sja/netty,qingsong-xu/netty,Spikhalskiy/netty,fenik17/netty,smayoorans/netty,yawkat/netty,Spikhalskiy/netty,blademainer/netty,mubarak/netty,pengzj/netty,mosoft521/netty,zzcclp/netty,lukehutch/netty,afredlyj/learn-netty,mosoft521/netty,Kalvar/netty,satishsaley/netty,Squarespace/netty,s-gheldd/netty,huanyi0723/netty,timboudreau/netty,silvaran/netty,dongjiaqiang/netty,LuminateWireless/netty,slandelle/netty,exinguu/netty,ninja-/netty,shuangqiuan/netty,blademainer/netty,wuxiaowei907/netty,jovezhougang/netty,yawkat/netty,lightsocks/netty,xingguang2013/netty,dongjiaqiang/netty,mubarak/netty,sammychen105/netty,kvr000/netty,xiexingguang/netty,slandelle/netty,lugt/netty,ngocdaothanh/netty,xiongzheng/netty,nayato/netty,NiteshKant/netty,ajaysarda/netty,rovarga/netty,Mounika-Chirukuri/netty,clebertsuconic/netty,mcanthony/netty,blucas/netty,bob329/netty,shelsonjava/netty,zzcclp/netty,sammychen105/netty,LuminateWireless/netty,AnselQiao/netty,seetharamireddy540/netty,BrunoColin/netty,sunbeansoft/netty,altihou/netty,artgon/netty,shenguoquan/netty,maliqq/netty,junjiemars/netty,phlizik/netty,olupotd/netty,youprofit/netty,DavidAlphaFox/netty,mcanthony/netty,huuthang1993/netty,huuthang1993/netty,mway08/netty,Kalvar/netty,tempbottle/netty,rovarga/netty,KatsuraKKKK/netty,shism/netty,bigheary/netty,olupotd/netty,codevelop/netty,mosoft521/netty,MediumOne/netty,tbrooks8/netty,unei66/netty,zer0se7en/netty,xiexingguang/netty,duqiao/netty,chrisprobst/netty,liyang1025/netty,unei66/netty,KatsuraKKKK/netty,timboudreau/netty,nmittler/netty,lukw00/netty,carlbai/netty,buchgr/netty,brennangaunce/netty,blademainer/netty,mikkokar/netty,xiongzheng/netty,normanmaurer/netty,yrcourage/netty,dongjiaqiang/netty,johnou/netty,carl-mastrangelo/netty,yawkat/netty,orika/netty,ifesdjeen/netty,danny200309/netty,Alwayswithme/netty,yawkat/netty,wuxiaowei907/netty,Alwayswithme/netty,codevelop/netty,danny200309/netty,SinaTadayon/netty,tbrooks8/netty,jenskordowski/netty,cnoldtree/netty,luyiisme/netty,serioussam/netty,jenskordowski/netty,gerdriesselmann/netty,blademainer/netty,shuangqiuan/netty,artgon/netty,chrisprobst/netty,wuyinxian124/netty,gerdriesselmann/netty,golovnin/netty,ninja-/netty,AchinthaReemal/netty,lukehutch/netty,fenik17/netty,ajaysarda/netty,andsel/netty,timboudreau/netty,imangry/netty-zh,danny200309/netty,zhoffice/netty,AnselQiao/netty,eonezhang/netty,wuxiaowei907/netty,chrisprobst/netty,liyang1025/netty,skyao/netty,mx657649013/netty,caoyanwei/netty,sammychen105/netty,NiteshKant/netty,zxhfirefox/netty,luyiisme/netty,imangry/netty-zh,luyiisme/netty,gerdriesselmann/netty,liuciuse/netty,Scottmitch/netty,maliqq/netty,huuthang1993/netty,chrisprobst/netty,serioussam/netty,skyao/netty,idelpivnitskiy/netty,nmittler/netty,caoyanwei/netty,Apache9/netty,ejona86/netty,normanmaurer/netty,satishsaley/netty,ioanbsu/netty,windie/netty,golovnin/netty,gigold/netty,yipen9/netty,firebase/netty,IBYoung/netty,nayato/netty,lznhust/netty,ijuma/netty,Techcable/netty,jchambers/netty,lugt/netty,sja/netty,normanmaurer/netty,afds/netty,Spikhalskiy/netty,artgon/netty,xingguang2013/netty,IBYoung/netty,jongyeol/netty,woshilaiceshide/netty,doom369/netty,seetharamireddy540/netty,zhujingling/netty,eonezhang/netty,nadeeshaan/netty,carlbai/netty,rovarga/netty,netty/netty,carl-mastrangelo/netty,mx657649013/netty,altihou/netty,wuyinxian124/netty,CodingFabian/netty,blademainer/netty,eincs/netty,normanmaurer/netty,Kingson4Wu/netty,mway08/netty,Scottmitch/netty,Scottmitch/netty,bryce-anderson/netty,sverkera/netty,bryce-anderson/netty,junjiemars/netty,WangJunTYTL/netty,luyiisme/netty,joansmith/netty,djchen/netty,sameira/netty,chinayin/netty,blucas/netty,mikkokar/netty,s-gheldd/netty,liyang1025/netty,cnoldtree/netty,windie/netty,firebase/netty,jovezhougang/netty,mway08/netty,artgon/netty,eincs/netty,wuxiaowei907/netty,danny200309/netty,Techcable/netty,woshilaiceshide/netty,jchambers/netty,yipen9/netty,shuangqiuan/netty,phlizik/netty,alkemist/netty,AchinthaReemal/netty,woshilaiceshide/netty,olupotd/netty,SinaTadayon/netty,Scottmitch/netty,Alwayswithme/netty,MediumOne/netty,shelsonjava/netty,ajaysarda/netty,afds/netty,daschl/netty,JungMinu/netty,chanakaudaya/netty,smayoorans/netty,unei66/netty,unei66/netty,clebertsuconic/netty,AnselQiao/netty,afds/netty,ifesdjeen/netty,satishsaley/netty,mx657649013/netty,dongjiaqiang/netty,silvaran/netty,DavidAlphaFox/netty,ngocdaothanh/netty,idelpivnitskiy/netty,xiongzheng/netty,eincs/netty,cnoldtree/netty,xingguang2013/netty,zer0se7en/netty,exinguu/netty,djchen/netty,fantayeneh/netty,woshilaiceshide/netty,KatsuraKKKK/netty,ijuma/netty,sja/netty,AnselQiao/netty,CodingFabian/netty,fengjiachun/netty,altihou/netty,kiril-me/netty,x1957/netty,s-gheldd/netty,sja/netty,sverkera/netty,mcobrien/netty,ajaysarda/netty,nayato/netty,castomer/netty,ngocdaothanh/netty,SinaTadayon/netty,zxhfirefox/netty,BrunoColin/netty,jongyeol/netty,Kalvar/netty,lukehutch/netty,bigheary/netty,youprofit/netty,mcobrien/netty,zhujingling/netty,windie/netty,yrcourage/netty,drowning/netty,liuciuse/netty,hepin1989/netty,castomer/netty,louxiu/netty,shuangqiuan/netty,youprofit/netty,jovezhougang/netty,danbev/netty,Kalvar/netty,netty/netty,unei66/netty,x1957/netty,wuxiaowei907/netty,luyiisme/netty,kjniemi/netty,exinguu/netty,jenskordowski/netty,balaprasanna/netty,bob329/netty,mx657649013/netty,shenguoquan/netty,carlbai/netty,fantayeneh/netty,WangJunTYTL/netty,doom369/netty,nmittler/netty,chinayin/netty,balaprasanna/netty,andsel/netty,lznhust/netty,bryce-anderson/netty,AchinthaReemal/netty,skyao/netty,shenguoquan/netty,lightsocks/netty,Kingson4Wu/netty,wuyinxian124/netty,gerdriesselmann/netty,carl-mastrangelo/netty,louiscryan/netty,zzcclp/netty,buchgr/netty,f7753/netty,lznhust/netty,mway08/netty,wangyikai/netty,blucas/netty,bryce-anderson/netty,castomer/netty,eincs/netty,nkhuyu/netty,nayato/netty,kjniemi/netty,sameira/netty,jovezhougang/netty,kvr000/netty,sameira/netty,ichaki5748/netty,hgl888/netty,balaprasanna/netty,lightsocks/netty,doom369/netty,Alwayswithme/netty,sunbeansoft/netty,carlbai/netty | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.caliper;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import java.util.Collections;
import java.util.List;
final class StandardVm extends Vm {
@Override public List<String> getVmSpecificOptions(MeasurementType type, Arguments arguments) {
if (!arguments.getCaptureVmLog()) {
return ImmutableList.of();
}
List<String> result = Lists.newArrayList(
"-server", "-dsa", "-da", "-ea:io.netty...",
"-Xms768m", "-Xmx768m", "-XX:MaxDirectMemorySize=768m",
"-XX:+AggressiveOpts", "-XX:+UseBiasedLocking", "-XX:+UseFastAccessorMethods",
"-XX:+UseStringCache", "-XX:+OptimizeStringConcat",
"-XX:+HeapDumpOnOutOfMemoryError", "-Dio.netty.noResourceLeakDetection");
if (type == MeasurementType.TIME) {
Collections.addAll(
result,
"-XX:+PrintCompilation");
} else {
Collections.addAll(
result,
"-verbose:gc",
"-Xbatch",
"-XX:+UseSerialGC",
"-XX:+TieredCompilation");
}
return result;
}
public static String defaultVmName() {
return "java";
}
}
| microbench/src/test/java/com/google/caliper/StandardVm.java | /*
* Copyright 2012 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.caliper;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import java.util.Collections;
import java.util.List;
final class StandardVm extends Vm {
@Override public List<String> getVmSpecificOptions(MeasurementType type, Arguments arguments) {
if (!arguments.getCaptureVmLog()) {
return ImmutableList.of();
}
List<String> result = Lists.newArrayList(
"-server", "-dsa", "-da", "-ea:io.netty...",
"-Xms768m", "-Xmx768m", "-XX:MaxDirectMemorySize=768m",
"-XX:+AggressiveOpts", "-XX:+UseBiasedLocking", "-XX:+UseFastAccessorMethods",
"-XX:+UseStringCache", "-XX:+OptimizeStringConcat",
"-XX:+HeapDumpOnOutOfMemoryError");
if (type == MeasurementType.TIME) {
Collections.addAll(
result,
"-XX:+PrintCompilation");
} else {
Collections.addAll(
result,
"-verbose:gc",
"-Xbatch",
"-XX:+UseSerialGC",
"-XX:+TieredCompilation");
}
return result;
}
public static String defaultVmName() {
return "java";
}
}
| Add io.netty.noResourceLeak option to microbench
| microbench/src/test/java/com/google/caliper/StandardVm.java | Add io.netty.noResourceLeak option to microbench |
|
Java | apache-2.0 | 87efc4d36620dcb2eb060c5b6ec8ea95950b9ac5 | 0 | vestrel00/android-dagger-butterknife-mvp | /*
* Copyright 2017 Vandolf Estrellado
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.vestrel00.daggerbutterknifemvp;
import android.app.Activity;
import android.app.Application;
import javax.inject.Inject;
import dagger.android.AndroidInjector;
import dagger.android.DispatchingAndroidInjector;
import dagger.android.HasActivityInjector;
/**
* The Android {@link Application}.
* <p>
* <b>DEPENDENCY INJECTION</b>
* We could extend {@link dagger.android.DaggerApplication} so we can get the boilerplate
* dagger code for free. However, we want to avoid inheritance (if possible and it is in this case)
* so that we have to option to inherit from something else later on if needed
* (e.g. if we need to override MultidexApplication).
*/
public class App extends Application implements HasActivityInjector {
@Inject
DispatchingAndroidInjector<Activity> activityInjector;
@Override
public void onCreate() {
super.onCreate();
DaggerAppComponent.create().inject(this);
}
@Override
public AndroidInjector<Activity> activityInjector() {
return activityInjector;
}
} | app/src/main/java/com/vestrel00/daggerbutterknifemvp/App.java | /*
* Copyright 2017 Vandolf Estrellado
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.vestrel00.daggerbutterknifemvp;
import android.app.Activity;
import android.app.Application;
import javax.inject.Inject;
import dagger.android.AndroidInjector;
import dagger.android.DispatchingAndroidInjector;
import dagger.android.HasActivityInjector;
/**
* The Android {@link Application}.
*/
public class App extends Application implements HasActivityInjector {
@Inject
DispatchingAndroidInjector<Activity> activityInjector;
@Override
public void onCreate() {
super.onCreate();
DaggerAppComponent.create().inject(this);
}
@Override
public AndroidInjector<Activity> activityInjector() {
return activityInjector;
}
} | Added DaggerApplication mention in App class doc
| app/src/main/java/com/vestrel00/daggerbutterknifemvp/App.java | Added DaggerApplication mention in App class doc |
|
Java | apache-2.0 | 12eef8008092d7772d3951fe13b300c9c0d2088f | 0 | Wikidata/QueryAnalysis,Wikidata/QueryAnalysis,Wikidata/QueryAnalysis,Wikidata/QueryAnalysis,Wikidata/QueryAnalysis | package general;
/*-
* #%L
* sparqlQueryTester
* %%
* Copyright (C) 2016 QueryAnalysis
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import input.InputHandlerParquet;
import input.InputHandlerTSV;
import logging.LoggingHandler;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.UnrecognizedOptionException;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaSparkContext;
import org.openrdf.query.algebra.TupleExpr;
import org.openrdf.query.parser.ParsedQuery;
import org.openrdf.queryrender.sparql.SPARQLQueryRenderer;
import query.JenaQueryHandler;
import query.OpenRDFQueryHandler;
/**
* @author jgonsior
*/
public final class Main
{
/**
* Saves the encountered queryTypes.
*/
public static List<ParsedQuery> queryTypes = Collections.synchronizedList(new ArrayList<ParsedQuery>());
/**
* Define a static logger variable.
*/
private static Logger logger = Logger.getLogger(Main.class);
/**
* Since this is a utility class, it should not be instantiated.
*/
private Main()
{
throw new AssertionError("Instantiating utility class Main");
}
/**
* Selects the files to be processed and specifies the files to write to.
*
* @param args Arguments to specify runtime behavior.
*/
public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException
{
//args = new String[] {"-olt", "-file test/test/test/QueryCntSept", "-n5"};
Options options = new Options();
options.addOption("l", "logging", false, "enables file logging");
options.addOption("j", "jena", false, "uses the Jena SPARQL Parser");
options.addOption("o", "openrdf", false, "uses the OpenRDF SPARQL Parser");
options.addOption("f", "file", true, "defines the input file prefix");
options.addOption("h", "help", false, "displays this help");
options.addOption("t", "tsv", false, "reads from .tsv-files");
options.addOption("p", "parquet", false, "read from .parquet-files");
options.addOption("n", "numberOfThreads", true, "number of used threads, default 1");
//some parameters which can be changed through parameters
//QueryHandler queryHandler = new OpenRDFQueryHandler();
String inputFilePrefix;
String inputFileSuffix = ".tsv";
String queryParserName = "OpenRDF";
Class inputHandlerClass = null;
Class queryHandlerClass = null;
int numberOfThreads = 1;
CommandLineParser parser = new DefaultParser();
CommandLine cmd;
try {
cmd = parser.parse(options, args);
if (cmd.hasOption("help")) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("help", options);
return;
}
if (cmd.hasOption("jena")) {
queryHandlerClass = JenaQueryHandler.class;
queryParserName = "Jena";
}
if (cmd.hasOption("openrdf")) {
queryHandlerClass = OpenRDFQueryHandler.class;
}
if (cmd.hasOption("tsv")) {
inputFileSuffix = ".tsv";
inputHandlerClass = InputHandlerTSV.class;
}
if (cmd.hasOption("parquet")) {
inputFileSuffix = ".parquet";
Logger.getLogger("org").setLevel(Level.WARN);
Logger.getLogger("akka").setLevel(Level.WARN);
SparkConf conf = new SparkConf().setAppName("SPARQLQueryAnalyzer").setMaster("local");
JavaSparkContext sc = new JavaSparkContext(conf);
inputHandlerClass = InputHandlerParquet.class;
}
if (inputHandlerClass == null) {
System.out.println("Please specify which parser to use, either -t for TSV or -p for parquet.");
}
if (cmd.hasOption("file")) {
inputFilePrefix = cmd.getOptionValue("file").trim();
} else {
System.out.println("Please specify at least the file which we should work on using the option '--file PREFIX' or 'f PREFIX'");
return;
}
if (cmd.hasOption("logging")) {
LoggingHandler.initFileLog(queryParserName, inputFilePrefix);
}
if (cmd.hasOption("numberOfThreads")) {
numberOfThreads = Integer.parseInt(cmd.getOptionValue("numberOfThreads"));
}
} catch (UnrecognizedOptionException e) {
System.out.println("Unrecognized commandline option: " + e.getOption());
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("help", options);
return;
} catch (ParseException e) {
System.out.println("There was an error while parsing your command line input. Did you rechecked your syntax before running?");
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("help", options);
return;
}
LoggingHandler.initConsoleLog();
long startTime = System.nanoTime();
ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads);
for (int day = 1; day <= 31; day++) {
String inputFile = inputFilePrefix + String.format("%02d", day) + inputFileSuffix;
Runnable parseOneMonthWorker = new ParseOneMonthWorker(inputFile, inputFilePrefix, inputHandlerClass, queryParserName, queryHandlerClass, day);
executor.execute(parseOneMonthWorker);
}
executor.shutdown();
while (!executor.isTerminated()) {
//wait until all workers are finished
}
String outputFolderName = inputFilePrefix.substring(0, inputFilePrefix.lastIndexOf('/') + 1) + "queryType/queryTypeFiles/";
new File(outputFolderName).mkdir();
SPARQLQueryRenderer renderer = new SPARQLQueryRenderer();
for (int i = 0; i < queryTypes.size(); i++) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(outputFolderName + i + ".queryType"))) {
bw.write(renderer.render(queryTypes.get(i)));
} catch (IOException e) {
logger.error("Could not write the query type " + i + ".", e);
}
catch (Exception e) {
logger.error("Error while rendering query type " + i + ".", e);
}
}
long stopTime = System.nanoTime();
long millis = TimeUnit.MILLISECONDS.convert(stopTime - startTime, TimeUnit.NANOSECONDS);
Date date = new Date(millis);
System.out.println("Finished executing with all threads: " + new SimpleDateFormat("mm-dd HH:mm:ss:SSSSSSS").format(date));
}
}
| src/main/java/general/Main.java | package general;
/*-
* #%L
* sparqlQueryTester
* %%
* Copyright (C) 2016 QueryAnalysis
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import input.InputHandlerParquet;
import input.InputHandlerTSV;
import logging.LoggingHandler;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.UnrecognizedOptionException;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaSparkContext;
import org.openrdf.query.algebra.TupleExpr;
import org.openrdf.query.parser.ParsedQuery;
import org.openrdf.queryrender.sparql.SPARQLQueryRenderer;
import query.JenaQueryHandler;
import query.OpenRDFQueryHandler;
/**
* @author jgonsior
*/
public final class Main
{
/**
* Saves the encountered queryTypes.
*/
public static List<ParsedQuery> queryTypes = Collections.synchronizedList(new ArrayList<ParsedQuery>());
/**
* Define a static logger variable.
*/
private static Logger logger = Logger.getLogger(Main.class);
/**
* Since this is a utility class, it should not be instantiated.
*/
private Main()
{
throw new AssertionError("Instantiating utility class Main");
}
/**
* Selects the files to be processed and specifies the files to write to.
*
* @param args Arguments to specify runtime behavior.
*/
public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException
{
//args = new String[] {"-olt", "-file test/test/test/QueryCntSept", "-n5"};
Options options = new Options();
options.addOption("l", "logging", false, "enables file logging");
options.addOption("j", "jena", false, "uses the Jena SPARQL Parser");
options.addOption("o", "openrdf", false, "uses the OpenRDF SPARQL Parser");
options.addOption("f", "file", true, "defines the input file prefix");
options.addOption("h", "help", false, "displays this help");
options.addOption("t", "tsv", false, "reads from .tsv-files");
options.addOption("p", "parquet", false, "read from .parquet-files");
options.addOption("n", "numberOfThreads", true, "number of used threads, default 1");
//some parameters which can be changed through parameters
//QueryHandler queryHandler = new OpenRDFQueryHandler();
String inputFilePrefix;
String inputFileSuffix = ".tsv";
String queryParserName = "OpenRDF";
Class inputHandlerClass = null;
Class queryHandlerClass = null;
int numberOfThreads = 1;
CommandLineParser parser = new DefaultParser();
CommandLine cmd;
try {
cmd = parser.parse(options, args);
if (cmd.hasOption("help")) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("help", options);
return;
}
if (cmd.hasOption("jena")) {
queryHandlerClass = JenaQueryHandler.class;
queryParserName = "Jena";
}
if (cmd.hasOption("openrdf")) {
queryHandlerClass = OpenRDFQueryHandler.class;
}
if (cmd.hasOption("tsv")) {
inputFileSuffix = ".tsv";
inputHandlerClass = InputHandlerTSV.class;
}
if (cmd.hasOption("parquet")) {
inputFileSuffix = ".parquet";
Logger.getLogger("org").setLevel(Level.WARN);
Logger.getLogger("akka").setLevel(Level.WARN);
SparkConf conf = new SparkConf().setAppName("SPARQLQueryAnalyzer").setMaster("local");
JavaSparkContext sc = new JavaSparkContext(conf);
inputHandlerClass = InputHandlerParquet.class;
}
if (inputHandlerClass == null) {
System.out.println("Please specify which parser to use, either -t for TSV or -p for parquet.");
}
if (cmd.hasOption("file")) {
inputFilePrefix = cmd.getOptionValue("file").trim();
} else {
System.out.println("Please specify at least the file which we should work on using the option '--file PREFIX' or 'f PREFIX'");
return;
}
if (cmd.hasOption("logging")) {
LoggingHandler.initFileLog(queryParserName, inputFilePrefix);
}
if (cmd.hasOption("numberOfThreads")) {
numberOfThreads = Integer.parseInt(cmd.getOptionValue("numberOfThreads"));
}
} catch (UnrecognizedOptionException e) {
System.out.println("Unrecognized commandline option: " + e.getOption());
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("help", options);
return;
} catch (ParseException e) {
System.out.println("There was an error while parsing your command line input. Did you rechecked your syntax before running?");
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("help", options);
return;
}
LoggingHandler.initConsoleLog();
long startTime = System.nanoTime();
ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads);
for (int day = 1; day <= 31; day++) {
String inputFile = inputFilePrefix + String.format("%02d", day) + inputFileSuffix;
Runnable parseOneMonthWorker = new ParseOneMonthWorker(inputFile, inputFilePrefix, inputHandlerClass, queryParserName, queryHandlerClass, day);
executor.execute(parseOneMonthWorker);
}
executor.shutdown();
while (!executor.isTerminated()) {
//wait until all workers are finished
}
String outputFolderName = inputFilePrefix.substring(0, inputFilePrefix.lastIndexOf('/') + 1) + "queryTypes/";
new File(outputFolderName).mkdir();
SPARQLQueryRenderer renderer = new SPARQLQueryRenderer();
for (int i = 0; i < queryTypes.size(); i++) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(outputFolderName + i + ".queryType"))) {
bw.write(renderer.render(queryTypes.get(i)));
} catch (IOException e) {
logger.error("Could not write the query type " + i + ".", e);
}
catch (Exception e) {
logger.error("Error while rendering query type " + i + ".", e);
}
}
long stopTime = System.nanoTime();
long millis = TimeUnit.MILLISECONDS.convert(stopTime - startTime, TimeUnit.NANOSECONDS);
Date date = new Date(millis);
System.out.println("Finished executing with all threads: " + new SimpleDateFormat("mm-dd HH:mm:ss:SSSSSSS").format(date));
}
}
| Update Main.java | src/main/java/general/Main.java | Update Main.java |
|
Java | apache-2.0 | 8a820bb62f3ce97e8c3c3b3ac202210df64d9ed8 | 0 | blstream/AugumentedSzczecin_java,blstream/AugumentedSzczecin_java | package com.bls.mongodb;
import java.net.UnknownHostException;
import javax.inject.Named;
import com.bls.dao.CommonDao;
import com.bls.dao.UserDao;
import com.bls.mongodb.dao.EventMongodbDao;
import com.bls.mongodb.dao.PersonMongodbDao;
import com.bls.mongodb.dao.PoiMongodbDao;
import com.bls.mongodb.dao.UserMongodbDao;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import com.mongodb.DB;
import com.mongodb.MongoClient;
public class MongodbModule extends AbstractModule {
@Override
protected void configure() {
}
@Singleton
@Provides
public DB provideMongodb(final MongodbConfiguration config, final MongoClient mongoClient) throws UnknownHostException {
return mongoClient.getDB(config.getDbname());
}
@Singleton
@Provides
public MongoClient provideMongodbClient(final MongodbConfiguration config) throws UnknownHostException {
return config.buildMongoClient();
}
@Singleton
@Provides
public UserDao provideUserDao(final DB mongodb) {
return new UserMongodbDao(mongodb);
}
@Singleton
@Provides
@Named("poi")
public CommonDao providePoiDao(final DB mongodb) {
return new PoiMongodbDao(mongodb);
}
@Singleton
@Provides
@Named("event")
public CommonDao provideEventDao(final DB mongodb) {
return new EventMongodbDao(mongodb);
}
@Singleton
@Provides
@Named("person")
public CommonDao providePersonDao(final DB mongodb) {
return new PersonMongodbDao(mongodb);
}
}
| mongo/src/main/java/com/bls/mongodb/MongodbModule.java | package com.bls.mongodb;
import java.net.UnknownHostException;
import javax.inject.Named;
import com.bls.dao.CommonDao;
import com.bls.dao.UserDao;
import com.bls.mongodb.dao.EventMongodbDao;
import com.bls.mongodb.dao.PoiMongodbDao;
import com.bls.mongodb.dao.UserMongodbDao;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import com.mongodb.DB;
import com.mongodb.MongoClient;
public class MongodbModule extends AbstractModule {
@Override
protected void configure() {
}
@Singleton
@Provides
public DB provideMongodb(final MongodbConfiguration config, final MongoClient mongoClient) throws UnknownHostException {
return mongoClient.getDB(config.getDbname());
}
@Singleton
@Provides
public MongoClient provideMongodbClient(final MongodbConfiguration config) throws UnknownHostException {
return config.buildMongoClient();
}
@Singleton
@Provides
public UserDao provideUserDao(final DB mongodb) {
return new UserMongodbDao(mongodb);
}
@Singleton
@Provides
@Named("poi")
public CommonDao providePoiDao(final DB mongodb) {
return new PoiMongodbDao(mongodb);
}
@Singleton
@Provides
@Named("event")
public CommonDao provideEventDao(final DB mongodb) {
return new EventMongodbDao(mongodb);
}
}
| Added Person provider
| mongo/src/main/java/com/bls/mongodb/MongodbModule.java | Added Person provider |
|
Java | apache-2.0 | 6d9f7450a9a4a22868aadb7bab63080b5c08f69a | 0 | ptrd/jmeter-plugins,Sausageo/jmeter-plugins,Sausageo/jmeter-plugins,Sausageo/jmeter-plugins,ptrd/jmeter-plugins,Sausageo/jmeter-plugins,Sausageo/jmeter-plugins,ptrd/jmeter-plugins,ptrd/jmeter-plugins,ptrd/jmeter-plugins | package kg.apc.jmeter;
import javax.swing.BorderFactory;
import org.apache.jmeter.gui.util.VerticalPanel;
import java.awt.Component;
import java.nio.ByteBuffer;
import javax.swing.JLabel;
import javax.swing.JPanel;
import org.apache.jmeter.gui.util.PowerTableModel;
import org.apache.jmeter.testelement.property.CollectionProperty;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author undera
*/
public class JMeterPluginsUtilsTest {
public JMeterPluginsUtilsTest() {
}
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of prefixLabel method, of class JMeterPluginsUtils.
*/
@Test
public void testPrefixLabel() {
System.out.println("prefixLabel");
String string = "TEST";
String result = JMeterPluginsUtils.prefixLabel(string);
assertTrue(result.indexOf(string) != -1);
}
/**
* Test of getStackTrace method, of class JMeterPluginsUtils.
*/
@Test
public void testGetStackTrace() {
System.out.println("getStackTrace");
Exception ex = new Exception();
String result = JMeterPluginsUtils.getStackTrace(ex);
assertTrue(result.length() > 0);
}
/**
* Test of byteBufferToString method, of class JMeterPluginsUtils.
*/
@Test
public void testByteBufferToString() {
System.out.println("byteBufferToString");
ByteBuffer buf = ByteBuffer.wrap("My Test".getBytes());
String expResult = "My Test";
String result = JMeterPluginsUtils.byteBufferToString(buf);
assertEquals(expResult, result);
}
@Test
public void testByteBufferToString2() {
System.out.println("byteBufferToString2");
ByteBuffer buf = ByteBuffer.allocateDirect(2014);
buf.put("My Test".getBytes());
buf.flip();
String expResult = "My Test";
String result = JMeterPluginsUtils.byteBufferToString(buf);
assertEquals(expResult, result);
}
/**
* Test of replaceRNT method, of class JMeterPluginsUtils.
*/
@Test
public void testReplaceRNT() {
System.out.println("replaceRNT");
assertEquals("\t", JMeterPluginsUtils.replaceRNT("\\t"));
assertEquals("\t\t", JMeterPluginsUtils.replaceRNT("\\t\\t"));
assertEquals("-\t-", JMeterPluginsUtils.replaceRNT("-\\t-"));
System.out.println("\\\\t");
assertEquals("\\t", JMeterPluginsUtils.replaceRNT("\\\\t"));
assertEquals("\t\n\r", JMeterPluginsUtils.replaceRNT("\\t\\n\\r"));
assertEquals("\t\n\n\r", JMeterPluginsUtils.replaceRNT("\\t\\n\\n\\r"));
}
/**
* Test of getWikiLinkText method, of class JMeterPluginsUtils.
*/
@Test
public void testGetWikiLinkText() {
System.out.println("getWikiLinkText");
String wikiPage = "test";
String result = JMeterPluginsUtils.getWikiLinkText(wikiPage);
assertTrue(result.endsWith(wikiPage) || java.awt.Desktop.isDesktopSupported());
}
/**
* Test of openInBrowser method, of class JMeterPluginsUtils.
*/
@Test
public void testOpenInBrowser() {
System.out.println("openInBrowser");
// don't do this, because of odd window popups
// JMeterPluginsUtils.openInBrowser("http://code.google.com/p/jmeter-plugins/");
}
/**
* Test of addHelpLinkToPanel method, of class JMeterPluginsUtils.
*/
@Test
public void testAddHelpLinkToPanel() {
System.out.println("addHelpLinkToPanel");
VerticalPanel titlePanel = new VerticalPanel();
titlePanel.add(new JLabel("title"));
VerticalPanel contentPanel = new VerticalPanel();
contentPanel.setBorder(BorderFactory.createEtchedBorder());
contentPanel.add(new JPanel());
contentPanel.add(new JPanel());
contentPanel.setName("THIS");
titlePanel.add(contentPanel);
String helpPage = "";
Component result = JMeterPluginsUtils.addHelpLinkToPanel(titlePanel, helpPage);
assertNotNull(result);
}
/**
* Test of getSecondsForShort method, of class JMeterPluginsUtils.
*/
@Test
public void testGetSecondsForShortString() {
System.out.println("getSecondsForShort");
assertEquals(105, JMeterPluginsUtils.getSecondsForShortString("105"));
assertEquals(105, JMeterPluginsUtils.getSecondsForShortString("105s"));
assertEquals(60 * 15, JMeterPluginsUtils.getSecondsForShortString("15m"));
assertEquals(60 * 60 * 4, JMeterPluginsUtils.getSecondsForShortString("4h"));
assertEquals(104025, JMeterPluginsUtils.getSecondsForShortString("27h103m645s"));
}
/**
* Test of byteBufferToByteArray method, of class JMeterPluginsUtils.
*/
@Test
public void testByteBufferToByteArray() {
System.out.println("byteBufferToByteArray");
ByteBuffer buf = ByteBuffer.wrap("test".getBytes());
byte[] result = JMeterPluginsUtils.byteBufferToByteArray(buf);
assertEquals(4, result.length);
}
private PowerTableModel getTestModel() {
String[] headers = {"col1", "col2"};
Class[] classes = {String.class, String.class};
PowerTableModel model = new PowerTableModel(headers, classes);
String[] row1 = {"1", "2"};
String[] row2 = {"3", "4"};
model.addRow(row1);
model.addRow(row2);
return model;
}
/**
* Test of tableModelRowsToCollectionProperty method, of class JMeterPluginsUtils.
*/
@Test
public void testTableModelRowsToCollectionProperty() {
System.out.println("tableModelRowsToCollectionProperty");
PowerTableModel model = getTestModel();
String propname = "prop";
CollectionProperty result = JMeterPluginsUtils.tableModelRowsToCollectionProperty(model, propname);
assertEquals(2, result.size());
assertEquals("[[1, 2], [3, 4]]", result.toString());
}
/**
* Test of collectionPropertyToTableModelRows method, of class JMeterPluginsUtils.
*/
@Test
public void testCollectionPropertyToTableModelRows() {
System.out.println("collectionPropertyToTableModelRows");
String propname = "prop";
PowerTableModel modelSrc = getTestModel();
CollectionProperty propExp = JMeterPluginsUtils.tableModelRowsToCollectionProperty(modelSrc, propname);
PowerTableModel modelDst = getTestModel();
modelDst.clearData();
JMeterPluginsUtils.collectionPropertyToTableModelRows(propExp, modelDst);
CollectionProperty propRes = JMeterPluginsUtils.tableModelRowsToCollectionProperty(modelDst, propname);
assertEquals(propExp.toString(), propRes.toString());
}
/**
* Test of tableModelRowsToCollectionPropertyEval method, of class JMeterPluginsUtils.
*/
@Test
public void testTableModelRowsToCollectionPropertyEval() {
System.out.println("tableModelRowsToCollectionPropertyEval");
PowerTableModel model = getTestModel();
String propname = "prop";
CollectionProperty result = JMeterPluginsUtils.tableModelRowsToCollectionPropertyEval(model, propname);
assertEquals(2, result.size());
assertEquals("[[1, 2], [3, 4]]", result.toString());
}
/**
* Test of tableModelColsToCollectionProperty method, of class JMeterPluginsUtils.
*/
@Test
public void testTableModelColsToCollectionProperty() {
System.out.println("tableModelColsToCollectionProperty");
PowerTableModel model = getTestModel();
String propname = "";
CollectionProperty result = JMeterPluginsUtils.tableModelColsToCollectionProperty(model, propname);
assertEquals("[[1, 3], [2, 4]]", result.toString());
}
/**
* Test of collectionPropertyToTableModelCols method, of class JMeterPluginsUtils.
*/
@Test
public void testCollectionPropertyToTableModelCols() {
System.out.println("collectionPropertyToTableModelCols");
CollectionProperty prop = JMeterPluginsUtils.tableModelColsToCollectionProperty(getTestModel(), "");
PowerTableModel model = getTestModel();
JMeterPluginsUtils.collectionPropertyToTableModelCols(prop, model);
assertEquals(prop.size(), model.getColumnCount());
}
/**
* Test of getFloatFromString method, of class JMeterPluginsUtils.
*/
@Test
public void testGetFloatFromString() {
System.out.println("getFloatFromString");
String stringValue = "5.3";
float defaultValue = 1.0F;
float expResult = 5.3F;
float result = JMeterPluginsUtils.getFloatFromString(stringValue, defaultValue);
assertEquals(expResult, result, 0.0);
}
/**
* Test of collectionPropertyToTableModelRows method, of class JMeterPluginsUtils.
*/
@Test
public void testCollectionPropertyToTableModelRows_CollectionProperty_PowerTableModel() {
System.out.println("collectionPropertyToTableModelRows");
CollectionProperty prop = JMeterPluginsUtils.tableModelColsToCollectionProperty(getTestModel(), "");
PowerTableModel model = getTestModel();
JMeterPluginsUtils.collectionPropertyToTableModelRows(prop, model);
}
/**
* Test of collectionPropertyToTableModelRows method, of class JMeterPluginsUtils.
*/
@Test
public void testCollectionPropertyToTableModelRows_3args() {
System.out.println("collectionPropertyToTableModelRows");
CollectionProperty prop = JMeterPluginsUtils.tableModelColsToCollectionProperty(getTestModel(), "");
PowerTableModel model = getTestModel();
Class[] columnClasses = {String.class, String.class};
JMeterPluginsUtils.collectionPropertyToTableModelRows(prop, model, columnClasses);
}
}
| plugins/test/kg/apc/jmeter/JMeterPluginsUtilsTest.java | package kg.apc.jmeter;
import javax.swing.BorderFactory;
import org.apache.jmeter.gui.util.VerticalPanel;
import java.awt.Component;
import java.nio.ByteBuffer;
import javax.swing.JLabel;
import javax.swing.JPanel;
import org.apache.jmeter.gui.util.PowerTableModel;
import org.apache.jmeter.testelement.property.CollectionProperty;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author undera
*/
public class JMeterPluginsUtilsTest {
public JMeterPluginsUtilsTest() {
}
@BeforeClass
public static void setUpClass() throws Exception {
}
@AfterClass
public static void tearDownClass() throws Exception {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of prefixLabel method, of class JMeterPluginsUtils.
*/
@Test
public void testPrefixLabel() {
System.out.println("prefixLabel");
String string = "TEST";
String result = JMeterPluginsUtils.prefixLabel(string);
assertTrue(result.indexOf(string) != -1);
}
/**
* Test of getStackTrace method, of class JMeterPluginsUtils.
*/
@Test
public void testGetStackTrace() {
System.out.println("getStackTrace");
Exception ex = new Exception();
String result = JMeterPluginsUtils.getStackTrace(ex);
assertTrue(result.length() > 0);
}
/**
* Test of byteBufferToString method, of class JMeterPluginsUtils.
*/
@Test
public void testByteBufferToString() {
System.out.println("byteBufferToString");
ByteBuffer buf = ByteBuffer.wrap("My Test".getBytes());
String expResult = "My Test";
String result = JMeterPluginsUtils.byteBufferToString(buf);
assertEquals(expResult, result);
}
@Test
public void testByteBufferToString2() {
System.out.println("byteBufferToString2");
ByteBuffer buf = ByteBuffer.allocateDirect(2014);
buf.put("My Test".getBytes());
buf.flip();
String expResult = "My Test";
String result = JMeterPluginsUtils.byteBufferToString(buf);
assertEquals(expResult, result);
}
/**
* Test of replaceRNT method, of class JMeterPluginsUtils.
*/
@Test
public void testReplaceRNT() {
System.out.println("replaceRNT");
assertEquals("\t", JMeterPluginsUtils.replaceRNT("\\t"));
assertEquals("\t\t", JMeterPluginsUtils.replaceRNT("\\t\\t"));
assertEquals("-\t-", JMeterPluginsUtils.replaceRNT("-\\t-"));
System.out.println("\\\\t");
assertEquals("\\t", JMeterPluginsUtils.replaceRNT("\\\\t"));
assertEquals("\t\n\r", JMeterPluginsUtils.replaceRNT("\\t\\n\\r"));
assertEquals("\t\n\n\r", JMeterPluginsUtils.replaceRNT("\\t\\n\\n\\r"));
}
/**
* Test of getWikiLinkText method, of class JMeterPluginsUtils.
*/
@Test
public void testGetWikiLinkText() {
System.out.println("getWikiLinkText");
String wikiPage = "test";
String result = JMeterPluginsUtils.getWikiLinkText(wikiPage);
assertTrue(result.endsWith(wikiPage) || java.awt.Desktop.isDesktopSupported());
}
/**
* Test of openInBrowser method, of class JMeterPluginsUtils.
*/
@Test
public void testOpenInBrowser() {
System.out.println("openInBrowser");
// don't do this, because of odd window popups
// JMeterPluginsUtils.openInBrowser("http://code.google.com/p/jmeter-plugins/");
}
/**
* Test of addHelpLinkToPanel method, of class JMeterPluginsUtils.
*/
@Test
public void testAddHelpLinkToPanel() {
System.out.println("addHelpLinkToPanel");
VerticalPanel titlePanel = new VerticalPanel();
titlePanel.add(new JLabel("title"));
VerticalPanel contentPanel = new VerticalPanel();
contentPanel.setBorder(BorderFactory.createEtchedBorder());
contentPanel.add(new JPanel());
contentPanel.add(new JPanel());
contentPanel.setName("THIS");
titlePanel.add(contentPanel);
String helpPage = "";
Component result = JMeterPluginsUtils.addHelpLinkToPanel(titlePanel, helpPage);
assertNotNull(result);
}
/**
* Test of getSecondsForShort method, of class JMeterPluginsUtils.
*/
@Test
public void testGetSecondsForShortString() {
System.out.println("getSecondsForShort");
assertEquals(105, JMeterPluginsUtils.getSecondsForShortString("105"));
assertEquals(105, JMeterPluginsUtils.getSecondsForShortString("105s"));
assertEquals(60 * 15, JMeterPluginsUtils.getSecondsForShortString("15m"));
assertEquals(60 * 60 * 4, JMeterPluginsUtils.getSecondsForShortString("4h"));
assertEquals(104025, JMeterPluginsUtils.getSecondsForShortString("27h103m645s"));
}
/**
* Test of byteBufferToByteArray method, of class JMeterPluginsUtils.
*/
@Test
public void testByteBufferToByteArray() {
System.out.println("byteBufferToByteArray");
ByteBuffer buf = ByteBuffer.wrap("test".getBytes());
byte[] result = JMeterPluginsUtils.byteBufferToByteArray(buf);
assertEquals(4, result.length);
}
private PowerTableModel getTestModel() {
String[] headers = {"col1", "col2"};
Class[] classes = {String.class, String.class};
PowerTableModel model = new PowerTableModel(headers, classes);
String[] row1 = {"1", "2"};
String[] row2 = {"3", "4"};
model.addRow(row1);
model.addRow(row2);
return model;
}
/**
* Test of tableModelRowsToCollectionProperty method, of class JMeterPluginsUtils.
*/
@Test
public void testTableModelRowsToCollectionProperty() {
System.out.println("tableModelRowsToCollectionProperty");
PowerTableModel model = getTestModel();
String propname = "prop";
CollectionProperty result = JMeterPluginsUtils.tableModelRowsToCollectionProperty(model, propname);
assertEquals(2, result.size());
assertEquals("[[1, 2], [3, 4]]", result.toString());
}
/**
* Test of collectionPropertyToTableModelRows method, of class JMeterPluginsUtils.
*/
@Test
public void testCollectionPropertyToTableModelRows() {
System.out.println("collectionPropertyToTableModelRows");
String propname = "prop";
PowerTableModel modelSrc = getTestModel();
CollectionProperty propExp = JMeterPluginsUtils.tableModelRowsToCollectionProperty(modelSrc, propname);
PowerTableModel modelDst = getTestModel();
modelDst.clearData();
JMeterPluginsUtils.collectionPropertyToTableModelRows(propExp, modelDst);
CollectionProperty propRes = JMeterPluginsUtils.tableModelRowsToCollectionProperty(modelDst, propname);
assertEquals(propExp.toString(), propRes.toString());
}
/**
* Test of tableModelRowsToCollectionPropertyEval method, of class JMeterPluginsUtils.
*/
@Test
public void testTableModelRowsToCollectionPropertyEval() {
System.out.println("tableModelRowsToCollectionPropertyEval");
PowerTableModel model = getTestModel();
String propname = "prop";
CollectionProperty result = JMeterPluginsUtils.tableModelRowsToCollectionPropertyEval(model, propname);
assertEquals(2, result.size());
assertEquals("[[1, 2], [3, 4]]", result.toString());
}
/**
* Test of tableModelColsToCollectionProperty method, of class JMeterPluginsUtils.
*/
@Test
public void testTableModelColsToCollectionProperty() {
System.out.println("tableModelColsToCollectionProperty");
PowerTableModel model = getTestModel();
String propname = "";
CollectionProperty result = JMeterPluginsUtils.tableModelColsToCollectionProperty(model, propname);
assertEquals("[[1, 3], [2, 4]]", result.toString());
}
/**
* Test of collectionPropertyToTableModelCols method, of class JMeterPluginsUtils.
*/
@Test
public void testCollectionPropertyToTableModelCols() {
System.out.println("collectionPropertyToTableModelCols");
CollectionProperty prop = JMeterPluginsUtils.tableModelColsToCollectionProperty(getTestModel(), "");
PowerTableModel model = getTestModel();
JMeterPluginsUtils.collectionPropertyToTableModelCols(prop, model);
assertEquals(prop.size(), model.getColumnCount());
}
/**
* Test of getFloatFromString method, of class JMeterPluginsUtils.
*/
@Test
public void testGetFloatFromString() {
System.out.println("getFloatFromString");
String stringValue = "5.3";
float defaultValue = 1.0F;
float expResult = 5.3F;
float result = JMeterPluginsUtils.getFloatFromString(stringValue, defaultValue);
assertEquals(expResult, result, 0.0);
}
}
| Add DbMon tests related to PluginUtils additions
| plugins/test/kg/apc/jmeter/JMeterPluginsUtilsTest.java | Add DbMon tests related to PluginUtils additions |
|
Java | apache-2.0 | 816a1fd80e95a31a9e7dc8c53d732c06041b49ba | 0 | torakiki/sambox,torakiki/sambox | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sejda.sambox.pdmodel;
import static java.util.Optional.ofNullable;
import static org.sejda.commons.util.RequireUtils.requireNotBlank;
import static org.sejda.io.CountingWritableByteChannel.from;
import static org.sejda.sambox.cos.DirectCOSObject.asDirectObject;
import static org.sejda.sambox.util.SpecVersionUtils.V1_4;
import static org.sejda.sambox.util.SpecVersionUtils.isAtLeast;
import java.awt.Point;
import java.awt.image.DataBuffer;
import java.awt.image.Raster;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Calendar;
import java.util.HashSet;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import org.apache.fontbox.ttf.TrueTypeFont;
import org.sejda.commons.util.IOUtils;
import org.sejda.io.CountingWritableByteChannel;
import org.sejda.io.SeekableSources;
import org.sejda.sambox.SAMBox;
import org.sejda.sambox.cos.COSArray;
import org.sejda.sambox.cos.COSBase;
import org.sejda.sambox.cos.COSDictionary;
import org.sejda.sambox.cos.COSDocument;
import org.sejda.sambox.cos.COSInteger;
import org.sejda.sambox.cos.COSName;
import org.sejda.sambox.cos.COSNumber;
import org.sejda.sambox.cos.COSString;
import org.sejda.sambox.cos.DirectCOSObject;
import org.sejda.sambox.encryption.EncryptionContext;
import org.sejda.sambox.encryption.MessageDigests;
import org.sejda.sambox.encryption.StandardSecurity;
import org.sejda.sambox.input.PDFParser;
import org.sejda.sambox.output.PDDocumentWriter;
import org.sejda.sambox.output.WriteOption;
import org.sejda.sambox.pdmodel.common.PDStream;
import org.sejda.sambox.pdmodel.encryption.AccessPermission;
import org.sejda.sambox.pdmodel.encryption.PDEncryption;
import org.sejda.sambox.pdmodel.encryption.SecurityHandler;
import org.sejda.sambox.pdmodel.font.Subsettable;
import org.sejda.sambox.pdmodel.graphics.color.PDDeviceRGB;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This is the in-memory representation of the PDF document.
*
* @author Ben Litchfield
*/
public class PDDocument implements Closeable
{
private static final Logger LOG = LoggerFactory.getLogger(PDDocument.class);
/**
* avoid concurrency issues with PDDeviceRGB and deadlock in COSNumber/COSInteger
*/
static
{
try
{
PDDeviceRGB.INSTANCE.toRGBImage(
Raster.createBandedRaster(DataBuffer.TYPE_BYTE, 1, 1, 3, new Point(0, 0)));
}
catch (IOException e)
{
LOG.warn("This shouldn't happen", e);
}
try
{
// TODO remove this and deprecated COSNumber statics in 3.0
COSNumber.get("0");
COSNumber.get("1");
}
catch (IOException ex)
{
//
}
}
private final COSDocument document;
private PDDocumentCatalog documentCatalog;
private SecurityHandler securityHandler;
private boolean open = true;
private OnClose onClose = () -> LOG.debug("Closing document");
private ResourceCache resourceCache = new DefaultResourceCache();
// fonts to subset before saving
private final Set<Subsettable> fontsToSubset = new HashSet<>();
public PDDocument()
{
document = new COSDocument();
document.getCatalog().setItem(COSName.VERSION, COSName.getPDFName("1.4"));
COSDictionary pages = new COSDictionary();
document.getCatalog().setItem(COSName.PAGES, pages);
pages.setItem(COSName.TYPE, COSName.PAGES);
pages.setItem(COSName.KIDS, new COSArray());
pages.setItem(COSName.COUNT, COSInteger.ZERO);
}
/**
* Constructor that uses an existing document. The COSDocument that is passed in must be valid.
*
* @param document The COSDocument that this document wraps.
*/
public PDDocument(COSDocument document)
{
this(document, null);
}
/**
* Constructor that uses an existing document. The COSDocument that is passed in must be valid.
*
* @param document The COSDocument that this document wraps.
* @param securityHandler
*/
public PDDocument(COSDocument document, SecurityHandler securityHandler)
{
this.document = document;
this.securityHandler = securityHandler;
}
/**
* This will add a page to the document. This is a convenience method, that will add the page to the root of the
* hierarchy and set the parent of the page to the root.
*
* @param page The page to add to the document.
*/
public void addPage(PDPage page)
{
requireOpen();
getPages().add(page);
}
/**
* Remove the page from the document.
*
* @param page The page to remove from the document.
*/
public void removePage(PDPage page)
{
requireOpen();
getPages().remove(page);
}
/**
* Remove the page from the document.
*
* @param pageNumber 0 based index to page number.
*/
public void removePage(int pageNumber)
{
requireOpen();
getPages().remove(pageNumber);
}
/**
* This will import and copy the contents from another location. Currently the content stream is stored in a scratch
* file. The scratch file is associated with the document. If you are adding a page to this document from another
* document and want to copy the contents to this document's scratch file then use this method otherwise just use
* the addPage method.
*
* @param page The page to import.
* @return The page that was imported.
*
*/
public PDPage importPage(PDPage page)
{
requireOpen();
PDPage importedPage = new PDPage(page.getCOSObject().duplicate());
InputStream in = null;
try
{
in = page.getContents();
if (in != null)
{
PDStream dest = new PDStream(in, COSName.FLATE_DECODE);
importedPage.setContents(dest);
}
addPage(importedPage);
}
catch (IOException e)
{
IOUtils.closeQuietly(in);
}
return importedPage;
}
/**
* @return The document that this layer sits on top of.
*/
public COSDocument getDocument()
{
return document;
}
/**
* This will get the document info dictionary. This is guaranteed to not return null.
*
* @return The documents /Info dictionary
*/
public PDDocumentInformation getDocumentInformation()
{
COSDictionary infoDic = document.getTrailer().getCOSObject()
.getDictionaryObject(COSName.INFO, COSDictionary.class);
if (infoDic == null)
{
infoDic = new COSDictionary();
document.getTrailer().getCOSObject().setItem(COSName.INFO, infoDic);
}
return new PDDocumentInformation(infoDic);
}
/**
* This will set the document information for this document.
*
* @param info The updated document information.
*/
public void setDocumentInformation(PDDocumentInformation documentInformation)
{
requireOpen();
document.getTrailer().getCOSObject().setItem(COSName.INFO,
documentInformation.getCOSObject());
}
/**
* This will get the document CATALOG. This is guaranteed to not return null.
*
* @return The documents /Root dictionary
*/
public PDDocumentCatalog getDocumentCatalog()
{
if (documentCatalog == null)
{
documentCatalog = new PDDocumentCatalog(this, document.getCatalog());
}
return documentCatalog;
}
/**
* @return true If this document is encrypted.
*/
public boolean isEncrypted()
{
return document.isEncrypted();
}
/**
* This will get the encryption dictionary for this document.
*
* @return The encryption dictionary
*/
public PDEncryption getEncryption()
{
if (isEncrypted())
{
return new PDEncryption(document.getEncryptionDictionary());
}
return new PDEncryption();
}
/**
* For internal PDFBox use when creating PDF documents: register a TrueTypeFont to make sure it is closed when the
* PDDocument is closed to avoid memory leaks. Users don't have to call this method, it is done by the appropriate
* PDFont classes.
*
* @param ttf
*/
public void registerTrueTypeFontForClosing(TrueTypeFont ttf)
{
onClose.andThen(() -> IOUtils.closeQuietly(ttf));
}
/**
* @return the list of fonts which will be subset before the document is saved.
*/
public Set<Subsettable> getFontsToSubset()
{
return fontsToSubset;
}
/**
* @param pageIndex the page index
* @return the page at the given zero based index.
*/
public PDPage getPage(int pageIndex)
{
return getDocumentCatalog().getPages().get(pageIndex);
}
public PDPageTree getPages()
{
return getDocumentCatalog().getPages();
}
/**
* @return The total number of pages in the PDF document.
*/
public int getNumberOfPages()
{
return getDocumentCatalog().getPages().getCount();
}
/**
* Returns the access permissions granted when the document was decrypted. If the document was not decrypted this
* method returns the access permission for a document owner (ie can do everything). The returned object is in read
* only mode so that permissions cannot be changed. Methods providing access to content should rely on this object
* to verify if the current user is allowed to proceed.
*
* @return the access permissions for the current user on the document.
*/
public AccessPermission getCurrentAccessPermission()
{
return ofNullable(securityHandler).map(s -> s.getCurrentAccessPermission())
.orElseGet(AccessPermission::getOwnerAccessPermission);
}
public SecurityHandler getSecurityHandler()
{
return securityHandler;
}
/**
* @return The version of the PDF specification to which the document conforms.
*/
public String getVersion()
{
String headerVersion = getDocument().getHeaderVersion();
if (isAtLeast(headerVersion, V1_4))
{
return ofNullable(getDocumentCatalog().getVersion())
.filter(catalogVersion -> (catalogVersion.compareTo(headerVersion) > 0))
.orElse(headerVersion);
}
return headerVersion;
}
/**
* Sets the version of the PDF specification to which the document conforms. Downgrading of the document version is
* not allowed.
*
* @param newVersion the new PDF version
*
*/
public void setVersion(String newVersion)
{
requireOpen();
requireNotBlank(newVersion, "Spec version cannot be blank");
int compare = getVersion().compareTo(newVersion);
if (compare > 0)
{
LOG.info("Spec version downgrade not allowed");
}
else if (compare < 0)
{
if (isAtLeast(newVersion, V1_4))
{
getDocumentCatalog().setVersion(newVersion);
}
getDocument().setHeaderVersion(newVersion);
}
}
/**
* If the document is not at the given version or above, it sets the version of the PDF specification to which the
* document conforms.
*
* @param version
*/
public void requireMinVersion(String version)
{
if (!isAtLeast(getVersion(), version))
{
LOG.debug("Minimum spec version required is {}", version);
setVersion(version);
}
}
/**
* Sets an action to be performed right before this {@link PDDocument} is closed.
*
* @param onClose
*/
public void setOnCloseAction(OnClose onClose)
{
requireOpen();
this.onClose = onClose.andThen(this.onClose);
}
private void requireOpen() throws IllegalStateException
{
if (!isOpen())
{
throw new IllegalStateException("The document is closed");
}
}
/**
* Generates file identifier as defined in the chap 14.4 PDF 32000-1:2008 and sets it as first and second value for
* the ID array in the document trailer.
*
* @param md5Update
* @param encContext
*/
private void generateFileIdentifier(byte[] md5Update, Optional<EncryptionContext> encContext)
{
COSString id = generateFileIdentifier(md5Update);
encContext.ifPresent(c -> c.documentId(id.getBytes()));
DirectCOSObject directId = asDirectObject(id);
getDocument().getTrailer().getCOSObject().setItem(COSName.ID,
asDirectObject(new COSArray(directId, directId)));
}
/**
*
* @param md5Update
* @return a newly generated ID based on the input bytes, current timestamp and some other information, to be used
* as value of the ID array in the document trailer.
*/
public COSString generateFileIdentifier(byte[] md5Update)
{
MessageDigest md5 = MessageDigests.md5();
md5.update(Long.toString(System.currentTimeMillis()).getBytes(StandardCharsets.ISO_8859_1));
md5.update(md5Update);
ofNullable(getDocument().getTrailer().getCOSObject().getDictionaryObject(COSName.INFO,
COSDictionary.class)).ifPresent(d -> {
for (COSBase current : d.getValues())
{
md5.update(current.toString().getBytes(StandardCharsets.ISO_8859_1));
}
});
COSString retVal = COSString.newInstance(md5.digest());
retVal.setForceHexForm(true);
retVal.encryptable(false);
return retVal;
}
/**
* Writes the document to the given {@link File}. The document is closed once written.
*
* @see PDDocument#close()
* @param file
* @param options
* @throws IOException
*/
public void writeTo(File file, WriteOption... options) throws IOException
{
writeTo(from(file), null, options);
}
/**
* Writes the document to the file corresponding the given file name. The document is closed once written.
*
* @see PDDocument#close()
* @param filename
* @param options
* @throws IOException
*/
public void writeTo(String filename, WriteOption... options) throws IOException
{
writeTo(from(filename), null, options);
}
/**
* Writes the document to the given {@link WritableByteChannel}. The document is closed once written.
*
* @see PDDocument#close()
* @param channel
* @param options
* @throws IOException
*/
public void writeTo(WritableByteChannel channel, WriteOption... options) throws IOException
{
writeTo(from(channel), null, options);
}
/**
* Writes the document to the given {@link OutputStream}. The document is closed once written.
*
* @see PDDocument#close()
* @param out
* @param options
* @throws IOException
*/
public void writeTo(OutputStream out, WriteOption... options) throws IOException
{
writeTo(from(out), null, options);
}
/**
* Writes the document to the given {@link File} encrypting it using the given security. The document is closed once
* written.
*
* @see PDDocument#close()
* @param file
* @param security
* @param options
* @throws IOException
*/
public void writeTo(File file, StandardSecurity security, WriteOption... options)
throws IOException
{
writeTo(from(file), security, options);
}
/**
* Writes the document to the file corresponding the given file name encrypting it using the given security. The
* document is closed once written.
*
* @see PDDocument#close()
* @param filename
* @param security
* @param options
* @throws IOException
*/
public void writeTo(String filename, StandardSecurity security, WriteOption... options)
throws IOException
{
writeTo(from(filename), security, options);
}
/**
* Writes the document to the given {@link WritableByteChannel} encrypting it using the given security. The document
* is closed once written.
*
* @see PDDocument#close()
* @param channel
* @param security
* @param options
* @throws IOException
*/
public void writeTo(WritableByteChannel channel, StandardSecurity security,
WriteOption... options) throws IOException
{
writeTo(from(channel), security, options);
}
/**
* Writes the document to the given {@link OutputStream} encrypting it using the given security. The document is
* closed once written.
*
* @see PDDocument#close()
* @param out
* @param security
* @param options
* @throws IOException
*/
public void writeTo(OutputStream out, StandardSecurity security, WriteOption... options)
throws IOException
{
writeTo(from(out), security, options);
}
private void writeTo(CountingWritableByteChannel output, StandardSecurity security,
WriteOption... options) throws IOException
{
requireOpen();
getDocumentInformation().setProducer(SAMBox.PRODUCER);
getDocumentInformation().setModificationDate(Calendar.getInstance());
for (Subsettable font : fontsToSubset)
{
font.subset();
}
fontsToSubset.clear();
Optional<EncryptionContext> encryptionContext = ofNullable(
ofNullable(security).map(EncryptionContext::new).orElse(null));
generateFileIdentifier(output.toString().getBytes(StandardCharsets.ISO_8859_1),
encryptionContext);
try (PDDocumentWriter writer = new PDDocumentWriter(output, encryptionContext, options))
{
writer.write(this);
}
finally
{
IOUtils.close(this);
}
}
/**
* @return true if the {@link PDDocument} is open
*/
public boolean isOpen()
{
return this.open;
}
/**
* Closes the {@link PDDocument} executing the set onClose action. Once closed the document is pretty much unusable
* since most of the methods requires an open document.
*
* @see PDDocument#setOnCloseAction(OnClose)
*/
@Override
public void close() throws IOException
{
if (isOpen())
{
onClose.onClose();
this.resourceCache.clear();
this.open = false;
}
}
/**
* Action to be performed before the {@link PDDocument} is close
*
* @author Andrea Vacondio
*/
@FunctionalInterface
public static interface OnClose
{
/**
* Sets an action to be performed right before this {@link PDDocument} is closed.
*
* @param onClose
*/
void onClose() throws IOException;
default OnClose andThen(OnClose after)
{
Objects.requireNonNull(after);
return () -> {
onClose();
after.onClose();
};
}
}
/**
* Returns the resource cache associated with this document, or null if there is none.
*/
public ResourceCache getResourceCache()
{
return resourceCache;
}
// bridge to pdfbox style api, used in tests
public static PDDocument load(File file) throws IOException
{
return PDFParser.parse(SeekableSources.seekableSourceFrom(file));
}
}
| src/main/java/org/sejda/sambox/pdmodel/PDDocument.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sejda.sambox.pdmodel;
import static java.util.Optional.ofNullable;
import static org.sejda.commons.util.RequireUtils.requireNotBlank;
import static org.sejda.io.CountingWritableByteChannel.from;
import static org.sejda.sambox.cos.DirectCOSObject.asDirectObject;
import static org.sejda.sambox.util.SpecVersionUtils.V1_4;
import static org.sejda.sambox.util.SpecVersionUtils.isAtLeast;
import java.awt.Point;
import java.awt.image.DataBuffer;
import java.awt.image.Raster;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Calendar;
import java.util.HashSet;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import org.sejda.commons.util.IOUtils;
import org.apache.fontbox.ttf.TrueTypeFont;
import org.sejda.io.CountingWritableByteChannel;
import org.sejda.io.SeekableSources;
import org.sejda.sambox.SAMBox;
import org.sejda.sambox.cos.COSArray;
import org.sejda.sambox.cos.COSBase;
import org.sejda.sambox.cos.COSDictionary;
import org.sejda.sambox.cos.COSDocument;
import org.sejda.sambox.cos.COSInteger;
import org.sejda.sambox.cos.COSName;
import org.sejda.sambox.cos.COSNumber;
import org.sejda.sambox.cos.COSString;
import org.sejda.sambox.cos.DirectCOSObject;
import org.sejda.sambox.encryption.EncryptionContext;
import org.sejda.sambox.encryption.MessageDigests;
import org.sejda.sambox.encryption.StandardSecurity;
import org.sejda.sambox.input.PDFParser;
import org.sejda.sambox.output.PDDocumentWriter;
import org.sejda.sambox.output.WriteOption;
import org.sejda.sambox.pdmodel.common.PDStream;
import org.sejda.sambox.pdmodel.encryption.AccessPermission;
import org.sejda.sambox.pdmodel.encryption.PDEncryption;
import org.sejda.sambox.pdmodel.encryption.SecurityHandler;
import org.sejda.sambox.pdmodel.font.Subsettable;
import org.sejda.sambox.pdmodel.graphics.color.PDDeviceRGB;
import org.sejda.sambox.util.Version;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This is the in-memory representation of the PDF document.
*
* @author Ben Litchfield
*/
public class PDDocument implements Closeable
{
private static final Logger LOG = LoggerFactory.getLogger(PDDocument.class);
/**
* avoid concurrency issues with PDDeviceRGB and deadlock in COSNumber/COSInteger
*/
static
{
try
{
PDDeviceRGB.INSTANCE.toRGBImage(
Raster.createBandedRaster(DataBuffer.TYPE_BYTE, 1, 1, 3, new Point(0, 0)));
}
catch (IOException e)
{
LOG.warn("This shouldn't happen", e);
}
try
{
// TODO remove this and deprecated COSNumber statics in 3.0
COSNumber.get("0");
COSNumber.get("1");
}
catch (IOException ex)
{
//
}
}
private final COSDocument document;
private PDDocumentCatalog documentCatalog;
private SecurityHandler securityHandler;
private boolean open = true;
private OnClose onClose = () -> LOG.debug("Closing document");
private ResourceCache resourceCache = new DefaultResourceCache();
// fonts to subset before saving
private final Set<Subsettable> fontsToSubset = new HashSet<>();
public PDDocument()
{
document = new COSDocument();
document.getCatalog().setItem(COSName.VERSION, COSName.getPDFName("1.4"));
COSDictionary pages = new COSDictionary();
document.getCatalog().setItem(COSName.PAGES, pages);
pages.setItem(COSName.TYPE, COSName.PAGES);
pages.setItem(COSName.KIDS, new COSArray());
pages.setItem(COSName.COUNT, COSInteger.ZERO);
}
/**
* Constructor that uses an existing document. The COSDocument that is passed in must be valid.
*
* @param document The COSDocument that this document wraps.
*/
public PDDocument(COSDocument document)
{
this(document, null);
}
/**
* Constructor that uses an existing document. The COSDocument that is passed in must be valid.
*
* @param document The COSDocument that this document wraps.
* @param securityHandler
*/
public PDDocument(COSDocument document, SecurityHandler securityHandler)
{
this.document = document;
this.securityHandler = securityHandler;
}
/**
* This will add a page to the document. This is a convenience method, that will add the page to the root of the
* hierarchy and set the parent of the page to the root.
*
* @param page The page to add to the document.
*/
public void addPage(PDPage page)
{
requireOpen();
getPages().add(page);
}
/**
* Remove the page from the document.
*
* @param page The page to remove from the document.
*/
public void removePage(PDPage page)
{
requireOpen();
getPages().remove(page);
}
/**
* Remove the page from the document.
*
* @param pageNumber 0 based index to page number.
*/
public void removePage(int pageNumber)
{
requireOpen();
getPages().remove(pageNumber);
}
/**
* This will import and copy the contents from another location. Currently the content stream is stored in a scratch
* file. The scratch file is associated with the document. If you are adding a page to this document from another
* document and want to copy the contents to this document's scratch file then use this method otherwise just use
* the addPage method.
*
* @param page The page to import.
* @return The page that was imported.
*
*/
public PDPage importPage(PDPage page)
{
requireOpen();
PDPage importedPage = new PDPage(page.getCOSObject().duplicate());
InputStream in = null;
try
{
in = page.getContents();
if (in != null)
{
PDStream dest = new PDStream(in, COSName.FLATE_DECODE);
importedPage.setContents(dest);
}
addPage(importedPage);
}
catch (IOException e)
{
IOUtils.closeQuietly(in);
}
return importedPage;
}
/**
* @return The document that this layer sits on top of.
*/
public COSDocument getDocument()
{
return document;
}
/**
* This will get the document info dictionary. This is guaranteed to not return null.
*
* @return The documents /Info dictionary
*/
public PDDocumentInformation getDocumentInformation()
{
COSDictionary infoDic = document.getTrailer().getCOSObject()
.getDictionaryObject(COSName.INFO, COSDictionary.class);
if (infoDic == null)
{
infoDic = new COSDictionary();
document.getTrailer().getCOSObject().setItem(COSName.INFO, infoDic);
}
return new PDDocumentInformation(infoDic);
}
/**
* This will set the document information for this document.
*
* @param info The updated document information.
*/
public void setDocumentInformation(PDDocumentInformation documentInformation)
{
requireOpen();
document.getTrailer().getCOSObject().setItem(COSName.INFO,
documentInformation.getCOSObject());
}
/**
* This will get the document CATALOG. This is guaranteed to not return null.
*
* @return The documents /Root dictionary
*/
public PDDocumentCatalog getDocumentCatalog()
{
if (documentCatalog == null)
{
documentCatalog = new PDDocumentCatalog(this, document.getCatalog());
}
return documentCatalog;
}
/**
* @return true If this document is encrypted.
*/
public boolean isEncrypted()
{
return document.isEncrypted();
}
/**
* This will get the encryption dictionary for this document.
*
* @return The encryption dictionary
*/
public PDEncryption getEncryption()
{
if (isEncrypted())
{
return new PDEncryption(document.getEncryptionDictionary());
}
return new PDEncryption();
}
/**
* For internal PDFBox use when creating PDF documents: register a TrueTypeFont to make sure it is closed when the
* PDDocument is closed to avoid memory leaks. Users don't have to call this method, it is done by the appropriate
* PDFont classes.
*
* @param ttf
*/
public void registerTrueTypeFontForClosing(TrueTypeFont ttf)
{
onClose.andThen(() -> IOUtils.closeQuietly(ttf));
}
/**
* @return the list of fonts which will be subset before the document is saved.
*/
public Set<Subsettable> getFontsToSubset()
{
return fontsToSubset;
}
/**
* @param pageIndex the page index
* @return the page at the given zero based index.
*/
public PDPage getPage(int pageIndex)
{
return getDocumentCatalog().getPages().get(pageIndex);
}
public PDPageTree getPages()
{
return getDocumentCatalog().getPages();
}
/**
* @return The total number of pages in the PDF document.
*/
public int getNumberOfPages()
{
return getDocumentCatalog().getPages().getCount();
}
/**
* Returns the access permissions granted when the document was decrypted. If the document was not decrypted this
* method returns the access permission for a document owner (ie can do everything). The returned object is in read
* only mode so that permissions cannot be changed. Methods providing access to content should rely on this object
* to verify if the current user is allowed to proceed.
*
* @return the access permissions for the current user on the document.
*/
public AccessPermission getCurrentAccessPermission()
{
return ofNullable(securityHandler).map(s -> s.getCurrentAccessPermission())
.orElseGet(AccessPermission::getOwnerAccessPermission);
}
public SecurityHandler getSecurityHandler()
{
return securityHandler;
}
/**
* @return The version of the PDF specification to which the document conforms.
*/
public String getVersion()
{
String headerVersion = getDocument().getHeaderVersion();
if (isAtLeast(headerVersion, V1_4))
{
return ofNullable(getDocumentCatalog().getVersion())
.filter(catalogVersion -> (catalogVersion.compareTo(headerVersion) > 0))
.orElse(headerVersion);
}
return headerVersion;
}
/**
* Sets the version of the PDF specification to which the document conforms. Downgrading of the document version is
* not allowed.
*
* @param newVersion the new PDF version
*
*/
public void setVersion(String newVersion)
{
requireOpen();
requireNotBlank(newVersion, "Spec version cannot be blank");
int compare = getVersion().compareTo(newVersion);
if (compare > 0)
{
LOG.info("Spec version downgrade not allowed");
}
else if (compare < 0)
{
if (isAtLeast(newVersion, V1_4))
{
getDocumentCatalog().setVersion(newVersion);
}
getDocument().setHeaderVersion(newVersion);
}
}
/**
* If the document is not at the given version or above, it sets the version of the PDF specification to which the
* document conforms.
*
* @param version
*/
public void requireMinVersion(String version)
{
if (!isAtLeast(getVersion(), version))
{
LOG.debug("Minimum spec version required is {}", version);
setVersion(version);
}
}
/**
* Sets an action to be performed right before this {@link PDDocument} is closed.
*
* @param onClose
*/
public void setOnCloseAction(OnClose onClose)
{
requireOpen();
this.onClose = onClose.andThen(this.onClose);
}
private void requireOpen() throws IllegalStateException
{
if (!isOpen())
{
throw new IllegalStateException("The document is closed");
}
}
/**
* Generates file identifier as defined in the chap 14.4 PDF 32000-1:2008 and sets it as first and second value for
* the ID array in the document trailer.
*
* @param md5Update
* @param encContext
*/
private void generateFileIdentifier(byte[] md5Update, Optional<EncryptionContext> encContext)
{
COSString id = generateFileIdentifier(md5Update);
encContext.ifPresent(c -> c.documentId(id.getBytes()));
DirectCOSObject directId = asDirectObject(id);
getDocument().getTrailer().getCOSObject().setItem(COSName.ID,
asDirectObject(new COSArray(directId, directId)));
}
/**
*
* @param md5Update
* @return a newly generated ID based on the input bytes, current timestamp and some other information, to be used
* as value of the ID array in the document trailer.
*/
public COSString generateFileIdentifier(byte[] md5Update)
{
MessageDigest md5 = MessageDigests.md5();
md5.update(Long.toString(System.currentTimeMillis()).getBytes(StandardCharsets.ISO_8859_1));
md5.update(md5Update);
ofNullable(getDocument().getTrailer().getCOSObject().getDictionaryObject(COSName.INFO,
COSDictionary.class)).ifPresent(d -> {
for (COSBase current : d.getValues())
{
md5.update(current.toString().getBytes(StandardCharsets.ISO_8859_1));
}
});
COSString retVal = COSString.newInstance(md5.digest());
retVal.setForceHexForm(true);
retVal.encryptable(false);
return retVal;
}
/**
* Writes the document to the given {@link File}. The document is closed once written.
*
* @see PDDocument#close()
* @param file
* @param options
* @throws IOException
*/
public void writeTo(File file, WriteOption... options) throws IOException
{
writeTo(from(file), null, options);
}
/**
* Writes the document to the file corresponding the given file name. The document is closed once written.
*
* @see PDDocument#close()
* @param filename
* @param options
* @throws IOException
*/
public void writeTo(String filename, WriteOption... options) throws IOException
{
writeTo(from(filename), null, options);
}
/**
* Writes the document to the given {@link WritableByteChannel}. The document is closed once written.
*
* @see PDDocument#close()
* @param channel
* @param options
* @throws IOException
*/
public void writeTo(WritableByteChannel channel, WriteOption... options) throws IOException
{
writeTo(from(channel), null, options);
}
/**
* Writes the document to the given {@link OutputStream}. The document is closed once written.
*
* @see PDDocument#close()
* @param out
* @param options
* @throws IOException
*/
public void writeTo(OutputStream out, WriteOption... options) throws IOException
{
writeTo(from(out), null, options);
}
/**
* Writes the document to the given {@link File} encrypting it using the given security. The document is closed once
* written.
*
* @see PDDocument#close()
* @param file
* @param security
* @param options
* @throws IOException
*/
public void writeTo(File file, StandardSecurity security, WriteOption... options)
throws IOException
{
writeTo(from(file), security, options);
}
/**
* Writes the document to the file corresponding the given file name encrypting it using the given security. The
* document is closed once written.
*
* @see PDDocument#close()
* @param filename
* @param security
* @param options
* @throws IOException
*/
public void writeTo(String filename, StandardSecurity security, WriteOption... options)
throws IOException
{
writeTo(from(filename), security, options);
}
/**
* Writes the document to the given {@link WritableByteChannel} encrypting it using the given security. The document
* is closed once written.
*
* @see PDDocument#close()
* @param channel
* @param security
* @param options
* @throws IOException
*/
public void writeTo(WritableByteChannel channel, StandardSecurity security,
WriteOption... options) throws IOException
{
writeTo(from(channel), security, options);
}
/**
* Writes the document to the given {@link OutputStream} encrypting it using the given security. The document is
* closed once written.
*
* @see PDDocument#close()
* @param out
* @param security
* @param options
* @throws IOException
*/
public void writeTo(OutputStream out, StandardSecurity security, WriteOption... options)
throws IOException
{
writeTo(from(out), security, options);
}
private void writeTo(CountingWritableByteChannel output, StandardSecurity security,
WriteOption... options) throws IOException
{
requireOpen();
getDocumentInformation().setProducer(SAMBox.PRODUCER);
getDocumentInformation().setModificationDate(Calendar.getInstance());
for (Subsettable font : fontsToSubset)
{
font.subset();
}
fontsToSubset.clear();
Optional<EncryptionContext> encryptionContext = ofNullable(
ofNullable(security).map(EncryptionContext::new).orElse(null));
generateFileIdentifier(output.toString().getBytes(StandardCharsets.ISO_8859_1),
encryptionContext);
try (PDDocumentWriter writer = new PDDocumentWriter(output, encryptionContext, options))
{
writer.write(this);
}
finally
{
IOUtils.close(this);
}
}
/**
* @return true if the {@link PDDocument} is open
*/
public boolean isOpen()
{
return this.open;
}
/**
* Closes the {@link PDDocument} executing the set onClose action. Once closed the document is pretty much unusable
* since most of the methods requires an open document.
*
* @see PDDocument#setOnCloseAction(OnClose)
*/
@Override
public void close() throws IOException
{
if (isOpen())
{
onClose.onClose();
this.resourceCache.clear();
this.open = false;
}
}
/**
* Action to be performed before the {@link PDDocument} is close
*
* @author Andrea Vacondio
*/
@FunctionalInterface
public static interface OnClose
{
/**
* Sets an action to be performed right before this {@link PDDocument} is closed.
*
* @param onClose
*/
void onClose() throws IOException;
default OnClose andThen(OnClose after)
{
Objects.requireNonNull(after);
return () -> {
onClose();
after.onClose();
};
}
}
/**
* Returns the resource cache associated with this document, or null if there is none.
*/
public ResourceCache getResourceCache()
{
return resourceCache;
}
// bridge to pdfbox style api, used in tests
public static PDDocument load(File file) throws IOException
{
return PDFParser.parse(SeekableSources.seekableSourceFrom(file));
}
}
| removed unused import
| src/main/java/org/sejda/sambox/pdmodel/PDDocument.java | removed unused import |
|
Java | apache-2.0 | bf9ca3f942ce553aad8c653624084a370821b306 | 0 | realityforge-experiments/star-punk,realityforge-experiments/star-punk,realityforge-experiments/star-punk | package com.artemis.managers;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import com.artemis.Entity;
import com.artemis.Manager;
/**
* If you need to tag any entity, use this. A typical usage would be to tag
* entities such as "PLAYER", "BOSS" or something that is very unique.
*
* @author Arni Arent
*
*/
public class TagManager extends Manager {
private Map<String, Entity> entitiesByTag;
private Map<Entity, String> tagsByEntity;
public TagManager() {
entitiesByTag = new HashMap<>();
tagsByEntity = new HashMap<>();
}
public void register(String tag, Entity e) {
entitiesByTag.put(tag, e);
tagsByEntity.put(e, tag);
}
public void unregister(String tag) {
tagsByEntity.remove(entitiesByTag.remove(tag));
}
public boolean isRegistered(String tag) {
return entitiesByTag.containsKey(tag);
}
public Entity getEntity(String tag) {
return entitiesByTag.get(tag);
}
public Collection<String> getRegisteredTags() {
return tagsByEntity.values();
}
@Override
protected void changed(Entity e) {
}
@Override
protected void added(Entity e) {
}
@Override
protected void deleted(Entity e) {
String removedTag = tagsByEntity.remove(e);
if(removedTag != null) {
entitiesByTag.remove(removedTag);
}
}
@Override
protected void initialize() {
}
}
| src/com/artemis/managers/TagManager.java | package com.artemis.managers;
import java.util.HashMap;
import java.util.Map;
import com.artemis.Entity;
import com.artemis.Manager;
import com.artemis.World;
/**
* If you need to tag any entity, use this. A typical usage would be to tag
* entities such as "PLAYER". After creating an entity call register().
*
* @author Arni Arent
*
*/
public class TagManager extends Manager {
private World world;
private Map<String, Entity> entityByTag;
public TagManager(World world) {
this.world = world;
entityByTag = new HashMap<String, Entity>();
}
public void register(String tag, Entity e) {
entityByTag.put(tag, e);
}
public void unregister(String tag) {
entityByTag.remove(tag);
}
public boolean isRegistered(String tag) {
return entityByTag.containsKey(tag);
}
public Entity getEntity(String tag) {
return entityByTag.get(tag);
}
protected void remove(Entity e) {
entityByTag.values().remove(e);
}
@Override
protected void changed(Entity e) {
}
@Override
protected void added(Entity e) {
}
@Override
protected void deleted(Entity e) {
}
@Override
protected void initialize() {
}
}
| Refactoring TagManager.
| src/com/artemis/managers/TagManager.java | Refactoring TagManager. |
|
Java | apache-2.0 | 38589d7992751314602e9d20419bee9609dd33d2 | 0 | fj11/jmeter,hizhangqi/jmeter-1,hizhangqi/jmeter-1,tuanhq/jmeter,thomsonreuters/jmeter,kyroskoh/jmeter,kyroskoh/jmeter,vherilier/jmeter,hemikak/jmeter,vherilier/jmeter,ubikfsabbe/jmeter,fj11/jmeter,tuanhq/jmeter,etnetera/jmeter,ubikfsabbe/jmeter,ThiagoGarciaAlves/jmeter,hemikak/jmeter,max3163/jmeter,d0k1/jmeter,DoctorQ/jmeter,vherilier/jmeter,kschroeder/jmeter,ra0077/jmeter,DoctorQ/jmeter,max3163/jmeter,kschroeder/jmeter,ubikloadpack/jmeter,irfanah/jmeter,liwangbest/jmeter,max3163/jmeter,ubikfsabbe/jmeter,hizhangqi/jmeter-1,ra0077/jmeter,vherilier/jmeter,kyroskoh/jmeter,d0k1/jmeter,ThiagoGarciaAlves/jmeter,liwangbest/jmeter,etnetera/jmeter,liwangbest/jmeter,d0k1/jmeter,irfanah/jmeter,ubikfsabbe/jmeter,etnetera/jmeter,etnetera/jmeter,d0k1/jmeter,ra0077/jmeter,thomsonreuters/jmeter,fj11/jmeter,tuanhq/jmeter,ubikloadpack/jmeter,kschroeder/jmeter,hemikak/jmeter,max3163/jmeter,ThiagoGarciaAlves/jmeter,etnetera/jmeter,ubikloadpack/jmeter,irfanah/jmeter,ubikloadpack/jmeter,ra0077/jmeter,hemikak/jmeter,DoctorQ/jmeter,thomsonreuters/jmeter | /*
* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001-2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Apache" and "Apache Software Foundation" and
* "Apache JMeter" must not be used to endorse or promote products
* derived from this software without prior written permission. For
* written permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* "Apache JMeter", nor may "Apache" appear in their name, without
* prior written permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.jmeter.protocol.http.sampler;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.BindException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
//import java.util.ArrayList;
import java.util.zip.GZIPInputStream;
import org.apache.jmeter.config.Argument;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.http.control.AuthManager;
import org.apache.jmeter.protocol.http.control.CookieManager;
import org.apache.jmeter.protocol.http.control.Header;
import org.apache.jmeter.protocol.http.control.HeaderManager;
import org.apache.jmeter.protocol.http.util.HTTPArgument;
import org.apache.jmeter.samplers.AbstractSampler;
import org.apache.jmeter.samplers.Entry;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.testelement.property.BooleanProperty;
import org.apache.jmeter.testelement.property.CollectionProperty;
import org.apache.jmeter.testelement.property.IntegerProperty;
import org.apache.jmeter.testelement.property.JMeterProperty;
import org.apache.jmeter.testelement.property.PropertyIterator;
import org.apache.jmeter.testelement.property.StringProperty;
import org.apache.jmeter.testelement.property.TestElementProperty;
import org.apache.jmeter.threads.JMeterContextService;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jmeter.util.SSLManager;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.jorphan.util.JOrphanUtils;
import org.apache.log.Logger;
import org.apache.oro.text.PatternCacheLRU;
import org.apache.oro.text.regex.Perl5Compiler;
import org.apache.oro.text.regex.Perl5Matcher;
import org.apache.oro.text.regex.StringSubstitution;
import org.apache.oro.text.regex.Substitution;
import org.apache.oro.text.regex.Util;
/**
* A sampler which understands all the parts necessary to read statistics about
* HTTP requests, including cookies and authentication.
*
* @author Michael Stover
* @version $Revision$
*/
public class HTTPSampler extends AbstractSampler
{
public final static String HEADERS = "headers";
public final static String HEADER = "header";
public final static String ARGUMENTS = "HTTPsampler.Arguments";
public final static String AUTH_MANAGER = "HTTPSampler.auth_manager";
public final static String COOKIE_MANAGER = "HTTPSampler.cookie_manager";
public final static String HEADER_MANAGER = "HTTPSampler.header_manager";
public final static String MIMETYPE = "HTTPSampler.mimetype";
public final static String DOMAIN = "HTTPSampler.domain";
public final static String PORT = "HTTPSampler.port";
public final static String METHOD = "HTTPSampler.method";
public final static String PATH = "HTTPSampler.path";
public final static String FOLLOW_REDIRECTS =
"HTTPSampler.follow_redirects";
public final static String PROTOCOL = "HTTPSampler.protocol";
public final static String DEFAULT_PROTOCOL = "http";
public final static String URL = "HTTPSampler.URL";
public final static String POST = "POST";
public final static String GET = "GET";
public final static String USE_KEEPALIVE = "HTTPSampler.use_keepalive";
public final static String FILE_NAME = "HTTPSampler.FILE_NAME";
public final static String FILE_FIELD = "HTTPSampler.FILE_FIELD";
public final static String FILE_DATA = "HTTPSampler.FILE_DATA";
public final static String FILE_MIMETYPE = "HTTPSampler.FILE_MIMETYPE";
public final static String CONTENT_TYPE = "HTTPSampler.CONTENT_TYPE";
public final static String NORMAL_FORM = "normal_form";
public final static String MULTIPART_FORM = "multipart_form";
public final static String ENCODED_PATH = "HTTPSampler.encoded_path";
public final static String IMAGE_PARSER = "HTTPSampler.image_parser";
/** A number to indicate that the port has not been set. **/
public static final int UNSPECIFIED_PORT = 0;
private static final int MAX_REDIRECTS = 10;
protected static String encoding = "iso-8859-1";
private static final PostWriter postWriter = new PostWriter();
transient protected HttpURLConnection conn;
/** 10-20-2003 changed HTTPSampler to use NewHTTPSamplerFulll Peter Lin **/
private NewHTTPSamplerFull imageSampler;
static {
System.setProperty(
"java.protocol.handler.pkgs",
JMeterUtils.getPropDefault(
"ssl.pkgs",
"com.sun.net.ssl.internal.www.protocol"));
System.setProperty("javax.net.ssl.debug", "all");
}
private static PatternCacheLRU patternCache =
new PatternCacheLRU(1000, new Perl5Compiler());
private static ThreadLocal localMatcher = new ThreadLocal()
{
protected synchronized Object initialValue()
{
return new Perl5Matcher();
}
};
private static Substitution spaceSub = new StringSubstitution("%20");
private int connectionTries = 0;
/* Delegate redirects to the URLConnection implementation - this can be useful
* with alternate URLConnection implementations.
*
* Defaults to false, to maintain backward compatibility.
*/
private static boolean delegateRedirects =
JMeterUtils.getJMeterProperties().
getProperty("HTTPSampler.delegateRedirects","false").equalsIgnoreCase("true") ;
public void setFileField(String value)
{
setProperty(FILE_FIELD, value);
}
public String getFileField()
{
return getPropertyAsString(FILE_FIELD);
}
public void setFilename(String value)
{
setProperty(FILE_NAME, value);
}
public String getFilename()
{
return getPropertyAsString(FILE_NAME);
}
public void setProtocol(String value)
{
setProperty(PROTOCOL, value);
}
public String getProtocol()
{
String protocol = getPropertyAsString(PROTOCOL);
if (protocol == null || protocol.equals(""))
{
return DEFAULT_PROTOCOL;
}
else
{
return protocol;
}
}
/**
* Sets the Path attribute of the UrlConfig object
*
*@param path The new Path value
*/
public void setPath(String path)
{
if (GET.equals(getMethod()))
{
int index = path.indexOf("?");
if (index > -1)
{
setProperty(PATH, path.substring(0, index));
parseArguments(path.substring(index + 1));
}
else
{
setProperty(PATH, path);
}
}
else
{
setProperty(PATH, path);
}
}
public void setEncodedPath(String path)
{
path = encodePath(path);
setProperty(ENCODED_PATH, path);
}
private String encodePath(String path)
{
path =
Util.substitute(
(Perl5Matcher) localMatcher.get(),
patternCache.getPattern(
" ",
Perl5Compiler.READ_ONLY_MASK
& Perl5Compiler.SINGLELINE_MASK),
spaceSub,
path,
Util.SUBSTITUTE_ALL);
return path;
}
public String getEncodedPath()
{
return getPropertyAsString(ENCODED_PATH);
}
public void setProperty(JMeterProperty prop)
{
super.setProperty(prop);
if (PATH.equals(prop.getName()))
{
setEncodedPath(prop.getStringValue());
}
}
public void addProperty(JMeterProperty prop)
{
super.addProperty(prop);
if (PATH.equals(prop.getName()))
{
super.addProperty(
new StringProperty(
ENCODED_PATH,
encodePath(prop.getStringValue())));
}
}
public String getPath()
{
return getPropertyAsString(PATH);
}
public void setFollowRedirects(boolean value)
{
setProperty(new BooleanProperty(FOLLOW_REDIRECTS, value));
}
public boolean getFollowRedirects()
{
return getPropertyAsBoolean(FOLLOW_REDIRECTS);
}
public void setMethod(String value)
{
setProperty(METHOD, value);
}
public String getMethod()
{
return getPropertyAsString(METHOD);
}
public void setUseKeepAlive(boolean value)
{
setProperty(new BooleanProperty(USE_KEEPALIVE, value));
}
public boolean getUseKeepAlive()
{
return getPropertyAsBoolean(USE_KEEPALIVE);
}
public void addEncodedArgument(String name, String value, String metaData)
{
log.debug(
"adding argument: name: "
+ name
+ " value: "
+ value
+ " metaData: "
+ metaData);
Arguments args = getArguments();
HTTPArgument arg = new HTTPArgument(name, value, metaData, true);
if (arg.getName().equals(arg.getEncodedName())
&& arg.getValue().equals(arg.getEncodedValue()))
{
arg.setAlwaysEncoded(false);
}
args.addArgument(arg);
}
public void addArgument(String name, String value)
{
Arguments args = this.getArguments();
args.addArgument(new HTTPArgument(name, value));
}
public void addTestElement(TestElement el)
{
if (el instanceof CookieManager)
{
setCookieManager((CookieManager) el);
}
else if (el instanceof HeaderManager)
{
setHeaderManager((HeaderManager) el);
}
else if (el instanceof AuthManager)
{
setAuthManager((AuthManager) el);
}
else
{
super.addTestElement(el);
}
}
public void addArgument(String name, String value, String metadata)
{
Arguments args = this.getArguments();
args.addArgument(new HTTPArgument(name, value, metadata));
}
public void setPort(int value)
{
setProperty(new IntegerProperty(PORT, value));
}
public int getPort()
{
int port = getPropertyAsInt(PORT);
if (port == UNSPECIFIED_PORT)
{
if ("https".equalsIgnoreCase(getProtocol()))
{
return 443;
}
return 80;
}
return port;
}
public void setDomain(String value)
{
setProperty(DOMAIN, value);
}
public String getDomain()
{
return getPropertyAsString(DOMAIN);
}
public void setArguments(Arguments value)
{
setProperty(new TestElementProperty(ARGUMENTS, value));
}
public Arguments getArguments()
{
return (Arguments) getProperty(ARGUMENTS).getObjectValue();
}
public void setAuthManager(AuthManager value)
{
setProperty(new TestElementProperty(AUTH_MANAGER, value));
}
public AuthManager getAuthManager()
{
return (AuthManager) getProperty(AUTH_MANAGER).getObjectValue();
}
public void setHeaderManager(HeaderManager value)
{
setProperty(new TestElementProperty(HEADER_MANAGER, value));
}
public HeaderManager getHeaderManager()
{
return (HeaderManager) getProperty(HEADER_MANAGER).getObjectValue();
}
public void setCookieManager(CookieManager value)
{
setProperty(new TestElementProperty(COOKIE_MANAGER, value));
}
public CookieManager getCookieManager()
{
return (CookieManager) getProperty(COOKIE_MANAGER).getObjectValue();
}
public void setMimetype(String value)
{
setProperty(MIMETYPE, value);
}
public String getMimetype()
{
return getPropertyAsString(MIMETYPE);
}
public boolean isImageParser()
{
return getPropertyAsBoolean(IMAGE_PARSER);
}
public void setImageParser(boolean parseImages)
{
setProperty(new BooleanProperty(IMAGE_PARSER, parseImages));
}
protected final static String NON_HTTP_RESPONSE_CODE =
"Non HTTP response code";
protected final static String NON_HTTP_RESPONSE_MESSAGE =
"Non HTTP response message";
transient private static Logger log = LoggingManager.getLoggerForClass();
/**
* Holds a list of URLs sampled - so we're not flooding stdout with debug
* information
*/
//private ArrayList m_sampledURLs = new ArrayList();
/**
* Constructor for the HTTPSampler object.
*/
public HTTPSampler()
{
setArguments(new Arguments());
}
public HTTPSampler(URL u)
{
setMethod(GET);
setDomain(u.getHost());
setPath(u.getPath());
setPort(u.getPort());
setProtocol(u.getProtocol());
parseArguments(u.getQuery());
setFollowRedirects(true);
setUseKeepAlive(true);
setArguments(new Arguments());
}
/**
* Do a sampling and return its results.
*
* @param e <code>Entry</code> to be sampled
* @return results of the sampling
*/
public SampleResult sample(Entry e)
{
return sample(0);
}
public SampleResult sample()
{
return sample(0);
}
public URL getUrl() throws MalformedURLException
{
String pathAndQuery = null;
if (this.getMethod().equals(HTTPSampler.GET)
&& getQueryString().length() > 0)
{
if (this.getEncodedPath().indexOf("?") > -1)
{
pathAndQuery = this.getEncodedPath() + "&" + getQueryString();
}
else
{
pathAndQuery = this.getEncodedPath() + "?" + getQueryString();
}
}
else
{
pathAndQuery = this.getEncodedPath();
}
if (!pathAndQuery.startsWith("/"))
{
pathAndQuery = "/" + pathAndQuery;
}
if (getPort() == UNSPECIFIED_PORT || getPort() == 80)
{
return new URL(getProtocol(), getDomain(), pathAndQuery);
}
else
{
return new URL(
getProtocol(),
getPropertyAsString(HTTPSampler.DOMAIN),
getPort(),
pathAndQuery);
}
}
/**
* Gets the QueryString attribute of the UrlConfig object.
*
* @return the QueryString value
*/
public String getQueryString()
{
StringBuffer buf = new StringBuffer();
PropertyIterator iter = getArguments().iterator();
boolean first = true;
while (iter.hasNext())
{
HTTPArgument item = null;
try
{
item = (HTTPArgument) iter.next().getObjectValue();
}
catch (ClassCastException e)
{
item =
new HTTPArgument((Argument) iter.next().getObjectValue());
}
if (!first)
{
buf.append("&");
}
else
{
first = false;
}
buf.append(item.getEncodedName());
if (item.getMetaData() == null)
{
buf.append("=");
}
else
{
buf.append(item.getMetaData());
}
buf.append(item.getEncodedValue());
}
return buf.toString();
}
/**
* Set request headers in preparation to opening a connection.
*
* @param connection <code>URLConnection</code> to set headers on
* @exception IOException if an I/O exception occurs
*/
public void setPostHeaders(URLConnection conn) throws IOException
{
postWriter.setHeaders(conn, this);
}
/**
* Send POST data from <code>Entry</code> to the open connection.
*
* @param connection <code>URLConnection</code> of where POST data should
* be sent
* @exception IOException if an I/O exception occurs
*/
public void sendPostData(URLConnection connection) throws IOException
{
postWriter.sendPostData(connection, this);
}
/**
* Returns a <code>HttpURLConnection</code> with request method(GET or
* POST), headers, cookies, authorization properly set for the URL request.
*
* @param u <code>URL</code> of the URL request
* @param url <code>UrlConfig</code> of the URL request
* @return <code>HttpURLConnection</code> of the URL request
* @exception IOException if an I/O Exception occurs
*/
protected HttpURLConnection setupConnection(
URL u,
String method,
SampleResult res)
throws IOException
{
HttpURLConnection conn;
// [Jordi <[email protected]>]
// I've not been able to find out why we're not using this
// feature of HttpURLConnections and we're doing redirection
// by hand instead. Everything would be so much simpler...
// [/Jordi]
// Mike: answer - it didn't work. Maybe in JDK1.4 it works, but
// honestly, it doesn't seem like they're working on this.
// My longer term plan is to use Apache's home grown HTTP Client, or
// maybe even HTTPUnit's classes. I'm sure both would be better than
// Sun's.
// [sebb] Make redirect following configurable (see bug 19004)
// They do seem to work on JVM 1.4.1_03 (Sun/WinXP)
HttpURLConnection.setFollowRedirects(delegateRedirects);
conn = (HttpURLConnection) u.openConnection();
// Delegate SSL specific stuff to SSLManager so that compilation still
// works otherwise.
if ("https".equals(u.getProtocol()))
{
try
{
SSLManager.getInstance().setContext(conn);
}
catch (Exception e)
{
log.warn(
"You may have forgotten to set the ssl.provider property "
+ "in jmeter.properties",
e);
}
}
// a well-bahaved browser is supposed to send 'Connection: close'
// with the last request to an HTTP server. Instead, most browsers
// leave it to the server to close the connection after their
// timeout period. Leave it to the JMeter user to decide.
if (getUseKeepAlive())
{
conn.setRequestProperty("Connection", "keep-alive");
}
else
{
conn.setRequestProperty("Connection", "close");
}
conn.setRequestMethod(method);
setConnectionHeaders(conn, u, getHeaderManager());
String cookies = setConnectionCookie(conn, u, getCookieManager());
if (res != null)
{
StringBuffer sb = new StringBuffer();
sb.append(this.toString());
sb.append("\nCookie Data:\n");
sb.append(cookies);
res.setSamplerData(sb.toString());
}
setConnectionAuthorization(conn, u, getAuthManager());
return conn;
}
//Mark Walsh 2002-08-03, modified to also parse a parameter name value
//string, where string contains only the parameter name and no equal sign.
/**
* This method allows a proxy server to send over the raw text from a
* browser's output stream to be parsed and stored correctly into the
* UrlConfig object.
*/
public void parseArguments(String queryString)
{
String[] args = JOrphanUtils.split(queryString, "&");
for (int i = 0; i < args.length; i++)
{
// need to handle four cases: string contains name=value
// string contains name=
// string contains name
// empty string
// find end of parameter name
int endOfNameIndex = 0;
String metaData = ""; // records the existance of an equal sign
if (args[i].indexOf("=") != -1)
{
// case of name=value, name=
endOfNameIndex = args[i].indexOf("=");
metaData = "=";
}
else
{
metaData = "";
if (args[i].length() > 0)
{
endOfNameIndex = args[i].length(); // case name
}
else
{
endOfNameIndex = 0; //case where name value string is empty
}
}
// parse name
String name = ""; // for empty string
if (args[i].length() > 0)
{
//for non empty string
name = args[i].substring(0, endOfNameIndex);
}
// parse value
String value = "";
if ((endOfNameIndex + 1) < args[i].length())
{
value = args[i].substring(endOfNameIndex + 1, args[i].length());
}
if (name.length() > 0)
{
// In JDK 1.2, the decode() method has a throws clause:
// "throws Exception". In JDK 1.3, the method does not have
// a throws clause. So, in order to be JDK 1.2 compliant,
// we need to add a try/catch around the method call.
try
{
addEncodedArgument(name, value, metaData);
}
catch (Exception e)
{
log.error(
"UrlConfig:parseArguments(): Unable to parse argument=["
+ value
+ "]");
log.error(
"UrlConfig:parseArguments(): queryString=["
+ queryString
+ "]",
e);
}
}
}
}
/**
* Reads the response from the URL connection.
*
* @param conn URL from which to read response
* @return response in <code>String</code>
* @exception IOException if an I/O exception occurs
*/
protected byte[] readResponse(HttpURLConnection conn) throws IOException
{
byte[] readBuffer = JMeterContextService.getContext().getReadBuffer();
BufferedInputStream in;
try
{
if (conn.getContentEncoding() != null
&& conn.getContentEncoding().equals("gzip"))
{
in =
new BufferedInputStream(
new GZIPInputStream(conn.getInputStream()));
}
else
{
in = new BufferedInputStream(conn.getInputStream());
}
}
catch (Exception e)
{
log.info("Getting error message from server",e);
in = new BufferedInputStream(conn.getErrorStream());
}
java.io.ByteArrayOutputStream w = new ByteArrayOutputStream();
int x = 0;
while ((x = in.read(readBuffer)) > -1)
{
w.write(readBuffer, 0, x);
}
in.close();
w.flush();
w.close();
return w.toByteArray();
}
/**
* Gets the ResponseHeaders from the URLConnection, save them to the
* SampleResults object.
*
* @param conn connection from which the headers are read
* @param res where the headers read are stored
*/
protected byte[] getResponseHeaders(
HttpURLConnection conn,
SampleResult res)
throws IOException
{
StringBuffer headerBuf = new StringBuffer();
headerBuf.append(conn.getHeaderField(0).substring(0, 8));
headerBuf.append(" ");
headerBuf.append(conn.getResponseCode());
headerBuf.append(" ");
headerBuf.append(conn.getResponseMessage());
headerBuf.append("\n");
for (int i = 1; conn.getHeaderFieldKey(i) != null; i++)
{
if (!conn
.getHeaderFieldKey(i)
.equalsIgnoreCase("transfer-encoding"))
{
headerBuf.append(conn.getHeaderFieldKey(i));
headerBuf.append(": ");
headerBuf.append(conn.getHeaderField(i));
headerBuf.append("\n");
}
}
headerBuf.append("\n");
return headerBuf.toString().getBytes("8859_1");
}
/**
* Extracts all the required cookies for that particular URL request and set
* them in the <code>HttpURLConnection</code> passed in.
*
* @param conn <code>HttpUrlConnection</code> which represents the
* URL request
* @param u <code>URL</code> of the URL request
* @param cookieManager the <code>CookieManager</code> containing all the
* cookies for this <code>UrlConfig</code>
*/
private String setConnectionCookie(
HttpURLConnection conn,
URL u,
CookieManager cookieManager)
{
String cookieHeader = null;
if (cookieManager != null)
{
cookieHeader = cookieManager.getCookieHeaderForURL(u);
if (cookieHeader != null)
{
conn.setRequestProperty("Cookie", cookieHeader);
}
}
return cookieHeader;
}
/**
* Extracts all the required headers for that particular URL request and set
* them in the <code>HttpURLConnection</code> passed in
*
*@param conn <code>HttpUrlConnection</code> which represents the
* URL request
*@param u <code>URL</code> of the URL request
*@param headerManager the <code>HeaderManager</code> containing all the
* cookies for this <code>UrlConfig</code>
*/
private void setConnectionHeaders(
HttpURLConnection conn,
URL u,
HeaderManager headerManager)
{
if (headerManager != null)
{
CollectionProperty headers = headerManager.getHeaders();
if (headers != null)
{
PropertyIterator i = headers.iterator();
while (i.hasNext())
{
Header header = (Header) i.next().getObjectValue();
conn.setRequestProperty(
header.getName(),
header.getValue());
}
}
}
}
/**
* Extracts all the required authorization for that particular URL request
* and set them in the <code>HttpURLConnection</code> passed in.
*
* @param conn <code>HttpUrlConnection</code> which represents the
* URL request
* @param u <code>URL</code> of the URL request
* @param authManager the <code>AuthManager</code> containing all the
* cookies for this <code>UrlConfig</code>
*/
private void setConnectionAuthorization(
HttpURLConnection conn,
URL u,
AuthManager authManager)
{
if (authManager != null)
{
String authHeader = authManager.getAuthHeaderForURL(u);
if (authHeader != null)
{
conn.setRequestProperty("Authorization", authHeader);
}
}
}
/**
* Get the response code of the URL connection and divide it by 100 thus
* returning 2(for 2xx response codes), 3(for 3xx reponse codes), etc
*
* @param conn <code>HttpURLConnection</code> of URL request
* @param res where all results of sampling will be stored
* @param time time when the URL request was first started
* @return HTTP response code divided by 100
*/
private int getErrorLevel(
HttpURLConnection conn,
SampleResult res,
long time)
throws IOException
{
int errorLevel = 200;
String message = null;
errorLevel = ((HttpURLConnection) conn).getResponseCode();
message = ((HttpURLConnection) conn).getResponseMessage();
res.setResponseCode(Integer.toString(errorLevel));
res.setResponseMessage(message);
return errorLevel;
}
public void removeArguments()
{
setProperty(
new TestElementProperty(HTTPSampler.ARGUMENTS, new Arguments()));
}
/**
* Follow redirection manually. Normally if the web server does a
* redirection the intermediate page is not returned. Only the resultant
* page and the response code for the page will be returned. With
* redirection turned off, the response code of 3xx will be returned
* together with a "Location" header-value pair to indicate that the
* "Location" value needs to be followed to get the resultant page.
*
* @param conn connection
* @param u
* @exception MalformedURLException if URL is not understood
*/
private void redirectUrl(HttpURLConnection conn, URL u)
throws MalformedURLException
{
String loc = conn.getHeaderField("Location");
if (loc != null)
{
if (loc.indexOf("http") == -1)
{
String tempURL = u.toString();
if (loc.startsWith("/"))
{
int ind = tempURL.indexOf("//") + 2;
loc =
tempURL.substring(0, tempURL.indexOf("/", ind) + 1)
+ loc.substring(1);
}
else
{
loc =
u.toString().substring(
0,
u.toString().lastIndexOf('/') + 1)
+ loc;
}
}
}
URL newUrl = new URL(loc);
setMethod(GET);
setProtocol(newUrl.getProtocol());
setDomain(newUrl.getHost());
setPort(newUrl.getPort());
setPath(newUrl.getFile());
removeArguments();
parseArguments(newUrl.getQuery());
}
protected long connect() throws IOException
{
long time = System.currentTimeMillis();
try
{
conn.connect();
connectionTries = 0;
}
catch (BindException e)
{
log.debug("Bind exception, try again");
if (connectionTries++ == 10)
{
log.error("Can't connect", e);
throw e;
}
conn.disconnect();
conn = null;
System.gc();
Runtime.getRuntime().runFinalization();
this.setUseKeepAlive(false);
conn = setupConnection(getUrl(), getMethod(), null);
if (getMethod().equals(HTTPSampler.POST))
{
setPostHeaders(conn);
}
time = connect();
}
catch (IOException e)
{
log.debug("Connection failed, giving up");
conn.disconnect();
conn = null;
System.gc();
Runtime.getRuntime().runFinalization();
throw e;
}
return time;
}
/**
* Samples <code>Entry</code> passed in and stores the result in
* <code>SampleResult</code>.
*
* @param e <code>Entry</code> to be sampled
* @param redirects the level of redirection we're processing (0 means
* original request) -- just used to prevent
* an infinite loop.
* @return results of the sampling
*/
private SampleResult sample(int redirects)
{
log.debug("Start : sample2");
long time = System.currentTimeMillis();
SampleResult res = new SampleResult();
URL u = null;
try
{
u = getUrl();
res.setSampleLabel(getName());
// specify the data to the result.
// res.setSamplerData(this.toString());
/****************************************
* END - cached logging hack
***************************************/
if (log.isDebugEnabled())
{
log.debug("sample2 : sampling url - " + u);
}
conn = setupConnection(u, getMethod(), res);
if (getMethod().equals(HTTPSampler.POST))
{
setPostHeaders(conn);
time = connect();
sendPostData(conn);
}
else
{
time = connect();
}
saveConnectionCookies(conn, u, getCookieManager());
int errorLevel = 0;
try
{
errorLevel = getErrorLevel(conn, res, time);
}
catch (IOException e)
{
time = bundleResponseInResult(time, res, conn);
res.setSuccessful(false);
res.setTime(time);
return res;
}
if (errorLevel / 100 == 2 || errorLevel == 304)
{
time = bundleResponseInResult(time, res, conn);
}
else if (errorLevel / 100 == 3)
{
if (redirects >= MAX_REDIRECTS)
{
throw new IOException(
"Maximum number of redirects exceeded");
}
if (!getFollowRedirects())
{
time = bundleResponseInResult(time, res, conn);
}
else
{
time = bundleResponseInResult(time, res, conn);
//System.currentTimeMillis() - time;
redirectUrl(conn, u);
SampleResult redirectResult = sample(redirects + 1);
res.addSubResult(redirectResult);
//res.setResponseData(redirectResult.getResponseData());
res.setSuccessful(redirectResult.isSuccessful());
time += redirectResult.getTime();
}
}
else
{
// Could not sample the URL
time = bundleResponseInResult(time, res, conn);
res.setSuccessful(false);
}
res.setTime(time);
log.debug("End : sample2");
if (isImageParser())
{
if (imageSampler == null)
{
// change to NewHTTPSamplerFull, which uses
// htmlparser to get the images and bin
// files.
imageSampler = new NewHTTPSamplerFull();
}
res = imageSampler.parseForImages(res, this);
}
return res;
}
catch (Exception ex)
{
log.warn(ex.getMessage(), ex);
res.setDataType(SampleResult.TEXT);
res.setResponseData(ex.toString().getBytes());
res.setResponseCode(NON_HTTP_RESPONSE_CODE);
res.setResponseMessage(NON_HTTP_RESPONSE_MESSAGE);
res.setTime(System.currentTimeMillis() - time);
res.setSuccessful(false);
}
finally
{
try
{
// calling disconnect doesn't close the connection immediately,
// but indicates we're through with it. The JVM should close
// it when necessary.
disconnect(conn);
}
catch (Exception e)
{}
}
log.debug("End : sample2");
return res;
}
protected void disconnect(HttpURLConnection conn)
{
String connection = conn.getHeaderField("Connection");
boolean http11 = conn.getHeaderField(0).startsWith("HTTP/1.1");
if ((connection == null && !http11)
|| (connection != null && connection.equalsIgnoreCase("close")))
{
conn.disconnect();
}
}
private long bundleResponseInResult(
long time,
SampleResult res,
HttpURLConnection conn)
throws IOException, FileNotFoundException
{
res.setDataType(SampleResult.TEXT);
byte[] ret = readResponse(conn);
byte[] head = getResponseHeaders(conn, res);
time = System.currentTimeMillis() - time;
byte[] complete = new byte[ret.length + head.length];
System.arraycopy(head, 0, complete, 0, head.length);
System.arraycopy(ret, 0, complete, head.length, ret.length);
res.setResponseData(complete);
res.setSuccessful(true);
return time;
}
/**
* From the <code>HttpURLConnection</code>, store all the "set-cookie"
* key-pair values in the cookieManager of the <code>UrlConfig</code>.
*
* @param conn <code>HttpUrlConnection</code> which represents the
* URL request
* @param u <code>URL</code> of the URL request
* @param cookieManager the <code>CookieManager</code> containing all the
* cookies for this <code>UrlConfig</code>
*/
private void saveConnectionCookies(
HttpURLConnection conn,
URL u,
CookieManager cookieManager)
{
if (cookieManager != null)
{
for (int i = 1; conn.getHeaderFieldKey(i) != null; i++)
{
if (conn.getHeaderFieldKey(i).equalsIgnoreCase("set-cookie"))
{
cookieManager.addCookieFromHeader(
conn.getHeaderField(i),
u);
}
}
}
}
public String toString()
{
try
{
return this.getUrl().toString()
+ ((POST.equals(getMethod()))
? "\nQuery Data: " + getQueryString()
: "");
}
catch (MalformedURLException e)
{
return "";
}
}
public static class Test extends junit.framework.TestCase
{
public Test(String name)
{
super(name);
}
public void testArgumentWithoutEquals() throws Exception
{
HTTPSampler sampler = new HTTPSampler();
sampler.setProtocol("http");
sampler.setMethod(HTTPSampler.GET);
sampler.setPath("/index.html?pear");
sampler.setDomain("www.apache.org");
assertEquals(
"http://www.apache.org/index.html?pear",
sampler.getUrl().toString());
}
public void testMakingUrl() throws Exception
{
HTTPSampler config = new HTTPSampler();
config.setProtocol("http");
config.setMethod(HTTPSampler.GET);
config.addArgument("param1", "value1");
config.setPath("/index.html");
config.setDomain("www.apache.org");
assertEquals(
"http://www.apache.org/index.html?param1=value1",
config.getUrl().toString());
}
public void testMakingUrl2() throws Exception
{
HTTPSampler config = new HTTPSampler();
config.setProtocol("http");
config.setMethod(HTTPSampler.GET);
config.addArgument("param1", "value1");
config.setPath("/index.html?p1=p2");
config.setDomain("www.apache.org");
assertEquals(
"http://www.apache.org/index.html?param1=value1&p1=p2",
config.getUrl().toString());
}
public void testMakingUrl3() throws Exception
{
HTTPSampler config = new HTTPSampler();
config.setProtocol("http");
config.setMethod(HTTPSampler.POST);
config.addArgument("param1", "value1");
config.setPath("/index.html?p1=p2");
config.setDomain("www.apache.org");
assertEquals(
"http://www.apache.org/index.html?p1=p2",
config.getUrl().toString());
}
// test cases for making Url, and exercise method
// addArgument(String name,String value,String metadata)
public void testMakingUrl4() throws Exception
{
HTTPSampler config = new HTTPSampler();
config.setProtocol("http");
config.setMethod(HTTPSampler.GET);
config.addArgument("param1", "value1", "=");
config.setPath("/index.html");
config.setDomain("www.apache.org");
assertEquals(
"http://www.apache.org/index.html?param1=value1",
config.getUrl().toString());
}
public void testMakingUrl5() throws Exception
{
HTTPSampler config = new HTTPSampler();
config.setProtocol("http");
config.setMethod(HTTPSampler.GET);
config.addArgument("param1", "", "=");
config.setPath("/index.html");
config.setDomain("www.apache.org");
assertEquals(
"http://www.apache.org/index.html?param1=",
config.getUrl().toString());
}
public void testMakingUrl6() throws Exception
{
HTTPSampler config = new HTTPSampler();
config.setProtocol("http");
config.setMethod(HTTPSampler.GET);
config.addArgument("param1", "", "");
config.setPath("/index.html");
config.setDomain("www.apache.org");
assertEquals(
"http://www.apache.org/index.html?param1",
config.getUrl().toString());
}
// test cases for making Url, and exercise method
// parseArguments(String queryString)
public void testMakingUrl7() throws Exception
{
HTTPSampler config = new HTTPSampler();
config.setProtocol("http");
config.setMethod(HTTPSampler.GET);
config.parseArguments("param1=value1");
config.setPath("/index.html");
config.setDomain("www.apache.org");
assertEquals(
"http://www.apache.org/index.html?param1=value1",
config.getUrl().toString());
}
public void testMakingUrl8() throws Exception
{
HTTPSampler config = new HTTPSampler();
config.setProtocol("http");
config.setMethod(HTTPSampler.GET);
config.parseArguments("param1=");
config.setPath("/index.html");
config.setDomain("www.apache.org");
assertEquals(
"http://www.apache.org/index.html?param1=",
config.getUrl().toString());
}
public void testMakingUrl9() throws Exception
{
HTTPSampler config = new HTTPSampler();
config.setProtocol("http");
config.setMethod(HTTPSampler.GET);
config.parseArguments("param1");
config.setPath("/index.html");
config.setDomain("www.apache.org");
assertEquals(
"http://www.apache.org/index.html?param1",
config.getUrl().toString());
}
public void testMakingUrl10() throws Exception
{
HTTPSampler config = new HTTPSampler();
config.setProtocol("http");
config.setMethod(HTTPSampler.GET);
config.parseArguments("");
config.setPath("/index.html");
config.setDomain("www.apache.org");
assertEquals(
"http://www.apache.org/index.html",
config.getUrl().toString());
}
}
}
| src/protocol/http/org/apache/jmeter/protocol/http/sampler/HTTPSampler.java | /*
* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001-2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Apache" and "Apache Software Foundation" and
* "Apache JMeter" must not be used to endorse or promote products
* derived from this software without prior written permission. For
* written permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* "Apache JMeter", nor may "Apache" appear in their name, without
* prior written permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.jmeter.protocol.http.sampler;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.BindException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
//import java.util.ArrayList;
import java.util.zip.GZIPInputStream;
import org.apache.jmeter.config.Argument;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.http.control.AuthManager;
import org.apache.jmeter.protocol.http.control.CookieManager;
import org.apache.jmeter.protocol.http.control.Header;
import org.apache.jmeter.protocol.http.control.HeaderManager;
import org.apache.jmeter.protocol.http.util.HTTPArgument;
import org.apache.jmeter.samplers.AbstractSampler;
import org.apache.jmeter.samplers.Entry;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.testelement.property.BooleanProperty;
import org.apache.jmeter.testelement.property.CollectionProperty;
import org.apache.jmeter.testelement.property.IntegerProperty;
import org.apache.jmeter.testelement.property.JMeterProperty;
import org.apache.jmeter.testelement.property.PropertyIterator;
import org.apache.jmeter.testelement.property.StringProperty;
import org.apache.jmeter.testelement.property.TestElementProperty;
import org.apache.jmeter.threads.JMeterContextService;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jmeter.util.SSLManager;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.jorphan.util.JOrphanUtils;
import org.apache.log.Logger;
import org.apache.oro.text.PatternCacheLRU;
import org.apache.oro.text.regex.Perl5Compiler;
import org.apache.oro.text.regex.Perl5Matcher;
import org.apache.oro.text.regex.StringSubstitution;
import org.apache.oro.text.regex.Substitution;
import org.apache.oro.text.regex.Util;
/**
* A sampler which understands all the parts necessary to read statistics about
* HTTP requests, including cookies and authentication.
*
* @author Michael Stover
* @version $Revision$
*/
public class HTTPSampler extends AbstractSampler
{
public final static String HEADERS = "headers";
public final static String HEADER = "header";
public final static String ARGUMENTS = "HTTPsampler.Arguments";
public final static String AUTH_MANAGER = "HTTPSampler.auth_manager";
public final static String COOKIE_MANAGER = "HTTPSampler.cookie_manager";
public final static String HEADER_MANAGER = "HTTPSampler.header_manager";
public final static String MIMETYPE = "HTTPSampler.mimetype";
public final static String DOMAIN = "HTTPSampler.domain";
public final static String PORT = "HTTPSampler.port";
public final static String METHOD = "HTTPSampler.method";
public final static String PATH = "HTTPSampler.path";
public final static String FOLLOW_REDIRECTS =
"HTTPSampler.follow_redirects";
public final static String PROTOCOL = "HTTPSampler.protocol";
public final static String DEFAULT_PROTOCOL = "http";
public final static String URL = "HTTPSampler.URL";
public final static String POST = "POST";
public final static String GET = "GET";
public final static String USE_KEEPALIVE = "HTTPSampler.use_keepalive";
public final static String FILE_NAME = "HTTPSampler.FILE_NAME";
public final static String FILE_FIELD = "HTTPSampler.FILE_FIELD";
public final static String FILE_DATA = "HTTPSampler.FILE_DATA";
public final static String FILE_MIMETYPE = "HTTPSampler.FILE_MIMETYPE";
public final static String CONTENT_TYPE = "HTTPSampler.CONTENT_TYPE";
public final static String NORMAL_FORM = "normal_form";
public final static String MULTIPART_FORM = "multipart_form";
public final static String ENCODED_PATH = "HTTPSampler.encoded_path";
public final static String IMAGE_PARSER = "HTTPSampler.image_parser";
/** A number to indicate that the port has not been set. **/
public static final int UNSPECIFIED_PORT = 0;
private static final int MAX_REDIRECTS = 10;
protected static String encoding = "iso-8859-1";
private static final PostWriter postWriter = new PostWriter();
transient protected HttpURLConnection conn;
private HTTPSamplerFull imageSampler;
static {
System.setProperty(
"java.protocol.handler.pkgs",
JMeterUtils.getPropDefault(
"ssl.pkgs",
"com.sun.net.ssl.internal.www.protocol"));
System.setProperty("javax.net.ssl.debug", "all");
}
private static PatternCacheLRU patternCache =
new PatternCacheLRU(1000, new Perl5Compiler());
private static ThreadLocal localMatcher = new ThreadLocal()
{
protected synchronized Object initialValue()
{
return new Perl5Matcher();
}
};
private static Substitution spaceSub = new StringSubstitution("%20");
private int connectionTries = 0;
/* Delegate redirects to the URLConnection implementation - this can be useful
* with alternate URLConnection implementations.
*
* Defaults to false, to maintain backward compatibility.
*/
private static boolean delegateRedirects =
JMeterUtils.getJMeterProperties().
getProperty("HTTPSampler.delegateRedirects","false").equalsIgnoreCase("true") ;
public void setFileField(String value)
{
setProperty(FILE_FIELD, value);
}
public String getFileField()
{
return getPropertyAsString(FILE_FIELD);
}
public void setFilename(String value)
{
setProperty(FILE_NAME, value);
}
public String getFilename()
{
return getPropertyAsString(FILE_NAME);
}
public void setProtocol(String value)
{
setProperty(PROTOCOL, value);
}
public String getProtocol()
{
String protocol = getPropertyAsString(PROTOCOL);
if (protocol == null || protocol.equals(""))
{
return DEFAULT_PROTOCOL;
}
else
{
return protocol;
}
}
/**
* Sets the Path attribute of the UrlConfig object
*
*@param path The new Path value
*/
public void setPath(String path)
{
if (GET.equals(getMethod()))
{
int index = path.indexOf("?");
if (index > -1)
{
setProperty(PATH, path.substring(0, index));
parseArguments(path.substring(index + 1));
}
else
{
setProperty(PATH, path);
}
}
else
{
setProperty(PATH, path);
}
}
public void setEncodedPath(String path)
{
path = encodePath(path);
setProperty(ENCODED_PATH, path);
}
private String encodePath(String path)
{
path =
Util.substitute(
(Perl5Matcher) localMatcher.get(),
patternCache.getPattern(
" ",
Perl5Compiler.READ_ONLY_MASK
& Perl5Compiler.SINGLELINE_MASK),
spaceSub,
path,
Util.SUBSTITUTE_ALL);
return path;
}
public String getEncodedPath()
{
return getPropertyAsString(ENCODED_PATH);
}
public void setProperty(JMeterProperty prop)
{
super.setProperty(prop);
if (PATH.equals(prop.getName()))
{
setEncodedPath(prop.getStringValue());
}
}
public void addProperty(JMeterProperty prop)
{
super.addProperty(prop);
if (PATH.equals(prop.getName()))
{
super.addProperty(
new StringProperty(
ENCODED_PATH,
encodePath(prop.getStringValue())));
}
}
public String getPath()
{
return getPropertyAsString(PATH);
}
public void setFollowRedirects(boolean value)
{
setProperty(new BooleanProperty(FOLLOW_REDIRECTS, value));
}
public boolean getFollowRedirects()
{
return getPropertyAsBoolean(FOLLOW_REDIRECTS);
}
public void setMethod(String value)
{
setProperty(METHOD, value);
}
public String getMethod()
{
return getPropertyAsString(METHOD);
}
public void setUseKeepAlive(boolean value)
{
setProperty(new BooleanProperty(USE_KEEPALIVE, value));
}
public boolean getUseKeepAlive()
{
return getPropertyAsBoolean(USE_KEEPALIVE);
}
public void addEncodedArgument(String name, String value, String metaData)
{
log.debug(
"adding argument: name: "
+ name
+ " value: "
+ value
+ " metaData: "
+ metaData);
Arguments args = getArguments();
HTTPArgument arg = new HTTPArgument(name, value, metaData, true);
if (arg.getName().equals(arg.getEncodedName())
&& arg.getValue().equals(arg.getEncodedValue()))
{
arg.setAlwaysEncoded(false);
}
args.addArgument(arg);
}
public void addArgument(String name, String value)
{
Arguments args = this.getArguments();
args.addArgument(new HTTPArgument(name, value));
}
public void addTestElement(TestElement el)
{
if (el instanceof CookieManager)
{
setCookieManager((CookieManager) el);
}
else if (el instanceof HeaderManager)
{
setHeaderManager((HeaderManager) el);
}
else if (el instanceof AuthManager)
{
setAuthManager((AuthManager) el);
}
else
{
super.addTestElement(el);
}
}
public void addArgument(String name, String value, String metadata)
{
Arguments args = this.getArguments();
args.addArgument(new HTTPArgument(name, value, metadata));
}
public void setPort(int value)
{
setProperty(new IntegerProperty(PORT, value));
}
public int getPort()
{
int port = getPropertyAsInt(PORT);
if (port == UNSPECIFIED_PORT)
{
if ("https".equalsIgnoreCase(getProtocol()))
{
return 443;
}
return 80;
}
return port;
}
public void setDomain(String value)
{
setProperty(DOMAIN, value);
}
public String getDomain()
{
return getPropertyAsString(DOMAIN);
}
public void setArguments(Arguments value)
{
setProperty(new TestElementProperty(ARGUMENTS, value));
}
public Arguments getArguments()
{
return (Arguments) getProperty(ARGUMENTS).getObjectValue();
}
public void setAuthManager(AuthManager value)
{
setProperty(new TestElementProperty(AUTH_MANAGER, value));
}
public AuthManager getAuthManager()
{
return (AuthManager) getProperty(AUTH_MANAGER).getObjectValue();
}
public void setHeaderManager(HeaderManager value)
{
setProperty(new TestElementProperty(HEADER_MANAGER, value));
}
public HeaderManager getHeaderManager()
{
return (HeaderManager) getProperty(HEADER_MANAGER).getObjectValue();
}
public void setCookieManager(CookieManager value)
{
setProperty(new TestElementProperty(COOKIE_MANAGER, value));
}
public CookieManager getCookieManager()
{
return (CookieManager) getProperty(COOKIE_MANAGER).getObjectValue();
}
public void setMimetype(String value)
{
setProperty(MIMETYPE, value);
}
public String getMimetype()
{
return getPropertyAsString(MIMETYPE);
}
public boolean isImageParser()
{
return getPropertyAsBoolean(IMAGE_PARSER);
}
public void setImageParser(boolean parseImages)
{
setProperty(new BooleanProperty(IMAGE_PARSER, parseImages));
}
protected final static String NON_HTTP_RESPONSE_CODE =
"Non HTTP response code";
protected final static String NON_HTTP_RESPONSE_MESSAGE =
"Non HTTP response message";
transient private static Logger log = LoggingManager.getLoggerForClass();
/**
* Holds a list of URLs sampled - so we're not flooding stdout with debug
* information
*/
//private ArrayList m_sampledURLs = new ArrayList();
/**
* Constructor for the HTTPSampler object.
*/
public HTTPSampler()
{
setArguments(new Arguments());
}
public HTTPSampler(URL u)
{
setMethod(GET);
setDomain(u.getHost());
setPath(u.getPath());
setPort(u.getPort());
setProtocol(u.getProtocol());
parseArguments(u.getQuery());
setFollowRedirects(true);
setUseKeepAlive(true);
setArguments(new Arguments());
}
/**
* Do a sampling and return its results.
*
* @param e <code>Entry</code> to be sampled
* @return results of the sampling
*/
public SampleResult sample(Entry e)
{
return sample(0);
}
public SampleResult sample()
{
return sample(0);
}
public URL getUrl() throws MalformedURLException
{
String pathAndQuery = null;
if (this.getMethod().equals(HTTPSampler.GET)
&& getQueryString().length() > 0)
{
if (this.getEncodedPath().indexOf("?") > -1)
{
pathAndQuery = this.getEncodedPath() + "&" + getQueryString();
}
else
{
pathAndQuery = this.getEncodedPath() + "?" + getQueryString();
}
}
else
{
pathAndQuery = this.getEncodedPath();
}
if (!pathAndQuery.startsWith("/"))
{
pathAndQuery = "/" + pathAndQuery;
}
if (getPort() == UNSPECIFIED_PORT || getPort() == 80)
{
return new URL(getProtocol(), getDomain(), pathAndQuery);
}
else
{
return new URL(
getProtocol(),
getPropertyAsString(HTTPSampler.DOMAIN),
getPort(),
pathAndQuery);
}
}
/**
* Gets the QueryString attribute of the UrlConfig object.
*
* @return the QueryString value
*/
public String getQueryString()
{
StringBuffer buf = new StringBuffer();
PropertyIterator iter = getArguments().iterator();
boolean first = true;
while (iter.hasNext())
{
HTTPArgument item = null;
try
{
item = (HTTPArgument) iter.next().getObjectValue();
}
catch (ClassCastException e)
{
item =
new HTTPArgument((Argument) iter.next().getObjectValue());
}
if (!first)
{
buf.append("&");
}
else
{
first = false;
}
buf.append(item.getEncodedName());
if (item.getMetaData() == null)
{
buf.append("=");
}
else
{
buf.append(item.getMetaData());
}
buf.append(item.getEncodedValue());
}
return buf.toString();
}
/**
* Set request headers in preparation to opening a connection.
*
* @param connection <code>URLConnection</code> to set headers on
* @exception IOException if an I/O exception occurs
*/
public void setPostHeaders(URLConnection conn) throws IOException
{
postWriter.setHeaders(conn, this);
}
/**
* Send POST data from <code>Entry</code> to the open connection.
*
* @param connection <code>URLConnection</code> of where POST data should
* be sent
* @exception IOException if an I/O exception occurs
*/
public void sendPostData(URLConnection connection) throws IOException
{
postWriter.sendPostData(connection, this);
}
/**
* Returns a <code>HttpURLConnection</code> with request method(GET or
* POST), headers, cookies, authorization properly set for the URL request.
*
* @param u <code>URL</code> of the URL request
* @param url <code>UrlConfig</code> of the URL request
* @return <code>HttpURLConnection</code> of the URL request
* @exception IOException if an I/O Exception occurs
*/
protected HttpURLConnection setupConnection(
URL u,
String method,
SampleResult res)
throws IOException
{
HttpURLConnection conn;
// [Jordi <[email protected]>]
// I've not been able to find out why we're not using this
// feature of HttpURLConnections and we're doing redirection
// by hand instead. Everything would be so much simpler...
// [/Jordi]
// Mike: answer - it didn't work. Maybe in JDK1.4 it works, but
// honestly, it doesn't seem like they're working on this.
// My longer term plan is to use Apache's home grown HTTP Client, or
// maybe even HTTPUnit's classes. I'm sure both would be better than
// Sun's.
// [sebb] Make redirect following configurable (see bug 19004)
// They do seem to work on JVM 1.4.1_03 (Sun/WinXP)
HttpURLConnection.setFollowRedirects(delegateRedirects);
conn = (HttpURLConnection) u.openConnection();
// Delegate SSL specific stuff to SSLManager so that compilation still
// works otherwise.
if ("https".equals(u.getProtocol()))
{
try
{
SSLManager.getInstance().setContext(conn);
}
catch (Exception e)
{
log.warn(
"You may have forgotten to set the ssl.provider property "
+ "in jmeter.properties",
e);
}
}
// a well-bahaved browser is supposed to send 'Connection: close'
// with the last request to an HTTP server. Instead, most browsers
// leave it to the server to close the connection after their
// timeout period. Leave it to the JMeter user to decide.
if (getUseKeepAlive())
{
conn.setRequestProperty("Connection", "keep-alive");
}
else
{
conn.setRequestProperty("Connection", "close");
}
conn.setRequestMethod(method);
setConnectionHeaders(conn, u, getHeaderManager());
String cookies = setConnectionCookie(conn, u, getCookieManager());
if (res != null)
{
StringBuffer sb = new StringBuffer();
sb.append(this.toString());
sb.append("\nCookie Data:\n");
sb.append(cookies);
res.setSamplerData(sb.toString());
}
setConnectionAuthorization(conn, u, getAuthManager());
return conn;
}
//Mark Walsh 2002-08-03, modified to also parse a parameter name value
//string, where string contains only the parameter name and no equal sign.
/**
* This method allows a proxy server to send over the raw text from a
* browser's output stream to be parsed and stored correctly into the
* UrlConfig object.
*/
public void parseArguments(String queryString)
{
String[] args = JOrphanUtils.split(queryString, "&");
for (int i = 0; i < args.length; i++)
{
// need to handle four cases: string contains name=value
// string contains name=
// string contains name
// empty string
// find end of parameter name
int endOfNameIndex = 0;
String metaData = ""; // records the existance of an equal sign
if (args[i].indexOf("=") != -1)
{
// case of name=value, name=
endOfNameIndex = args[i].indexOf("=");
metaData = "=";
}
else
{
metaData = "";
if (args[i].length() > 0)
{
endOfNameIndex = args[i].length(); // case name
}
else
{
endOfNameIndex = 0; //case where name value string is empty
}
}
// parse name
String name = ""; // for empty string
if (args[i].length() > 0)
{
//for non empty string
name = args[i].substring(0, endOfNameIndex);
}
// parse value
String value = "";
if ((endOfNameIndex + 1) < args[i].length())
{
value = args[i].substring(endOfNameIndex + 1, args[i].length());
}
if (name.length() > 0)
{
// In JDK 1.2, the decode() method has a throws clause:
// "throws Exception". In JDK 1.3, the method does not have
// a throws clause. So, in order to be JDK 1.2 compliant,
// we need to add a try/catch around the method call.
try
{
addEncodedArgument(name, value, metaData);
}
catch (Exception e)
{
log.error(
"UrlConfig:parseArguments(): Unable to parse argument=["
+ value
+ "]");
log.error(
"UrlConfig:parseArguments(): queryString=["
+ queryString
+ "]",
e);
}
}
}
}
/**
* Reads the response from the URL connection.
*
* @param conn URL from which to read response
* @return response in <code>String</code>
* @exception IOException if an I/O exception occurs
*/
protected byte[] readResponse(HttpURLConnection conn) throws IOException
{
byte[] readBuffer = JMeterContextService.getContext().getReadBuffer();
BufferedInputStream in;
try
{
if (conn.getContentEncoding() != null
&& conn.getContentEncoding().equals("gzip"))
{
in =
new BufferedInputStream(
new GZIPInputStream(conn.getInputStream()));
}
else
{
in = new BufferedInputStream(conn.getInputStream());
}
}
catch (Exception e)
{
log.info("Getting error message from server",e);
in = new BufferedInputStream(conn.getErrorStream());
}
java.io.ByteArrayOutputStream w = new ByteArrayOutputStream();
int x = 0;
while ((x = in.read(readBuffer)) > -1)
{
w.write(readBuffer, 0, x);
}
in.close();
w.flush();
w.close();
return w.toByteArray();
}
/**
* Gets the ResponseHeaders from the URLConnection, save them to the
* SampleResults object.
*
* @param conn connection from which the headers are read
* @param res where the headers read are stored
*/
protected byte[] getResponseHeaders(
HttpURLConnection conn,
SampleResult res)
throws IOException
{
StringBuffer headerBuf = new StringBuffer();
headerBuf.append(conn.getHeaderField(0).substring(0, 8));
headerBuf.append(" ");
headerBuf.append(conn.getResponseCode());
headerBuf.append(" ");
headerBuf.append(conn.getResponseMessage());
headerBuf.append("\n");
for (int i = 1; conn.getHeaderFieldKey(i) != null; i++)
{
if (!conn
.getHeaderFieldKey(i)
.equalsIgnoreCase("transfer-encoding"))
{
headerBuf.append(conn.getHeaderFieldKey(i));
headerBuf.append(": ");
headerBuf.append(conn.getHeaderField(i));
headerBuf.append("\n");
}
}
headerBuf.append("\n");
return headerBuf.toString().getBytes("8859_1");
}
/**
* Extracts all the required cookies for that particular URL request and set
* them in the <code>HttpURLConnection</code> passed in.
*
* @param conn <code>HttpUrlConnection</code> which represents the
* URL request
* @param u <code>URL</code> of the URL request
* @param cookieManager the <code>CookieManager</code> containing all the
* cookies for this <code>UrlConfig</code>
*/
private String setConnectionCookie(
HttpURLConnection conn,
URL u,
CookieManager cookieManager)
{
String cookieHeader = null;
if (cookieManager != null)
{
cookieHeader = cookieManager.getCookieHeaderForURL(u);
if (cookieHeader != null)
{
conn.setRequestProperty("Cookie", cookieHeader);
}
}
return cookieHeader;
}
/**
* Extracts all the required headers for that particular URL request and set
* them in the <code>HttpURLConnection</code> passed in
*
*@param conn <code>HttpUrlConnection</code> which represents the
* URL request
*@param u <code>URL</code> of the URL request
*@param headerManager the <code>HeaderManager</code> containing all the
* cookies for this <code>UrlConfig</code>
*/
private void setConnectionHeaders(
HttpURLConnection conn,
URL u,
HeaderManager headerManager)
{
if (headerManager != null)
{
CollectionProperty headers = headerManager.getHeaders();
if (headers != null)
{
PropertyIterator i = headers.iterator();
while (i.hasNext())
{
Header header = (Header) i.next().getObjectValue();
conn.setRequestProperty(
header.getName(),
header.getValue());
}
}
}
}
/**
* Extracts all the required authorization for that particular URL request
* and set them in the <code>HttpURLConnection</code> passed in.
*
* @param conn <code>HttpUrlConnection</code> which represents the
* URL request
* @param u <code>URL</code> of the URL request
* @param authManager the <code>AuthManager</code> containing all the
* cookies for this <code>UrlConfig</code>
*/
private void setConnectionAuthorization(
HttpURLConnection conn,
URL u,
AuthManager authManager)
{
if (authManager != null)
{
String authHeader = authManager.getAuthHeaderForURL(u);
if (authHeader != null)
{
conn.setRequestProperty("Authorization", authHeader);
}
}
}
/**
* Get the response code of the URL connection and divide it by 100 thus
* returning 2(for 2xx response codes), 3(for 3xx reponse codes), etc
*
* @param conn <code>HttpURLConnection</code> of URL request
* @param res where all results of sampling will be stored
* @param time time when the URL request was first started
* @return HTTP response code divided by 100
*/
private int getErrorLevel(
HttpURLConnection conn,
SampleResult res,
long time)
throws IOException
{
int errorLevel = 200;
String message = null;
errorLevel = ((HttpURLConnection) conn).getResponseCode();
message = ((HttpURLConnection) conn).getResponseMessage();
res.setResponseCode(Integer.toString(errorLevel));
res.setResponseMessage(message);
return errorLevel;
}
public void removeArguments()
{
setProperty(
new TestElementProperty(HTTPSampler.ARGUMENTS, new Arguments()));
}
/**
* Follow redirection manually. Normally if the web server does a
* redirection the intermediate page is not returned. Only the resultant
* page and the response code for the page will be returned. With
* redirection turned off, the response code of 3xx will be returned
* together with a "Location" header-value pair to indicate that the
* "Location" value needs to be followed to get the resultant page.
*
* @param conn connection
* @param u
* @exception MalformedURLException if URL is not understood
*/
private void redirectUrl(HttpURLConnection conn, URL u)
throws MalformedURLException
{
String loc = conn.getHeaderField("Location");
if (loc != null)
{
if (loc.indexOf("http") == -1)
{
String tempURL = u.toString();
if (loc.startsWith("/"))
{
int ind = tempURL.indexOf("//") + 2;
loc =
tempURL.substring(0, tempURL.indexOf("/", ind) + 1)
+ loc.substring(1);
}
else
{
loc =
u.toString().substring(
0,
u.toString().lastIndexOf('/') + 1)
+ loc;
}
}
}
URL newUrl = new URL(loc);
setMethod(GET);
setProtocol(newUrl.getProtocol());
setDomain(newUrl.getHost());
setPort(newUrl.getPort());
setPath(newUrl.getFile());
removeArguments();
parseArguments(newUrl.getQuery());
}
protected long connect() throws IOException
{
long time = System.currentTimeMillis();
try
{
conn.connect();
connectionTries = 0;
}
catch (BindException e)
{
log.debug("Bind exception, try again");
if (connectionTries++ == 10)
{
log.error("Can't connect", e);
throw e;
}
conn.disconnect();
conn = null;
System.gc();
Runtime.getRuntime().runFinalization();
this.setUseKeepAlive(false);
conn = setupConnection(getUrl(), getMethod(), null);
if (getMethod().equals(HTTPSampler.POST))
{
setPostHeaders(conn);
}
time = connect();
}
catch (IOException e)
{
log.debug("Connection failed, giving up");
conn.disconnect();
conn = null;
System.gc();
Runtime.getRuntime().runFinalization();
throw e;
}
return time;
}
/**
* Samples <code>Entry</code> passed in and stores the result in
* <code>SampleResult</code>.
*
* @param e <code>Entry</code> to be sampled
* @param redirects the level of redirection we're processing (0 means
* original request) -- just used to prevent
* an infinite loop.
* @return results of the sampling
*/
private SampleResult sample(int redirects)
{
log.debug("Start : sample2");
long time = System.currentTimeMillis();
SampleResult res = new SampleResult();
URL u = null;
try
{
u = getUrl();
res.setSampleLabel(getName());
// specify the data to the result.
// res.setSamplerData(this.toString());
/****************************************
* END - cached logging hack
***************************************/
if (log.isDebugEnabled())
{
log.debug("sample2 : sampling url - " + u);
}
conn = setupConnection(u, getMethod(), res);
if (getMethod().equals(HTTPSampler.POST))
{
setPostHeaders(conn);
time = connect();
sendPostData(conn);
}
else
{
time = connect();
}
saveConnectionCookies(conn, u, getCookieManager());
int errorLevel = 0;
try
{
errorLevel = getErrorLevel(conn, res, time);
}
catch (IOException e)
{
time = bundleResponseInResult(time, res, conn);
res.setSuccessful(false);
res.setTime(time);
return res;
}
if (errorLevel / 100 == 2 || errorLevel == 304)
{
time = bundleResponseInResult(time, res, conn);
}
else if (errorLevel / 100 == 3)
{
if (redirects >= MAX_REDIRECTS)
{
throw new IOException(
"Maximum number of redirects exceeded");
}
if (!getFollowRedirects())
{
time = bundleResponseInResult(time, res, conn);
}
else
{
time = bundleResponseInResult(time, res, conn);
//System.currentTimeMillis() - time;
redirectUrl(conn, u);
SampleResult redirectResult = sample(redirects + 1);
res.addSubResult(redirectResult);
//res.setResponseData(redirectResult.getResponseData());
res.setSuccessful(redirectResult.isSuccessful());
time += redirectResult.getTime();
}
}
else
{
// Could not sample the URL
time = bundleResponseInResult(time, res, conn);
res.setSuccessful(false);
}
res.setTime(time);
log.debug("End : sample2");
if (isImageParser())
{
if (imageSampler == null)
{
imageSampler = new HTTPSamplerFull();
}
res = imageSampler.parseForImages(res, this);
}
return res;
}
catch (Exception ex)
{
log.warn(ex.getMessage(), ex);
res.setDataType(SampleResult.TEXT);
res.setResponseData(ex.toString().getBytes());
res.setResponseCode(NON_HTTP_RESPONSE_CODE);
res.setResponseMessage(NON_HTTP_RESPONSE_MESSAGE);
res.setTime(System.currentTimeMillis() - time);
res.setSuccessful(false);
}
finally
{
try
{
// calling disconnect doesn't close the connection immediately,
// but indicates we're through with it. The JVM should close
// it when necessary.
disconnect(conn);
}
catch (Exception e)
{}
}
log.debug("End : sample2");
return res;
}
protected void disconnect(HttpURLConnection conn)
{
String connection = conn.getHeaderField("Connection");
boolean http11 = conn.getHeaderField(0).startsWith("HTTP/1.1");
if ((connection == null && !http11)
|| (connection != null && connection.equalsIgnoreCase("close")))
{
conn.disconnect();
}
}
private long bundleResponseInResult(
long time,
SampleResult res,
HttpURLConnection conn)
throws IOException, FileNotFoundException
{
res.setDataType(SampleResult.TEXT);
byte[] ret = readResponse(conn);
byte[] head = getResponseHeaders(conn, res);
time = System.currentTimeMillis() - time;
byte[] complete = new byte[ret.length + head.length];
System.arraycopy(head, 0, complete, 0, head.length);
System.arraycopy(ret, 0, complete, head.length, ret.length);
res.setResponseData(complete);
res.setSuccessful(true);
return time;
}
/**
* From the <code>HttpURLConnection</code>, store all the "set-cookie"
* key-pair values in the cookieManager of the <code>UrlConfig</code>.
*
* @param conn <code>HttpUrlConnection</code> which represents the
* URL request
* @param u <code>URL</code> of the URL request
* @param cookieManager the <code>CookieManager</code> containing all the
* cookies for this <code>UrlConfig</code>
*/
private void saveConnectionCookies(
HttpURLConnection conn,
URL u,
CookieManager cookieManager)
{
if (cookieManager != null)
{
for (int i = 1; conn.getHeaderFieldKey(i) != null; i++)
{
if (conn.getHeaderFieldKey(i).equalsIgnoreCase("set-cookie"))
{
cookieManager.addCookieFromHeader(
conn.getHeaderField(i),
u);
}
}
}
}
public String toString()
{
try
{
return this.getUrl().toString()
+ ((POST.equals(getMethod()))
? "\nQuery Data: " + getQueryString()
: "");
}
catch (MalformedURLException e)
{
return "";
}
}
public static class Test extends junit.framework.TestCase
{
public Test(String name)
{
super(name);
}
public void testArgumentWithoutEquals() throws Exception
{
HTTPSampler sampler = new HTTPSampler();
sampler.setProtocol("http");
sampler.setMethod(HTTPSampler.GET);
sampler.setPath("/index.html?pear");
sampler.setDomain("www.apache.org");
assertEquals(
"http://www.apache.org/index.html?pear",
sampler.getUrl().toString());
}
public void testMakingUrl() throws Exception
{
HTTPSampler config = new HTTPSampler();
config.setProtocol("http");
config.setMethod(HTTPSampler.GET);
config.addArgument("param1", "value1");
config.setPath("/index.html");
config.setDomain("www.apache.org");
assertEquals(
"http://www.apache.org/index.html?param1=value1",
config.getUrl().toString());
}
public void testMakingUrl2() throws Exception
{
HTTPSampler config = new HTTPSampler();
config.setProtocol("http");
config.setMethod(HTTPSampler.GET);
config.addArgument("param1", "value1");
config.setPath("/index.html?p1=p2");
config.setDomain("www.apache.org");
assertEquals(
"http://www.apache.org/index.html?param1=value1&p1=p2",
config.getUrl().toString());
}
public void testMakingUrl3() throws Exception
{
HTTPSampler config = new HTTPSampler();
config.setProtocol("http");
config.setMethod(HTTPSampler.POST);
config.addArgument("param1", "value1");
config.setPath("/index.html?p1=p2");
config.setDomain("www.apache.org");
assertEquals(
"http://www.apache.org/index.html?p1=p2",
config.getUrl().toString());
}
// test cases for making Url, and exercise method
// addArgument(String name,String value,String metadata)
public void testMakingUrl4() throws Exception
{
HTTPSampler config = new HTTPSampler();
config.setProtocol("http");
config.setMethod(HTTPSampler.GET);
config.addArgument("param1", "value1", "=");
config.setPath("/index.html");
config.setDomain("www.apache.org");
assertEquals(
"http://www.apache.org/index.html?param1=value1",
config.getUrl().toString());
}
public void testMakingUrl5() throws Exception
{
HTTPSampler config = new HTTPSampler();
config.setProtocol("http");
config.setMethod(HTTPSampler.GET);
config.addArgument("param1", "", "=");
config.setPath("/index.html");
config.setDomain("www.apache.org");
assertEquals(
"http://www.apache.org/index.html?param1=",
config.getUrl().toString());
}
public void testMakingUrl6() throws Exception
{
HTTPSampler config = new HTTPSampler();
config.setProtocol("http");
config.setMethod(HTTPSampler.GET);
config.addArgument("param1", "", "");
config.setPath("/index.html");
config.setDomain("www.apache.org");
assertEquals(
"http://www.apache.org/index.html?param1",
config.getUrl().toString());
}
// test cases for making Url, and exercise method
// parseArguments(String queryString)
public void testMakingUrl7() throws Exception
{
HTTPSampler config = new HTTPSampler();
config.setProtocol("http");
config.setMethod(HTTPSampler.GET);
config.parseArguments("param1=value1");
config.setPath("/index.html");
config.setDomain("www.apache.org");
assertEquals(
"http://www.apache.org/index.html?param1=value1",
config.getUrl().toString());
}
public void testMakingUrl8() throws Exception
{
HTTPSampler config = new HTTPSampler();
config.setProtocol("http");
config.setMethod(HTTPSampler.GET);
config.parseArguments("param1=");
config.setPath("/index.html");
config.setDomain("www.apache.org");
assertEquals(
"http://www.apache.org/index.html?param1=",
config.getUrl().toString());
}
public void testMakingUrl9() throws Exception
{
HTTPSampler config = new HTTPSampler();
config.setProtocol("http");
config.setMethod(HTTPSampler.GET);
config.parseArguments("param1");
config.setPath("/index.html");
config.setDomain("www.apache.org");
assertEquals(
"http://www.apache.org/index.html?param1",
config.getUrl().toString());
}
public void testMakingUrl10() throws Exception
{
HTTPSampler config = new HTTPSampler();
config.setProtocol("http");
config.setMethod(HTTPSampler.GET);
config.parseArguments("");
config.setPath("/index.html");
config.setDomain("www.apache.org");
assertEquals(
"http://www.apache.org/index.html",
config.getUrl().toString());
}
}
}
|
changed HTTPSampler to use NewHTTPSamplerFull, which uses
htmlparser instead of tidy.
git-svn-id: 7c053b8fbd1fb5868f764c6f9536fc6a9bbe7da9@323626 13f79535-47bb-0310-9956-ffa450edef68
| src/protocol/http/org/apache/jmeter/protocol/http/sampler/HTTPSampler.java | ||
Java | apache-2.0 | 2bfdec5b0ecf8a7f9ff86555c1752ce8eecf0bcc | 0 | mohanaraosv/commons-io,mohanaraosv/commons-io,MuShiiii/commons-io,krosenvold/commons-io,girirajsharma/commons-io,MuShiiii/commons-io,mohanaraosv/commons-io,girirajsharma/commons-io,MuShiiii/commons-io,yinhe402/commons-io,jankill/commons-io,yinhe402/commons-io,jankill/commons-io,krosenvold/commons-io,krosenvold/commons-io,jankill/commons-io,girirajsharma/commons-io,yinhe402/commons-io | /*
* Copyright 2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import junit.framework.Test;
import junit.framework.TestSuite;
import junit.textui.TestRunner;
import org.apache.commons.io.testtools.FileBasedTestCase;
/**
* This is used to test FileSystemUtils.
*
* @author Stephen Colebourne
* @version $Id$
*/
public class FileSystemUtilsTestCase extends FileBasedTestCase {
public static void main(String[] args) {
TestRunner.run(suite());
// try {
// System.out.println(FileSystemUtils.getFreeSpace("C:\\"));
// } catch (IOException ex) {
// ex.printStackTrace();
// }
}
public static Test suite() {
return new TestSuite(FileSystemUtilsTestCase.class);
}
public FileSystemUtilsTestCase(String name) throws IOException {
super(name);
}
protected void setUp() throws Exception {
}
protected void tearDown() throws Exception {
}
//-----------------------------------------------------------------------
public void testGetFreeSpace_String() throws Exception {
// test coverage, as we can't check value
if (File.separatorChar == '/') {
assertEquals(true, FileSystemUtils.getFreeSpace("/") > 0);
} else {
assertEquals(true, FileSystemUtils.getFreeSpace("") > 0);
}
}
//-----------------------------------------------------------------------
public void testGetFreeSpaceOS_String_NullPath() throws Exception {
FileSystemUtils fsu = new FileSystemUtils();
try {
fsu.getFreeSpaceOS(null, 1);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testGetFreeSpaceOS_String_InitError() throws Exception {
FileSystemUtils fsu = new FileSystemUtils();
try {
fsu.getFreeSpaceOS("", -1);
fail();
} catch (IllegalStateException ex) {}
}
public void testGetFreeSpaceOS_String_Other() throws Exception {
FileSystemUtils fsu = new FileSystemUtils();
try {
fsu.getFreeSpaceOS("", 0);
fail();
} catch (IllegalStateException ex) {}
}
public void testGetFreeSpaceOS_String_Windows() throws Exception {
FileSystemUtils fsu = new FileSystemUtils() {
protected long getFreeSpaceWindows(String path) throws IOException {
return 12345L;
}
};
assertEquals(12345L, fsu.getFreeSpaceOS("", 1));
}
public void testGetFreeSpaceOS_String_Unix() throws Exception {
FileSystemUtils fsu = new FileSystemUtils() {
protected long getFreeSpaceUnix(String path) throws IOException {
return 12345L;
}
};
assertEquals(12345L, fsu.getFreeSpaceOS("", 2));
}
//-----------------------------------------------------------------------
public void testGetFreeSpaceWindows_String_EmptyPath() throws Exception {
String lines =
" Volume in drive C is HDD\n" +
" Volume Serial Number is XXXX-YYYY\n" +
"\n" +
" Directory of C:\\Documents and Settings\\Xxxx\n" +
"\n" +
"19/08/2005 22:43 <DIR> .\n" +
"19/08/2005 22:43 <DIR> ..\n" +
"11/08/2005 01:07 81 build.properties\n" +
"17/08/2005 21:44 <DIR> Desktop\n" +
" 7 File(s) 180,260 bytes\n" +
" 10 Dir(s) 41,411,551,232 bytes free";
final StringReader reader = new StringReader(lines);
FileSystemUtils fsu = new FileSystemUtils() {
protected BufferedReader openProcessStream(String[] params) {
assertEquals("dir /c ", params[2]);
return new BufferedReader(reader);
}
};
assertEquals(41411551232L, fsu.getFreeSpaceWindows(""));
}
public void testGetFreeSpaceWindows_String_NormalResponse() throws Exception {
String lines =
" Volume in drive C is HDD\n" +
" Volume Serial Number is XXXX-YYYY\n" +
"\n" +
" Directory of C:\\Documents and Settings\\Xxxx\n" +
"\n" +
"19/08/2005 22:43 <DIR> .\n" +
"19/08/2005 22:43 <DIR> ..\n" +
"11/08/2005 01:07 81 build.properties\n" +
"17/08/2005 21:44 <DIR> Desktop\n" +
" 7 File(s) 180,260 bytes\n" +
" 10 Dir(s) 41,411,551,232 bytes free";
final StringReader reader = new StringReader(lines);
FileSystemUtils fsu = new FileSystemUtils() {
protected BufferedReader openProcessStream(String[] params) {
assertEquals("dir /c C:", params[2]);
return new BufferedReader(reader);
}
};
assertEquals(41411551232L, fsu.getFreeSpaceWindows("C:"));
}
public void testGetFreeSpaceWindows_String_StripDrive() throws Exception {
String lines =
" Volume in drive C is HDD\n" +
" Volume Serial Number is XXXX-YYYY\n" +
"\n" +
" Directory of C:\\Documents and Settings\\Xxxx\n" +
"\n" +
"19/08/2005 22:43 <DIR> .\n" +
"19/08/2005 22:43 <DIR> ..\n" +
"11/08/2005 01:07 81 build.properties\n" +
"17/08/2005 21:44 <DIR> Desktop\n" +
" 7 File(s) 180,260 bytes\n" +
" 10 Dir(s) 41,411,551,232 bytes free";
final StringReader reader = new StringReader(lines);
FileSystemUtils fsu = new FileSystemUtils() {
protected BufferedReader openProcessStream(String[] params) {
assertEquals("dir /c C:", params[2]);
return new BufferedReader(reader);
}
};
assertEquals(41411551232L, fsu.getFreeSpaceWindows("C:\\somedir"));
}
public void testGetFreeSpaceWindows_String_EmptyResponse() throws Exception {
String lines = "";
final StringReader reader = new StringReader(lines);
FileSystemUtils fsu = new FileSystemUtils() {
protected BufferedReader openProcessStream(String[] params) {
return new BufferedReader(reader);
}
};
try {
fsu.getFreeSpaceWindows("C:");
fail();
} catch (IOException ex) {}
}
//-----------------------------------------------------------------------
public void testGetFreeSpaceUnix_String_EmptyPath() throws Exception {
String lines =
"Filesystem 1K-blocks Used Available Use% Mounted on\n" +
"xxx:/home/users/s 14428928 12956424 1472504 90% /home/users/s";
final StringReader reader = new StringReader(lines);
FileSystemUtils fsu = new FileSystemUtils() {
protected BufferedReader openProcessStream(String[] params) {
return new BufferedReader(reader);
}
};
try {
fsu.getFreeSpaceUnix("");
fail();
} catch (IllegalArgumentException ex) {}
}
public void testGetFreeSpaceUnix_String_NormalResponse() throws Exception {
String lines =
"Filesystem 1K-blocks Used Available Use% Mounted on\n" +
"xxx:/home/users/s 14428928 12956424 1472504 90% /home/users/s";
final StringReader reader = new StringReader(lines);
FileSystemUtils fsu = new FileSystemUtils() {
protected BufferedReader openProcessStream(String[] params) {
return new BufferedReader(reader);
}
};
assertEquals(1472504L, fsu.getFreeSpaceUnix("/home/users/s"));
}
public void testGetFreeSpaceUnix_String_LongResponse() throws Exception {
String lines =
"Filesystem 1K-blocks Used Available Use% Mounted on\n" +
"xxx-yyyyyyy-zzz:/home/users/s\n" +
" 14428928 12956424 1472504 90% /home/users/s";
final StringReader reader = new StringReader(lines);
FileSystemUtils fsu = new FileSystemUtils() {
protected BufferedReader openProcessStream(String[] params) {
return new BufferedReader(reader);
}
};
assertEquals(1472504L, fsu.getFreeSpaceUnix("/home/users/s"));
}
public void testGetFreeSpaceUnix_String_EmptyResponse() throws Exception {
String lines = "";
final StringReader reader = new StringReader(lines);
FileSystemUtils fsu = new FileSystemUtils() {
protected BufferedReader openProcessStream(String[] params) {
return new BufferedReader(reader);
}
};
try {
fsu.getFreeSpaceUnix("/home/users/s");
fail();
} catch (IOException ex) {}
}
public void testGetFreeSpaceUnix_String_InvalidResponse1() throws Exception {
String lines =
"Filesystem 1K-blocks Used Available Use% Mounted on\n" +
" 14428928 12956424 100";
final StringReader reader = new StringReader(lines);
FileSystemUtils fsu = new FileSystemUtils() {
protected BufferedReader openProcessStream(String[] params) {
return new BufferedReader(reader);
}
};
try {
fsu.getFreeSpaceUnix("/home/users/s");
fail();
} catch (IOException ex) {}
}
public void testGetFreeSpaceUnix_String_InvalidResponse2() throws Exception {
String lines =
"Filesystem 1K-blocks Used Available Use% Mounted on\n" +
"xxx:/home/users/s 14428928 12956424 nnnnnnn 90% /home/users/s";
final StringReader reader = new StringReader(lines);
FileSystemUtils fsu = new FileSystemUtils() {
protected BufferedReader openProcessStream(String[] params) {
return new BufferedReader(reader);
}
};
try {
fsu.getFreeSpaceUnix("/home/users/s");
fail();
} catch (IOException ex) {}
}
public void testGetFreeSpaceUnix_String_InvalidResponse3() throws Exception {
String lines =
"Filesystem 1K-blocks Used Available Use% Mounted on\n" +
"xxx:/home/users/s 14428928 12956424 -1 90% /home/users/s";
final StringReader reader = new StringReader(lines);
FileSystemUtils fsu = new FileSystemUtils() {
protected BufferedReader openProcessStream(String[] params) {
return new BufferedReader(reader);
}
};
try {
fsu.getFreeSpaceUnix("/home/users/s");
fail();
} catch (IOException ex) {}
}
public void testGetFreeSpaceUnix_String_InvalidResponse4() throws Exception {
String lines =
"Filesystem 1K-blocks Used Available Use% Mounted on\n" +
"xxx-yyyyyyy-zzz:/home/users/s";
final StringReader reader = new StringReader(lines);
FileSystemUtils fsu = new FileSystemUtils() {
protected BufferedReader openProcessStream(String[] params) {
return new BufferedReader(reader);
}
};
try {
fsu.getFreeSpaceUnix("/home/users/s");
fail();
} catch (IOException ex) {}
}
}
| src/test/org/apache/commons/io/FileSystemUtilsTestCase.java | /*
* Copyright 2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import junit.framework.Test;
import junit.framework.TestSuite;
import junit.textui.TestRunner;
import org.apache.commons.io.testtools.FileBasedTestCase;
/**
* This is used to test FileSystemUtils.
*
* @author Stephen Colebourne
* @version $Id$
*/
public class FileSystemUtilsTestCase extends FileBasedTestCase {
public static void main(String[] args) {
TestRunner.run(suite());
}
public static Test suite() {
return new TestSuite(FileSystemUtilsTestCase.class);
}
public FileSystemUtilsTestCase(String name) throws IOException {
super(name);
}
protected void setUp() throws Exception {
}
protected void tearDown() throws Exception {
}
//-----------------------------------------------------------------------
public void testGetFreeSpace_String() throws Exception {
// test coverage, as we can't check value
if (File.separatorChar == '/') {
assertEquals(true, FileSystemUtils.getFreeSpace("~") > 0);
} else {
assertEquals(true, FileSystemUtils.getFreeSpace("") > 0);
}
}
//-----------------------------------------------------------------------
public void testGetFreeSpaceOS_String_NullPath() throws Exception {
FileSystemUtils fsu = new FileSystemUtils();
try {
fsu.getFreeSpaceOS(null, 1);
fail();
} catch (IllegalArgumentException ex) {}
}
public void testGetFreeSpaceOS_String_InitError() throws Exception {
FileSystemUtils fsu = new FileSystemUtils();
try {
fsu.getFreeSpaceOS("", -1);
fail();
} catch (IllegalStateException ex) {}
}
public void testGetFreeSpaceOS_String_Other() throws Exception {
FileSystemUtils fsu = new FileSystemUtils();
try {
fsu.getFreeSpaceOS("", 0);
fail();
} catch (IllegalStateException ex) {}
}
public void testGetFreeSpaceOS_String_Windows() throws Exception {
FileSystemUtils fsu = new FileSystemUtils() {
protected long getFreeSpaceWindows(String path) throws IOException {
return 12345L;
}
};
assertEquals(12345L, fsu.getFreeSpaceOS("", 1));
}
public void testGetFreeSpaceOS_String_Unix() throws Exception {
FileSystemUtils fsu = new FileSystemUtils() {
protected long getFreeSpaceUnix(String path) throws IOException {
return 12345L;
}
};
assertEquals(12345L, fsu.getFreeSpaceOS("", 2));
}
//-----------------------------------------------------------------------
public void testGetFreeSpaceWindows_String_EmptyPath() throws Exception {
String lines =
" Volume in drive C is HDD\n" +
" Volume Serial Number is XXXX-YYYY\n" +
"\n" +
" Directory of C:\\Documents and Settings\\Xxxx\n" +
"\n" +
"19/08/2005 22:43 <DIR> .\n" +
"19/08/2005 22:43 <DIR> ..\n" +
"11/08/2005 01:07 81 build.properties\n" +
"17/08/2005 21:44 <DIR> Desktop\n" +
" 7 File(s) 180,260 bytes\n" +
" 10 Dir(s) 41,411,551,232 bytes free";
final StringReader reader = new StringReader(lines);
FileSystemUtils fsu = new FileSystemUtils() {
protected BufferedReader openProcessStream(String[] params) {
assertEquals("dir /c ", params[2]);
return new BufferedReader(reader);
}
};
assertEquals(41411551232L, fsu.getFreeSpaceWindows(""));
}
public void testGetFreeSpaceWindows_String_NormalResponse() throws Exception {
String lines =
" Volume in drive C is HDD\n" +
" Volume Serial Number is XXXX-YYYY\n" +
"\n" +
" Directory of C:\\Documents and Settings\\Xxxx\n" +
"\n" +
"19/08/2005 22:43 <DIR> .\n" +
"19/08/2005 22:43 <DIR> ..\n" +
"11/08/2005 01:07 81 build.properties\n" +
"17/08/2005 21:44 <DIR> Desktop\n" +
" 7 File(s) 180,260 bytes\n" +
" 10 Dir(s) 41,411,551,232 bytes free";
final StringReader reader = new StringReader(lines);
FileSystemUtils fsu = new FileSystemUtils() {
protected BufferedReader openProcessStream(String[] params) {
assertEquals("dir /c C:", params[2]);
return new BufferedReader(reader);
}
};
assertEquals(41411551232L, fsu.getFreeSpaceWindows("C:"));
}
public void testGetFreeSpaceWindows_String_StripDrive() throws Exception {
String lines =
" Volume in drive C is HDD\n" +
" Volume Serial Number is XXXX-YYYY\n" +
"\n" +
" Directory of C:\\Documents and Settings\\Xxxx\n" +
"\n" +
"19/08/2005 22:43 <DIR> .\n" +
"19/08/2005 22:43 <DIR> ..\n" +
"11/08/2005 01:07 81 build.properties\n" +
"17/08/2005 21:44 <DIR> Desktop\n" +
" 7 File(s) 180,260 bytes\n" +
" 10 Dir(s) 41,411,551,232 bytes free";
final StringReader reader = new StringReader(lines);
FileSystemUtils fsu = new FileSystemUtils() {
protected BufferedReader openProcessStream(String[] params) {
assertEquals("dir /c C:", params[2]);
return new BufferedReader(reader);
}
};
assertEquals(41411551232L, fsu.getFreeSpaceWindows("C:\\somedir"));
}
public void testGetFreeSpaceWindows_String_EmptyResponse() throws Exception {
String lines = "";
final StringReader reader = new StringReader(lines);
FileSystemUtils fsu = new FileSystemUtils() {
protected BufferedReader openProcessStream(String[] params) {
return new BufferedReader(reader);
}
};
try {
fsu.getFreeSpaceWindows("C:");
fail();
} catch (IOException ex) {}
}
//-----------------------------------------------------------------------
public void testGetFreeSpaceUnix_String_EmptyPath() throws Exception {
String lines =
"Filesystem 1K-blocks Used Available Use% Mounted on\n" +
"xxx:/home/users/s 14428928 12956424 1472504 90% /home/users/s";
final StringReader reader = new StringReader(lines);
FileSystemUtils fsu = new FileSystemUtils() {
protected BufferedReader openProcessStream(String[] params) {
return new BufferedReader(reader);
}
};
try {
fsu.getFreeSpaceUnix("");
fail();
} catch (IllegalArgumentException ex) {}
}
public void testGetFreeSpaceUnix_String_NormalResponse() throws Exception {
String lines =
"Filesystem 1K-blocks Used Available Use% Mounted on\n" +
"xxx:/home/users/s 14428928 12956424 1472504 90% /home/users/s";
final StringReader reader = new StringReader(lines);
FileSystemUtils fsu = new FileSystemUtils() {
protected BufferedReader openProcessStream(String[] params) {
return new BufferedReader(reader);
}
};
assertEquals(1472504L, fsu.getFreeSpaceUnix("/home/users/s"));
}
public void testGetFreeSpaceUnix_String_LongResponse() throws Exception {
String lines =
"Filesystem 1K-blocks Used Available Use% Mounted on\n" +
"xxx-yyyyyyy-zzz:/home/users/s\n" +
" 14428928 12956424 1472504 90% /home/users/s";
final StringReader reader = new StringReader(lines);
FileSystemUtils fsu = new FileSystemUtils() {
protected BufferedReader openProcessStream(String[] params) {
return new BufferedReader(reader);
}
};
assertEquals(1472504L, fsu.getFreeSpaceUnix("/home/users/s"));
}
public void testGetFreeSpaceUnix_String_EmptyResponse() throws Exception {
String lines = "";
final StringReader reader = new StringReader(lines);
FileSystemUtils fsu = new FileSystemUtils() {
protected BufferedReader openProcessStream(String[] params) {
return new BufferedReader(reader);
}
};
try {
fsu.getFreeSpaceUnix("/home/users/s");
fail();
} catch (IOException ex) {}
}
public void testGetFreeSpaceUnix_String_InvalidResponse1() throws Exception {
String lines =
"Filesystem 1K-blocks Used Available Use% Mounted on\n" +
" 14428928 12956424 100";
final StringReader reader = new StringReader(lines);
FileSystemUtils fsu = new FileSystemUtils() {
protected BufferedReader openProcessStream(String[] params) {
return new BufferedReader(reader);
}
};
try {
fsu.getFreeSpaceUnix("/home/users/s");
fail();
} catch (IOException ex) {}
}
public void testGetFreeSpaceUnix_String_InvalidResponse2() throws Exception {
String lines =
"Filesystem 1K-blocks Used Available Use% Mounted on\n" +
"xxx:/home/users/s 14428928 12956424 nnnnnnn 90% /home/users/s";
final StringReader reader = new StringReader(lines);
FileSystemUtils fsu = new FileSystemUtils() {
protected BufferedReader openProcessStream(String[] params) {
return new BufferedReader(reader);
}
};
try {
fsu.getFreeSpaceUnix("/home/users/s");
fail();
} catch (IOException ex) {}
}
public void testGetFreeSpaceUnix_String_InvalidResponse3() throws Exception {
String lines =
"Filesystem 1K-blocks Used Available Use% Mounted on\n" +
"xxx:/home/users/s 14428928 12956424 -1 90% /home/users/s";
final StringReader reader = new StringReader(lines);
FileSystemUtils fsu = new FileSystemUtils() {
protected BufferedReader openProcessStream(String[] params) {
return new BufferedReader(reader);
}
};
try {
fsu.getFreeSpaceUnix("/home/users/s");
fail();
} catch (IOException ex) {}
}
public void testGetFreeSpaceUnix_String_InvalidResponse4() throws Exception {
String lines =
"Filesystem 1K-blocks Used Available Use% Mounted on\n" +
"xxx-yyyyyyy-zzz:/home/users/s";
final StringReader reader = new StringReader(lines);
FileSystemUtils fsu = new FileSystemUtils() {
protected BufferedReader openProcessStream(String[] params) {
return new BufferedReader(reader);
}
};
try {
fsu.getFreeSpaceUnix("/home/users/s");
fail();
} catch (IOException ex) {}
}
}
| Change test to try and make it pass Gump
git-svn-id: 93ad1b128ef73f61fb131daf820f82551b37ed4a@267448 13f79535-47bb-0310-9956-ffa450edef68
| src/test/org/apache/commons/io/FileSystemUtilsTestCase.java | Change test to try and make it pass Gump |
|
Java | apache-2.0 | bb6f61b89187771e9f5ec2260f60895c088510fc | 0 | apache/jmeter,apache/jmeter,benbenw/jmeter,apache/jmeter,ham1/jmeter,ham1/jmeter,apache/jmeter,etnetera/jmeter,apache/jmeter,benbenw/jmeter,etnetera/jmeter,etnetera/jmeter,ham1/jmeter,etnetera/jmeter,benbenw/jmeter,etnetera/jmeter,ham1/jmeter,benbenw/jmeter,ham1/jmeter | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.jmeter.threads;
/**
* Provides context service for JMeter threads.
* Keeps track of active and total thread counts.
*/
public final class JMeterContextService {
static private ThreadLocal threadContext = new ThreadLocal() {
public Object initialValue() {
return new JMeterContext();
}
};
private static long testStart = 0;
private static int numberOfActiveThreads = 0;
private static int totalThreads = 0;
/**
* Private constructor to prevent instantiation.
*/
private JMeterContextService() {
}
static public JMeterContext getContext() {
return (JMeterContext) threadContext.get();
}
static public synchronized void startTest() {
if (testStart == 0) {
numberOfActiveThreads = 0;
testStart = System.currentTimeMillis();
threadContext = new ThreadLocal() {
public Object initialValue() {
return new JMeterContext();
}
};
}
}
/**
* Increment number of active threads.
*/
static synchronized void incrNumberOfThreads() {
numberOfActiveThreads++;
}
/**
* Decrement number of active threads.
*/
static synchronized void decrNumberOfThreads() {
numberOfActiveThreads--;
}
/**
* Get the number of currently active threads
* @return active thread count
*/
static public synchronized int getNumberOfThreads() {
return numberOfActiveThreads;
}
static public synchronized void endTest() {
testStart = 0;
numberOfActiveThreads = 0;
}
static public synchronized long getTestStartTime() {// NOT USED
return testStart;
}
/**
* Get the total number of threads (>= active)
* @return total thread count
*/
public static synchronized int getTotalThreads() {
return totalThreads;
}
/**
* Update the total number of threads
* @param thisGroup number of threads in this thread group
*/
public static synchronized void addTotalThreads(int thisGroup) {
totalThreads += thisGroup;
}
/**
* Set total threads to zero
*/
public static synchronized void clearTotalThreads() {
totalThreads = 0;
}
}
| src/core/org/apache/jmeter/threads/JMeterContextService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.jmeter.threads;
/**
* @version $Revision$
*/
public final class JMeterContextService {
static private ThreadLocal threadContext = new ThreadLocal() {
public Object initialValue() {
return new JMeterContext();
}
};
private static long testStart = 0;
private static int numberOfThreads = 0; // Active thread count
private static int totalThreads = 0;
/**
* Private constructor to prevent instantiation.
*/
private JMeterContextService() {
}
static public JMeterContext getContext() {
return (JMeterContext) threadContext.get();
}
static public void startTest() {//TODO should this be synchronized?
if (testStart == 0) {
numberOfThreads = 0;
testStart = System.currentTimeMillis();
threadContext = new ThreadLocal() {
public Object initialValue() {
return new JMeterContext();
}
};
}
}
static synchronized void incrNumberOfThreads() {
numberOfThreads++;
}
static synchronized void decrNumberOfThreads() {
numberOfThreads--;
}
static public synchronized int getNumberOfThreads() {
return numberOfThreads;
}
static public void endTest() {//TODO should this be synchronized?
testStart = 0;
numberOfThreads = 0;
}
static public long getTestStartTime() {// NOT USED
return testStart;
}
public static synchronized int getTotalThreads() {
return totalThreads;
}
public static synchronized void addTotalThreads(int thisGroup) {
totalThreads += thisGroup;
}
public static synchronized void clearTotalThreads() {
totalThreads = 0;
}
}
| Update Javadoc
Ensure all accesses to counts are synchronized
git-svn-id: https://svn.apache.org/repos/asf/jakarta/jmeter/trunk@632686 13f79535-47bb-0310-9956-ffa450edef68
Former-commit-id: 7cc06fc381a99c453a1995b386c91c3018d936fa | src/core/org/apache/jmeter/threads/JMeterContextService.java | Update Javadoc Ensure all accesses to counts are synchronized |
|
Java | apache-2.0 | 685ee2f2b0ea80dc0465e327ab6dcfc6e1d116e5 | 0 | dita-ot/dita-ot,drmacro/dita-ot,shaneataylor/dita-ot,shaneataylor/dita-ot,shaneataylor/dita-ot,jelovirt/muuntaja,infotexture/dita-ot,eerohele/dita-ot,zanyants/dita-ot,jelovirt/muuntaja,drmacro/dita-ot,eerohele/dita-ot,infotexture/dita-ot,drmacro/dita-ot,dita-ot/dita-ot,dita-ot/dita-ot,zanyants/dita-ot,dita-ot/dita-ot,robander/dita-ot,eerohele/dita-ot,zanyants/dita-ot,dita-ot/dita-ot,doctales/dita-ot,robander/dita-ot,queshaw/dita-ot,Hasimir/dita-ot,Hasimir/dita-ot,doctales/dita-ot,queshaw/dita-ot,Hasimir/dita-ot,doctales/dita-ot,robander/dita-ot,infotexture/dita-ot,shaneataylor/dita-ot,infotexture/dita-ot,queshaw/dita-ot,shaneataylor/dita-ot,robander/dita-ot,eerohele/dita-ot,robander/dita-ot,queshaw/dita-ot,infotexture/dita-ot,jelovirt/muuntaja,doctales/dita-ot,drmacro/dita-ot,Hasimir/dita-ot,drmacro/dita-ot,zanyants/dita-ot | /*
* This file is part of the DITA Open Toolkit project.
* See the accompanying license.txt file for applicable licenses.
*/
/*
* (c) Copyright IBM Corp. 2004, 2005 All Rights Reserved.
*/
package org.dita.dost.module;
import static org.dita.dost.util.Constants.*;
import static org.dita.dost.writer.DitaWriter.*;
import static org.dita.dost.util.Job.*;
import static org.dita.dost.util.Configuration.*;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Properties;
import java.util.Queue;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;
import org.dita.dost.exception.DITAOTException;
import org.dita.dost.log.MessageUtils;
import org.dita.dost.pipeline.AbstractPipelineInput;
import org.dita.dost.pipeline.AbstractPipelineOutput;
import org.dita.dost.reader.DitaValReader;
import org.dita.dost.reader.SubjectSchemeReader;
import org.dita.dost.util.DelayConrefUtils;
import org.dita.dost.util.FilterUtils.Action;
import org.dita.dost.util.FilterUtils.FilterKey;
import org.dita.dost.util.CatalogUtils;
import org.dita.dost.util.FileUtils;
import org.dita.dost.util.FilterUtils;
import org.dita.dost.util.Job;
import org.dita.dost.util.KeyDef;
import org.dita.dost.util.StringUtils;
import org.dita.dost.util.URLUtils;
import org.dita.dost.util.XMLUtils;
import org.dita.dost.writer.DitaWriter;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLFilter;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLFilterImpl;
/**
* DebugAndFilterModule implement the second step in preprocess. It will insert debug
* information into every dita files and filter out the information that is not
* necessary.
*
* @author Zhang, Yuan Peng
*/
final class DebugAndFilterModule extends AbstractPipelineModuleImpl {
/** Subject scheme file extension */
private static final String SUBJECT_SCHEME_EXTENSION = ".subm";
/** Absolute input map path. */
private File inputMap = null;
@Override
public AbstractPipelineOutput execute(final AbstractPipelineInput input) throws DITAOTException {
if (logger == null) {
throw new IllegalStateException("Logger not set");
}
try {
final String baseDir = input.getAttribute(ANT_INVOKER_PARAM_BASEDIR);
/* Absolute DITA-OT base path. */
File ditaDir = new File(input.getAttribute(ANT_INVOKER_EXT_PARAM_DITADIR));
final String transtype = input.getAttribute(ANT_INVOKER_EXT_PARAM_TRANSTYPE);
File ditavalFile = null;
if (input.getAttribute(ANT_INVOKER_PARAM_DITAVAL) != null ) {
ditavalFile = new File(input.getAttribute(ANT_INVOKER_PARAM_DITAVAL));
if (!ditavalFile.isAbsolute()) {
ditavalFile = new File(baseDir, ditavalFile.getPath()).getAbsoluteFile();
}
}
/* Absolute input directory path. */
File inputDir = new File(job.getInputDir());
if (!inputDir.isAbsolute()) {
inputDir = new File(baseDir, inputDir.getPath()).getAbsoluteFile();
}
inputMap = new File(inputDir, job.getInputMap()).getAbsoluteFile();
// Output subject schemas
outputSubjectScheme();
final DitaValReader filterReader = new DitaValReader();
filterReader.setLogger(logger);
filterReader.initXMLReader("yes".equals(input.getAttribute(ANT_INVOKER_EXT_PARAN_SETSYSTEMID)));
FilterUtils filterUtils = new FilterUtils(printTranstype.contains(transtype));
filterUtils.setLogger(logger);
if (ditavalFile != null){
filterReader.read(ditavalFile.getAbsoluteFile());
filterUtils.setFilterMap(filterReader.getFilterMap());
}
final SubjectSchemeReader subjectSchemeReader = new SubjectSchemeReader();
subjectSchemeReader.setLogger(logger);
final DitaWriter fileWriter = new DitaWriter();
fileWriter.setLogger(logger);
try{
final boolean xmlValidate = Boolean.valueOf(input.getAttribute("validate"));
boolean setSystemid = true;
fileWriter.initXMLReader(ditaDir.getAbsoluteFile(),xmlValidate, setSystemid);
} catch (final SAXException e) {
throw new DITAOTException(e.getMessage(), e);
}
fileWriter.setTempDir(job.tempDir);
if (filterUtils != null) {
fileWriter.setFilterUtils(filterUtils);
}
if (transtype.equals(INDEX_TYPE_ECLIPSEHELP)) {
fileWriter.setDelayConrefUtils(new DelayConrefUtils());
}
fileWriter.setKeyDefinitions(KeyDef.readKeydef(new File(job.tempDir, KEYDEF_LIST_FILE)));
job.setGeneratecopyouter(input.getAttribute(ANT_INVOKER_EXT_PARAM_GENERATECOPYOUTTER));
job.setOutterControl(input.getAttribute(ANT_INVOKER_EXT_PARAM_OUTTERCONTROL));
job.setOnlyTopicInMap(input.getAttribute(ANT_INVOKER_EXT_PARAM_ONLYTOPICINMAP));
job.setInputFile(inputMap);
job.setOutputDir(new File(input.getAttribute(ANT_INVOKER_EXT_PARAM_OUTPUTDIR)));
fileWriter.setJob(job);
final Map<String, Set<String>> dic = readMapFromXML(FILE_NAME_SUBJECT_DICTIONARY);
for (final FileInfo f: job.getFileInfo()) {
if (ATTR_FORMAT_VALUE_DITA.equals(f.format) || ATTR_FORMAT_VALUE_DITAMAP.equals(f.format)
|| f.isConrefTarget || f.isCopyToSource) {
final File filename = f.file;
final File currentFile = new File(inputDir, filename.getPath());
if (!currentFile.exists()) {
// Assuming this is an copy-to target file, ignore it
logger.debug("Ignoring a copy-to file " + filename);
continue;
}
logger.info("Processing " + currentFile.getAbsolutePath());
final Set<String> schemaSet = dic.get(filename.getPath());
filterReader.reset();
if (schemaSet != null) {
subjectSchemeReader.reset();
final FilterUtils fu = new FilterUtils(printTranstype.contains(transtype));
fu.setLogger(logger);
for (final String schema: schemaSet) {
subjectSchemeReader.loadSubjectScheme(FileUtils.resolve(job.tempDir.getAbsolutePath(), schema) + SUBJECT_SCHEME_EXTENSION);
}
if (ditavalFile != null){
filterReader.filterReset();
filterReader.setSubjectScheme(subjectSchemeReader.getSubjectSchemeMap());
filterReader.read(ditavalFile.getAbsoluteFile());
final Map<FilterKey, Action> fm = new HashMap<FilterKey, Action>();
fm.putAll(filterReader.getFilterMap());
fm.putAll(filterUtils.getFilterMap());
fu.setFilterMap(Collections.unmodifiableMap(fm));
} else {
fu.setFilterMap(Collections.EMPTY_MAP);
}
fileWriter.setFilterUtils(fu);
fileWriter.setValidateMap(subjectSchemeReader.getValidValuesMap());
fileWriter.setDefaultValueMap(subjectSchemeReader.getDefaultValueMap());
} else {
fileWriter.setFilterUtils(filterUtils);
}
fileWriter.write(inputDir, filename);
}
}
// reload the property for processing of copy-to
performCopytoTask(job.tempDir, job);
} catch (final Exception e) {
e.printStackTrace();
throw new DITAOTException("Exception doing debug and filter module processing: " + e.getMessage(), e);
}
return null;
}
/**
* Read a map from XML properties file. Values are split by {@link org.dita.dost.util.Constants#COMMA COMMA} into a set.
*
* @param filename XML properties file path, relative to temporary directory
*/
private Map<String, Set<String>> readMapFromXML(final String filename) {
final File inputFile = new File(job.tempDir, filename);
final Map<String, Set<String>> graph = new HashMap<String, Set<String>>();
if (!inputFile.exists()) {
return graph;
}
final Properties prop = new Properties();
FileInputStream in = null;
try {
in = new FileInputStream(inputFile);
prop.loadFromXML(in);
in.close();
} catch (final IOException e) {
logger.error(e.getMessage(), e) ;
} finally {
if (in != null) {
try {
in.close();
} catch (final IOException e) {
logger.error(e.getMessage(), e) ;
}
}
}
for (final Map.Entry<Object, Object> entry: prop.entrySet()) {
final String key = (String) entry.getKey();
final String value = (String) entry.getValue();
graph.put(key, StringUtils.restoreSet(value, COMMA));
}
return Collections.unmodifiableMap(graph);
}
/**
* Output subject schema file.
*
* @throws DITAOTException if generation files
*/
private void outputSubjectScheme() throws DITAOTException {
final Map<String, Set<String>> graph = readMapFromXML(FILE_NAME_SUBJECT_RELATION);
final Queue<String> queue = new LinkedList<String>();
final Set<String> visitedSet = new HashSet<String>();
for (final Map.Entry<String, Set<String>> entry: graph.entrySet()) {
queue.offer(entry.getKey());
}
try {
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
final DocumentBuilder builder = factory.newDocumentBuilder();
builder.setEntityResolver(CatalogUtils.getCatalogResolver());
while (!queue.isEmpty()) {
final String parent = queue.poll();
final Set<String> children = graph.get(parent);
if (children != null) {
queue.addAll(children);
}
if ("ROOT".equals(parent) || visitedSet.contains(parent)) {
continue;
}
visitedSet.add(parent);
String tmprel = FileUtils.getRelativeUnixPath(inputMap.getAbsolutePath(), parent);
tmprel = FileUtils.resolve(job.tempDir.getAbsolutePath(), tmprel) + SUBJECT_SCHEME_EXTENSION;
Document parentRoot = null;
if (!FileUtils.fileExists(tmprel)) {
parentRoot = builder.parse(new InputSource(new FileInputStream(parent)));
} else {
parentRoot = builder.parse(new InputSource(new FileInputStream(tmprel)));
}
if (children != null) {
for (final String childpath: children) {
final Document childRoot = builder.parse(new InputSource(new FileInputStream(childpath)));
mergeScheme(parentRoot, childRoot);
String rel = FileUtils.getRelativeUnixPath(inputMap.getAbsolutePath(), childpath);
rel = FileUtils.resolve(job.tempDir.getAbsolutePath(), rel) + SUBJECT_SCHEME_EXTENSION;
generateScheme(rel, childRoot);
}
}
//Output parent scheme
String rel = FileUtils.getRelativeUnixPath(inputMap.getAbsolutePath(), parent);
rel = FileUtils.resolve(job.tempDir.getAbsolutePath(), rel) + SUBJECT_SCHEME_EXTENSION;
generateScheme(rel, parentRoot);
}
} catch (final Exception e) {
logger.error(e.getMessage(), e) ;
throw new DITAOTException(e);
}
}
private void mergeScheme(final Document parentRoot, final Document childRoot) {
final Queue<Element> pQueue = new LinkedList<Element>();
pQueue.offer(parentRoot.getDocumentElement());
while (!pQueue.isEmpty()) {
final Element pe = pQueue.poll();
NodeList pList = pe.getChildNodes();
for (int i = 0; i < pList.getLength(); i++) {
final Node node = pList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
pQueue.offer((Element)node);
}
}
String value = pe.getAttribute(ATTRIBUTE_NAME_CLASS);
if (StringUtils.isEmptyString(value)
|| !SUBJECTSCHEME_SUBJECTDEF.matches(value)) {
continue;
}
if (!StringUtils.isEmptyString(
value = pe.getAttribute(ATTRIBUTE_NAME_KEYREF))) {
// extend child scheme
final Element target = searchForKey(childRoot.getDocumentElement(), value);
if (target == null) {
/*
* TODO: we have a keyref here to extend into child scheme, but can't
* find any matching <subjectdef> in child scheme. Shall we throw out
* a warning?
*
* Not for now, just bypass it.
*/
continue;
}
// target found
pList = pe.getChildNodes();
for (int i = 0; i < pList.getLength(); i++) {
final Node tmpnode = childRoot.importNode(pList.item(i), false);
if (tmpnode.getNodeType() == Node.ELEMENT_NODE
&& searchForKey(target,
((Element)tmpnode).getAttribute(ATTRIBUTE_NAME_KEYS)) != null) {
continue;
}
target.appendChild(tmpnode);
}
} else if (!StringUtils.isEmptyString(
value = pe.getAttribute(ATTRIBUTE_NAME_KEYS))) {
// merge into parent scheme
final Element target = searchForKey(childRoot.getDocumentElement(), value);
if (target != null) {
pList = target.getChildNodes();
for (int i = 0; i < pList.getLength(); i++) {
final Node tmpnode = parentRoot.importNode(pList.item(i), false);
if (tmpnode.getNodeType() == Node.ELEMENT_NODE
&& searchForKey(pe,
((Element)tmpnode).getAttribute(ATTRIBUTE_NAME_KEYS)) != null) {
continue;
}
pe.appendChild(tmpnode);
}
}
}
}
}
private Element searchForKey(final Element root, final String key) {
if (root == null || StringUtils.isEmptyString(key)) {
return null;
}
final Queue<Element> queue = new LinkedList<Element>();
queue.offer(root);
while (!queue.isEmpty()) {
final Element pe = queue.poll();
final NodeList pchildrenList = pe.getChildNodes();
for (int i = 0; i < pchildrenList.getLength(); i++) {
final Node node = pchildrenList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
queue.offer((Element)node);
}
}
String value = pe.getAttribute(ATTRIBUTE_NAME_CLASS);
if (StringUtils.isEmptyString(value)
|| !SUBJECTSCHEME_SUBJECTDEF.matches(value)) {
continue;
}
value = pe.getAttribute(ATTRIBUTE_NAME_KEYS);
if (StringUtils.isEmptyString(value)) {
continue;
}
if (value.equals(key)) {
return pe;
}
}
return null;
}
/**
* Serialize subject scheme file.
*
* @param filename output filepath
* @param root subject scheme document
*
* @throws DITAOTException if generation fails
*/
private void generateScheme(final String filename, final Document root) throws DITAOTException {
FileOutputStream out = null;
try {
final File f = new File(filename);
final File p = f.getParentFile();
if (!p.exists() && !p.mkdirs()) {
throw new IOException("Failed to make directory " + p.getAbsolutePath());
}
out = new FileOutputStream(new File(filename));
final StreamResult res = new StreamResult(out);
final DOMSource ds = new DOMSource(root);
final TransformerFactory tff = TransformerFactory.newInstance();
final Transformer tf = tff.newTransformer();
tf.transform(ds, res);
} catch (final Exception e) {
logger.error(e.getMessage(), e) ;
throw new DITAOTException(e);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
throw new DITAOTException(e);
}
}
}
}
/**
* Execute copy-to task, generate copy-to targets base on sources
*/
private void performCopytoTask(final File tempDir, final Job job) {
final Map<File, File> copytoMap = job.getCopytoMap();
for (final Map.Entry<File, File> entry: copytoMap.entrySet()) {
final File copytoTarget = entry.getKey();
final File copytoSource = entry.getValue();
final File srcFile = new File(tempDir, copytoSource.getPath());
final File targetFile = new File(tempDir, copytoTarget.getPath());
if (targetFile.exists()) {
/*logger
.logWarn(new StringBuffer("Copy-to task [copy-to=\"")
.append(copytoTarget)
.append("\"] which points to an existed file was ignored.").toString());*/
logger.warn(MessageUtils.getInstance().getMessage("DOTX064W", copytoTarget.getPath()).toString());
}else{
final File inputMapInTemp = new File(tempDir, job.getInputMap()).getAbsoluteFile();
copyFileWithPIReplaced(srcFile, targetFile, copytoTarget, inputMapInTemp);
}
}
}
/**
* Copy files and replace workdir PI contents.
*
* @param src
* @param target
* @param copytoTargetFilename
* @param inputMapInTemp
*/
public void copyFileWithPIReplaced(final File src, final File target, final File copytoTargetFilename, final File inputMapInTemp) {
if (!target.getParentFile().exists() && !target.getParentFile().mkdirs()) {
logger.error("Failed to create copy-to target directory " + target.getParentFile().getAbsolutePath());
return;
}
final DitaWriter dw = new DitaWriter();
dw.setJob(job);
final String path2project = dw.getPathtoProject(copytoTargetFilename, target, inputMapInTemp);
final File workdir = target.getParentFile();
XMLFilter filter = new CopyToFilter(workdir, path2project);
logger.info("Processing " + target.getAbsolutePath());
try {
XMLUtils.transform(src, target, Arrays.asList(filter));
} catch (final DITAOTException e) {
logger.error("Failed to write copy-to file: " + e.getMessage(), e);
}
}
/**
* XML filter to rewrite processing instructions to reflect copy-to location. The following processing-instructions are
* processed:
*
* <ul>
* <li>{@link DitaWriter#PI_WORKDIR_TARGET PI_WORKDIR_TARGET}</li>
* <li>{@link DitaWriter#PI_WORKDIR_TARGET_URI PI_WORKDIR_TARGET_URI}</li>
* <li>{@link DitaWriter#PI_PATH2PROJ_TARGET PI_PATH2PROJ_TARGET}</li>
* <li>{@link DitaWriter#PI_PATH2PROJ_TARGET_URI PI_PATH2PROJ_TARGET_URI}</li>
* </ul>
*/
private static final class CopyToFilter extends XMLFilterImpl {
private final File workdir;
private final String path2project;
CopyToFilter(final File workdir, final String path2project) {
super();
this.workdir = workdir;
this.path2project = path2project;
}
@Override
public void processingInstruction(final String target, final String data) throws SAXException {
String d = data;
if(target.equals(PI_WORKDIR_TARGET)) {
if (workdir != null) {
try {
if (OS_NAME.toLowerCase().indexOf(OS_NAME_WINDOWS) == -1) {
d = workdir.getCanonicalPath();
} else {
d = UNIX_SEPARATOR + workdir.getCanonicalPath();
}
} catch (final IOException e) {
throw new RuntimeException("Failed to get canonical path for working directory: " + e.getMessage(), e);
}
}
} else if(target.equals(PI_WORKDIR_TARGET_URI)) {
if (workdir != null) {
d = workdir.toURI().toString();
}
} else if (target.equals(PI_PATH2PROJ_TARGET)) {
if (path2project != null) {
d = path2project;
}
} else if (target.equals(PI_PATH2PROJ_TARGET_URI)) {
if (path2project != null) {
d = URLUtils.correct(FileUtils.separatorsToUnix(path2project), true);
}
}
getContentHandler().processingInstruction(target, d);
}
}
}
| src/main/java/org/dita/dost/module/DebugAndFilterModule.java | /*
* This file is part of the DITA Open Toolkit project.
* See the accompanying license.txt file for applicable licenses.
*/
/*
* (c) Copyright IBM Corp. 2004, 2005 All Rights Reserved.
*/
package org.dita.dost.module;
import static org.dita.dost.util.Constants.*;
import static org.dita.dost.writer.DitaWriter.*;
import static org.dita.dost.util.Job.*;
import static org.dita.dost.util.Configuration.*;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Properties;
import java.util.Queue;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;
import org.dita.dost.exception.DITAOTException;
import org.dita.dost.log.MessageUtils;
import org.dita.dost.pipeline.AbstractPipelineInput;
import org.dita.dost.pipeline.AbstractPipelineOutput;
import org.dita.dost.reader.DitaValReader;
import org.dita.dost.reader.SubjectSchemeReader;
import org.dita.dost.util.DelayConrefUtils;
import org.dita.dost.util.FilterUtils.Action;
import org.dita.dost.util.FilterUtils.FilterKey;
import org.dita.dost.util.CatalogUtils;
import org.dita.dost.util.FileUtils;
import org.dita.dost.util.FilterUtils;
import org.dita.dost.util.Job;
import org.dita.dost.util.KeyDef;
import org.dita.dost.util.StringUtils;
import org.dita.dost.util.URLUtils;
import org.dita.dost.util.XMLUtils;
import org.dita.dost.writer.DitaWriter;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLFilter;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLFilterImpl;
/**
* DebugAndFilterModule implement the second step in preprocess. It will insert debug
* information into every dita files and filter out the information that is not
* necessary.
*
* @author Zhang, Yuan Peng
*/
final class DebugAndFilterModule extends AbstractPipelineModuleImpl {
/** Subject scheme file extension */
private static final String SUBJECT_SCHEME_EXTENSION = ".subm";
/** Absolute input map path. */
private File inputMap = null;
@Override
public AbstractPipelineOutput execute(final AbstractPipelineInput input) throws DITAOTException {
if (logger == null) {
throw new IllegalStateException("Logger not set");
}
try {
final String baseDir = input.getAttribute(ANT_INVOKER_PARAM_BASEDIR);
/* Absolute DITA-OT base path. */
File ditaDir = new File(input.getAttribute(ANT_INVOKER_EXT_PARAM_DITADIR));
final String transtype = input.getAttribute(ANT_INVOKER_EXT_PARAM_TRANSTYPE);
File ditavalFile = null;
if (input.getAttribute(ANT_INVOKER_PARAM_DITAVAL) != null ) {
ditavalFile = new File(input.getAttribute(ANT_INVOKER_PARAM_DITAVAL));
if (!ditavalFile.isAbsolute()) {
ditavalFile = new File(baseDir, ditavalFile.getPath()).getAbsoluteFile();
}
}
/* Absolute input directory path. */
File inputDir = new File(job.getInputDir());
if (!inputDir.isAbsolute()) {
inputDir = new File(baseDir, inputDir.getPath()).getAbsoluteFile();
}
inputMap = new File(inputDir, job.getInputMap()).getAbsoluteFile();
// Output subject schemas
outputSubjectScheme();
final DitaValReader filterReader = new DitaValReader();
filterReader.setLogger(logger);
filterReader.initXMLReader("yes".equals(input.getAttribute(ANT_INVOKER_EXT_PARAN_SETSYSTEMID)));
FilterUtils filterUtils = new FilterUtils(printTranstype.contains(transtype));
filterUtils.setLogger(logger);
if (ditavalFile != null){
filterReader.read(ditavalFile.getAbsoluteFile());
filterUtils.setFilterMap(filterReader.getFilterMap());
}
final SubjectSchemeReader subjectSchemeReader = new SubjectSchemeReader();
subjectSchemeReader.setLogger(logger);
final DitaWriter fileWriter = new DitaWriter();
fileWriter.setLogger(logger);
try{
final boolean xmlValidate = Boolean.valueOf(input.getAttribute("validate"));
boolean setSystemid = true;
fileWriter.initXMLReader(ditaDir.getAbsoluteFile(),xmlValidate, setSystemid);
} catch (final SAXException e) {
throw new DITAOTException(e.getMessage(), e);
}
fileWriter.setTempDir(job.tempDir);
if (filterUtils != null) {
fileWriter.setFilterUtils(filterUtils);
}
if (transtype.equals(INDEX_TYPE_ECLIPSEHELP)) {
fileWriter.setDelayConrefUtils(new DelayConrefUtils());
}
fileWriter.setKeyDefinitions(KeyDef.readKeydef(new File(job.tempDir, KEYDEF_LIST_FILE)));
job.setGeneratecopyouter(input.getAttribute(ANT_INVOKER_EXT_PARAM_GENERATECOPYOUTTER));
job.setOutterControl(input.getAttribute(ANT_INVOKER_EXT_PARAM_OUTTERCONTROL));
job.setOnlyTopicInMap(input.getAttribute(ANT_INVOKER_EXT_PARAM_ONLYTOPICINMAP));
job.setInputFile(inputMap);
job.setOutputDir(new File(input.getAttribute(ANT_INVOKER_EXT_PARAM_OUTPUTDIR)));
fileWriter.setJob(job);
final Map<String, Set<String>> dic = readMapFromXML(FILE_NAME_SUBJECT_DICTIONARY);
for (final FileInfo f: job.getFileInfo()) {
if (ATTR_FORMAT_VALUE_DITA.equals(f.format) || ATTR_FORMAT_VALUE_DITAMAP.equals(f.format)
|| f.isConrefTarget || f.isCopyToSource) {
final File filename = f.file;
final File currentFile = new File(inputDir, filename.getPath());
if (!currentFile.exists()) {
// Assuming this is an copy-to target file, ignore it
logger.debug("Ignoring a copy-to file " + filename);
continue;
}
logger.info("Processing " + currentFile.getAbsolutePath());
final Set<String> schemaSet = dic.get(filename.getPath());
filterReader.reset();
if (schemaSet != null) {
subjectSchemeReader.reset();
final FilterUtils fu = new FilterUtils(printTranstype.contains(transtype));
fu.setLogger(logger);
for (final String schema: schemaSet) {
subjectSchemeReader.loadSubjectScheme(FileUtils.resolve(job.tempDir.getAbsolutePath(), schema) + SUBJECT_SCHEME_EXTENSION);
}
if (ditavalFile != null){
filterReader.filterReset();
filterReader.setSubjectScheme(subjectSchemeReader.getSubjectSchemeMap());
filterReader.read(ditavalFile.getAbsoluteFile());
final Map<FilterKey, Action> fm = new HashMap<FilterKey, Action>();
fm.putAll(filterReader.getFilterMap());
fm.putAll(filterUtils.getFilterMap());
fu.setFilterMap(Collections.unmodifiableMap(fm));
} else {
fu.setFilterMap(Collections.EMPTY_MAP);
}
fileWriter.setFilterUtils(fu);
fileWriter.setValidateMap(subjectSchemeReader.getValidValuesMap());
fileWriter.setDefaultValueMap(subjectSchemeReader.getDefaultValueMap());
} else {
fileWriter.setFilterUtils(filterUtils);
}
fileWriter.write(inputDir, filename);
}
}
// reload the property for processing of copy-to
performCopytoTask(job.tempDir, job);
} catch (final Exception e) {
e.printStackTrace();
throw new DITAOTException("Exception doing debug and filter module processing: " + e.getMessage(), e);
}
return null;
}
/**
* Read a map from XML properties file. Values are split by {@link org.dita.dost.util.Constants#COMMA COMMA} into a set.
*
* @param filename XML properties file path, relative to temporary directory
*/
private Map<String, Set<String>> readMapFromXML(final String filename) {
final File inputFile = new File(job.tempDir, filename);
final Map<String, Set<String>> graph = new HashMap<String, Set<String>>();
if (!inputFile.exists()) {
return graph;
}
final Properties prop = new Properties();
FileInputStream in = null;
try {
in = new FileInputStream(inputFile);
prop.loadFromXML(in);
in.close();
} catch (final IOException e) {
logger.error(e.getMessage(), e) ;
} finally {
if (in != null) {
try {
in.close();
} catch (final IOException e) {
logger.error(e.getMessage(), e) ;
}
}
}
for (final Map.Entry<Object, Object> entry: prop.entrySet()) {
final String key = (String) entry.getKey();
final String value = (String) entry.getValue();
graph.put(key, StringUtils.restoreSet(value, COMMA));
}
return Collections.unmodifiableMap(graph);
}
/**
* Output subject schema file.
*
* @throws DITAOTException if generation files
*/
private void outputSubjectScheme() throws DITAOTException {
final Map<String, Set<String>> graph = readMapFromXML(FILE_NAME_SUBJECT_RELATION);
final Queue<String> queue = new LinkedList<String>();
final Set<String> visitedSet = new HashSet<String>();
for (final Map.Entry<String, Set<String>> entry: graph.entrySet()) {
queue.offer(entry.getKey());
}
try {
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
final DocumentBuilder builder = factory.newDocumentBuilder();
builder.setEntityResolver(CatalogUtils.getCatalogResolver());
while (!queue.isEmpty()) {
final String parent = queue.poll();
final Set<String> children = graph.get(parent);
if (children != null) {
queue.addAll(children);
}
if ("ROOT".equals(parent) || visitedSet.contains(parent)) {
continue;
}
visitedSet.add(parent);
String tmprel = FileUtils.getRelativeUnixPath(inputMap.getAbsolutePath(), parent);
tmprel = FileUtils.resolve(job.tempDir.getAbsolutePath(), tmprel) + SUBJECT_SCHEME_EXTENSION;
Document parentRoot = null;
if (!FileUtils.fileExists(tmprel)) {
parentRoot = builder.parse(new InputSource(new FileInputStream(parent)));
} else {
parentRoot = builder.parse(new InputSource(new FileInputStream(tmprel)));
}
if (children != null) {
for (final String childpath: children) {
final Document childRoot = builder.parse(new InputSource(new FileInputStream(childpath)));
mergeScheme(parentRoot, childRoot);
String rel = FileUtils.getRelativeUnixPath(inputMap.getAbsolutePath(), childpath);
rel = FileUtils.resolve(job.tempDir.getAbsolutePath(), rel) + SUBJECT_SCHEME_EXTENSION;
generateScheme(rel, childRoot);
}
}
//Output parent scheme
String rel = FileUtils.getRelativeUnixPath(inputMap.getAbsolutePath(), parent);
rel = FileUtils.resolve(job.tempDir.getAbsolutePath(), rel) + SUBJECT_SCHEME_EXTENSION;
generateScheme(rel, parentRoot);
}
} catch (final Exception e) {
logger.error(e.getMessage(), e) ;
throw new DITAOTException(e);
}
}
private void mergeScheme(final Document parentRoot, final Document childRoot) {
final Queue<Element> pQueue = new LinkedList<Element>();
pQueue.offer(parentRoot.getDocumentElement());
while (!pQueue.isEmpty()) {
final Element pe = pQueue.poll();
NodeList pList = pe.getChildNodes();
for (int i = 0; i < pList.getLength(); i++) {
final Node node = pList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
pQueue.offer((Element)node);
}
}
String value = pe.getAttribute(ATTRIBUTE_NAME_CLASS);
if (StringUtils.isEmptyString(value)
|| !SUBJECTSCHEME_SUBJECTDEF.matches(value)) {
continue;
}
if (!StringUtils.isEmptyString(
value = pe.getAttribute(ATTRIBUTE_NAME_KEYREF))) {
// extend child scheme
final Element target = searchForKey(childRoot.getDocumentElement(), value);
if (target == null) {
/*
* TODO: we have a keyref here to extend into child scheme, but can't
* find any matching <subjectdef> in child scheme. Shall we throw out
* a warning?
*
* Not for now, just bypass it.
*/
continue;
}
// target found
pList = pe.getChildNodes();
for (int i = 0; i < pList.getLength(); i++) {
final Node tmpnode = childRoot.importNode(pList.item(i), false);
if (tmpnode.getNodeType() == Node.ELEMENT_NODE
&& searchForKey(target,
((Element)tmpnode).getAttribute(ATTRIBUTE_NAME_KEYS)) != null) {
continue;
}
target.appendChild(tmpnode);
}
} else if (!StringUtils.isEmptyString(
value = pe.getAttribute(ATTRIBUTE_NAME_KEYS))) {
// merge into parent scheme
final Element target = searchForKey(childRoot.getDocumentElement(), value);
if (target != null) {
pList = target.getChildNodes();
for (int i = 0; i < pList.getLength(); i++) {
final Node tmpnode = parentRoot.importNode(pList.item(i), false);
if (tmpnode.getNodeType() == Node.ELEMENT_NODE
&& searchForKey(pe,
((Element)tmpnode).getAttribute(ATTRIBUTE_NAME_KEYS)) != null) {
continue;
}
pe.appendChild(tmpnode);
}
}
}
}
}
private Element searchForKey(final Element root, final String key) {
if (root == null || StringUtils.isEmptyString(key)) {
return null;
}
final Queue<Element> queue = new LinkedList<Element>();
queue.offer(root);
while (!queue.isEmpty()) {
final Element pe = queue.poll();
final NodeList pchildrenList = pe.getChildNodes();
for (int i = 0; i < pchildrenList.getLength(); i++) {
final Node node = pchildrenList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
queue.offer((Element)node);
}
}
String value = pe.getAttribute(ATTRIBUTE_NAME_CLASS);
if (StringUtils.isEmptyString(value)
|| !SUBJECTSCHEME_SUBJECTDEF.matches(value)) {
continue;
}
value = pe.getAttribute(ATTRIBUTE_NAME_KEYS);
if (StringUtils.isEmptyString(value)) {
continue;
}
if (value.equals(key)) {
return pe;
}
}
return null;
}
/**
* Serialize subject scheme file.
*
* @param filename output filepath
* @param root subject scheme document
*
* @throws DITAOTException if generation fails
*/
private void generateScheme(final String filename, final Document root) throws DITAOTException {
FileOutputStream out = null;
try {
final File f = new File(filename);
final File p = f.getParentFile();
if (!p.exists() && !p.mkdirs()) {
throw new IOException("Failed to make directory " + p.getAbsolutePath());
}
out = new FileOutputStream(new File(filename));
final StreamResult res = new StreamResult(out);
final DOMSource ds = new DOMSource(root);
final TransformerFactory tff = TransformerFactory.newInstance();
final Transformer tf = tff.newTransformer();
tf.transform(ds, res);
} catch (final Exception e) {
logger.error(e.getMessage(), e) ;
throw new DITAOTException(e);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
throw new DITAOTException(e);
}
}
}
}
/**
* Execute copy-to task, generate copy-to targets base on sources
*/
private void performCopytoTask(final File tempDir, final Job job) {
final Map<File, File> copytoMap = job.getCopytoMap();
for (final Map.Entry<File, File> entry: copytoMap.entrySet()) {
final File copytoTarget = entry.getKey();
final File copytoSource = entry.getValue();
final File srcFile = new File(tempDir, copytoSource.getPath());
final File targetFile = new File(tempDir, copytoTarget.getPath());
if (targetFile.exists()) {
/*logger
.logWarn(new StringBuffer("Copy-to task [copy-to=\"")
.append(copytoTarget)
.append("\"] which points to an existed file was ignored.").toString());*/
logger.warn(MessageUtils.getInstance().getMessage("DOTX064W", copytoTarget.getPath()).toString());
}else{
final File inputMapInTemp = new File(tempDir, job.getInputMap()).getAbsoluteFile();
copyFileWithPIReplaced(srcFile, targetFile, copytoTarget, inputMapInTemp);
}
}
}
/**
* Copy files and replace workdir PI contents.
*
* @param src
* @param target
* @param copytoTargetFilename
* @param inputMapInTemp
*/
public void copyFileWithPIReplaced(final File src, final File target, final File copytoTargetFilename, final File inputMapInTemp) {
if (!target.getParentFile().exists() && !target.getParentFile().mkdirs()) {
logger.error("Failed to create copy-to target directory " + target.getParentFile().getAbsolutePath());
return;
}
final DitaWriter dw = new DitaWriter();
dw.setJob(job);
final String path2project = dw.getPathtoProject(copytoTargetFilename, target, inputMapInTemp);
final File workdir = target.getParentFile();
XMLFilter filter = new CopyToFilter(workdir, path2project);
logger.info("Processing " + target.getAbsolutePath());
try {
XMLUtils.transform(src, target, Arrays.asList(filter));
} catch (final DITAOTException e) {
logger.error("Failed to write copy-to file: " + e.getMessage(), e);
}
}
/**
* XML filter to rewrite processing instructions to reflect copy-to location. The following processing-instructions are
* processed:
*
* <ul>
* <li>{@link DitaWriter#PI_WORKDIR_TARGET PI_WORKDIR_TARGET}</li>
* <li>{@link DitaWriter#PI_WORKDIR_TARGET_URI PI_WORKDIR_TARGET_URI}</li>
* <li>{@link DitaWriter#PI_PATH2PROJ_TARGET PI_PATH2PROJ_TARGET}</li>
* <li>{@link DitaWriter#PI_PATH2PROJ_TARGET_URI PI_PATH2PROJ_TARGET_URI}</li>
* </ul>
*/
private static final class CopyToFilter extends XMLFilterImpl {
private final File workdir;
private final String path2project;
CopyToFilter(final File workdir, final String path2project) {
super();
this.workdir = workdir;
this.path2project = path2project;
}
@Override
public void processingInstruction(final String target, final String data) throws SAXException {
String d = data;
if(target.equals(PI_WORKDIR_TARGET)) {
if (workdir != null) {
try {
if (OS_NAME.toLowerCase().indexOf(OS_NAME_WINDOWS) == -1) {
d = workdir.getCanonicalPath();
} else {
d = UNIX_SEPARATOR + workdir.getCanonicalPath();
}
} catch (final IOException e) {
throw new RuntimeException("Failed to get canonical path for working directory: " + e.getMessage(), e);
}
}
} else if(target.equals(PI_WORKDIR_TARGET_URI)) {
if (workdir != null) {
d = workdir.toURI().toString();
}
} else if (target.equals(PI_PATH2PROJ_TARGET)) {
if (path2project != null) {
d = path2project;
}
} else if (target.equals(PI_PATH2PROJ_TARGET_URI)) {
if (path2project != null) {
d = URLUtils.correct(path2project, true);
}
}
getContentHandler().processingInstruction(target, d);
}
}
}
| Fix URI generation bugs on Windows #1639
| src/main/java/org/dita/dost/module/DebugAndFilterModule.java | Fix URI generation bugs on Windows #1639 |
|
Java | apache-2.0 | 6fe9cd864bae1a761d8ee70651dc299e65b75809 | 0 | erdemolkun/instant-rates | package demoapps.exchangegraphics;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.DefaultAxisValueFormatter;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import java.util.List;
import java.util.Locale;
import butterknife.BindView;
import butterknife.ButterKnife;
import demoapps.exchangegraphics.data.BuySellRate;
import demoapps.exchangegraphics.data.Rate;
import demoapps.exchangegraphics.data.YorumlarRate;
import demoapps.exchangegraphics.provider.BigparaRateProvider;
import demoapps.exchangegraphics.provider.EnparaRateProvider;
import demoapps.exchangegraphics.provider.IRateProvider;
import demoapps.exchangegraphics.provider.YorumlarRateProvider;
/**
* Created by erdemmac on 24/11/2016.
*/
public class RatesActivity extends AppCompatActivity {
private List<BuySellRate> enparaRates;
private List<YorumlarRate> yorumlarRates;
@BindView(R.id.line_usd_chart)
LineChart lineChart;
@BindView(R.id.v_progress_wheel)
View vProgress;
private long startMilis;
IRateProvider enparaRateProvider, yorumlarRateProvider, bigparaRateProvider;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rates);
ButterKnife.bind(this);
startMilis = System.currentTimeMillis();
initUsdChart();
vProgress.setVisibility(View.GONE);
enparaRateProvider = new EnparaRateProvider(new IRateProvider.Callback<List<BuySellRate>>() {
@Override
public void onResult(List<BuySellRate> rates) {
enparaRates = rates;
BuySellRate rateUsd = null;
for (Rate rate : rates) {
if (rate.rateType == Rate.RateTypes.USD) {
rateUsd = (BuySellRate) rate;
}
addEntry(rateUsd != null ? rateUsd.value_sell_real : 0.0f, 1);
addEntry(rateUsd != null ? rateUsd.value_buy_real : 0.0f, 2);
}
}
@Override
public void onError() {
}
});
yorumlarRateProvider = new YorumlarRateProvider(new IRateProvider.Callback<List<YorumlarRate>>() {
@Override
public void onResult(List<YorumlarRate> rates) {
yorumlarRates = rates;
YorumlarRate rateUsd = null;
for (Rate rate : rates) {
if (rate.rateType == Rate.RateTypes.USD) {
rateUsd = (YorumlarRate) rate;
}
}
addEntry(rateUsd != null ? rateUsd.realValue : 0.0f, 0);
}
@Override
public void onError() {
}
});
bigparaRateProvider
= new BigparaRateProvider(new IRateProvider.Callback<List<BuySellRate>>() {
@Override
public void onResult(List<BuySellRate> value) {
addEntry(value.get(0).value_sell_real, 3);
}
@Override
public void onError() {
}
});
enparaRateProvider.start();
yorumlarRateProvider.start();
bigparaRateProvider.start();
}
private void initUsdChart() {
Description description = new Description();
// description.setPosition(10, 10);
description.setTextSize(12f);
description.setText("Dolar-TL Grafiği");
description.setXOffset(8);
description.setYOffset(8);
description.setTextColor(ContextCompat.getColor(this, android.R.color.white));
//lineChart.setDescription(description);
lineChart.getDescription().setEnabled(false);
lineChart.setBackgroundColor(ContextCompat.getColor(this, android.R.color.holo_orange_light));
// add an empty data object
lineChart.setData(new LineData());
// mChart.getXAxis().setDrawLabels(false);
// mChart.getXAxis().setDrawGridLines(false);
lineChart.getXAxis().setLabelCount(6);
// lineChart.getAxisRight().setAxisMaximum(3.48f);
// lineChart.getAxisRight().setAxisMinimum(3.42f);
lineChart.getAxisLeft().setEnabled(false);
final IAxisValueFormatter defaultXFormatter = lineChart.getXAxis().getValueFormatter();
lineChart.getXAxis().setValueFormatter(new IAxisValueFormatter() {
@Override
public String getFormattedValue(float value, AxisBase axis) {
int time = (int) value;
int minutes = time / (60);
int seconds = (time) % 60;
String str = String.format("%d:%02d", minutes, seconds, Locale.ENGLISH);
return str;
}
});
final IAxisValueFormatter defaultYFormatter = new DefaultAxisValueFormatter(3);
lineChart.getAxisRight().setValueFormatter(new IAxisValueFormatter() {
@Override
public String getFormattedValue(float value, AxisBase axis) {
return defaultYFormatter.getFormattedValue(value, axis) + " TL";
}
});
lineChart.setScaleEnabled(false);
lineChart.invalidate();
LineData data = lineChart.getData();
data.addDataSet(createSet(0));
data.addDataSet(createSet(1));
data.addDataSet(createSet(2));
data.addDataSet(createSet(3));
lineChart.setExtraBottomOffset(12);
lineChart.setExtraTopOffset(12);
lineChart.setPinchZoom(false);
}
private void addEntry(float value, int chartIndex) {
LineData data = lineChart.getData();
long diffSeconds = (System.currentTimeMillis() - startMilis) / 1000;
Entry entry = new Entry(diffSeconds, value);
data.addEntry(entry, chartIndex);
data.notifyDataChanged();
// let the chart know it's data has changed
lineChart.notifyDataSetChanged();
//mChart.setVisibleYRangeMaximum(15, AxisDependency.LEFT);
lineChart.setVisibleXRangeMaximum(120);
lineChart.getXAxis().setDrawGridLines(false);
lineChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);
lineChart.getXAxis().setTextColor(ContextCompat.getColor(this, android.R.color.white));
lineChart.getAxisRight().setTextColor(ContextCompat.getColor(this, android.R.color.white));
// this automatically refreshes the chart (calls invalidate())
lineChart.moveViewToX(data.getEntryCount());
// lineChart.getAxisRight().setAxisMinimum(lineChart.getYMin()-0.01f);
// lineChart.getAxisRight().setAxisMaximum(lineChart.getYMax()-0.01f);
}
private LineDataSet createSet(int chartIndex) {
String label;
switch (chartIndex) {
case 0:
label = "Piyasa";
break;
case 1:
label = "Enpara Satış";
break;
case 2:
label = "Enpara Alış";
break;
case 3:
label = "Bigpara";
break;
default:
label = "Unknown";
break;
}
LineDataSet set = new LineDataSet(null, label);
// set.setMode(LineDataSet.Mode.CUBIC_BEZIER);
set.setCubicIntensity(0.1f);
set.setDrawCircleHole(false);
set.setLineWidth(1.5f);
set.setCircleRadius(2f);
set.setDrawCircles(true);
int color;
if (chartIndex == 0) {
color = Color.rgb(240, 0, 0);
} else if (chartIndex == 1) {
color = Color.rgb(0, 0, 240);
} else if (chartIndex == 3) {
color = Color.rgb(0, 240, 0);
} else {
color = Color.rgb(60, 60, 60);
}
set.setCircleColor(color);
set.setHighLightColor(Color.rgb(0, 0, 255));
set.setAxisDependency(YAxis.AxisDependency.LEFT);
set.setColor(color);
// set.setDrawFilled(true);
set.setFillAlpha((int) (256 * 0.3f));
set.setFillColor(color);
set.setValueTextColor(color);
set.setValueTextSize(16f);
set.setDrawValues(false);
return set;
}
@Override
protected void onDestroy() {
enparaRateProvider.stop();
yorumlarRateProvider.stop();
super.onDestroy();
}
}
| app/src/main/java/demoapps/exchangegraphics/RatesActivity.java | package demoapps.exchangegraphics;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.DefaultAxisValueFormatter;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import java.util.List;
import java.util.Locale;
import butterknife.BindView;
import butterknife.ButterKnife;
import demoapps.exchangegraphics.data.BuySellRate;
import demoapps.exchangegraphics.data.Rate;
import demoapps.exchangegraphics.data.YorumlarRate;
import demoapps.exchangegraphics.provider.BigparaRateProvider;
import demoapps.exchangegraphics.provider.EnparaRateProvider;
import demoapps.exchangegraphics.provider.IRateProvider;
import demoapps.exchangegraphics.provider.YorumlarRateProvider;
/**
* Created by erdemmac on 24/11/2016.
*/
public class RatesActivity extends AppCompatActivity {
private List<BuySellRate> enparaRates;
private List<YorumlarRate> yorumlarRates;
@BindView(R.id.line_usd_chart)
LineChart lineChart;
@BindView(R.id.v_progress_wheel)
View vProgress;
private long startMilis;
IRateProvider enparaRateProvider, yorumlarRateProvider, bigparaRateProvider;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rates);
ButterKnife.bind(this);
startMilis = System.currentTimeMillis();
initUsdChart();
vProgress.setVisibility(View.GONE);
enparaRateProvider = new EnparaRateProvider(new IRateProvider.Callback<List<BuySellRate>>() {
@Override
public void onResult(List<BuySellRate> rates) {
enparaRates = rates;
BuySellRate rateUsd = null;
for (Rate rate : rates) {
if (rate.rateType == Rate.RateTypes.USD) {
rateUsd = (BuySellRate) rate;
}
addEntry(rateUsd != null ? rateUsd.value_sell_real : 0.0f, 1);
addEntry(rateUsd != null ? rateUsd.value_buy_real : 0.0f, 2);
}
}
@Override
public void onError() {
}
});
yorumlarRateProvider = new YorumlarRateProvider(new IRateProvider.Callback<List<YorumlarRate>>() {
@Override
public void onResult(List<YorumlarRate> rates) {
yorumlarRates = rates;
YorumlarRate rateUsd = null;
for (Rate rate : rates) {
if (rate.rateType == Rate.RateTypes.USD) {
rateUsd = (YorumlarRate) rate;
}
}
addEntry(rateUsd != null ? rateUsd.realValue : 0.0f, 0);
}
@Override
public void onError() {
}
});
bigparaRateProvider
= new BigparaRateProvider(new IRateProvider.Callback<List<BuySellRate>>() {
@Override
public void onResult(List<BuySellRate> value) {
addEntry(value.get(0).value_sell_real,3);
}
@Override
public void onError() {
}
});
enparaRateProvider.start();
yorumlarRateProvider.start();
bigparaRateProvider.start();
}
private void initUsdChart() {
Description description = new Description();
// description.setPosition(10, 10);
description.setTextSize(12f);
description.setText("Dolar-TL Grafiği");
description.setXOffset(8);
description.setYOffset(8);
description.setTextColor(ContextCompat.getColor(this, android.R.color.white));
//lineChart.setDescription(description);
lineChart.getDescription().setEnabled(false);
lineChart.setBackgroundColor(ContextCompat.getColor(this, android.R.color.holo_orange_light));
// add an empty data object
lineChart.setData(new LineData());
// mChart.getXAxis().setDrawLabels(false);
// mChart.getXAxis().setDrawGridLines(false);
lineChart.getXAxis().setLabelCount(6);
// lineChart.getAxisRight().setAxisMaximum(3.48f);
// lineChart.getAxisRight().setAxisMinimum(3.42f);
lineChart.getAxisLeft().setEnabled(false);
final IAxisValueFormatter defaultXFormatter = lineChart.getXAxis().getValueFormatter();
lineChart.getXAxis().setValueFormatter(new IAxisValueFormatter() {
@Override
public String getFormattedValue(float value, AxisBase axis) {
int time = (int) value;
int minutes = time / (60);
int seconds = (time) % 60;
String str = String.format("%d:%02d", minutes, seconds, Locale.ENGLISH);
return str;
}
});
final IAxisValueFormatter defaultYFormatter = new DefaultAxisValueFormatter(3);
lineChart.getAxisRight().setValueFormatter(new IAxisValueFormatter() {
@Override
public String getFormattedValue(float value, AxisBase axis) {
return defaultYFormatter.getFormattedValue(value, axis) + " TL";
}
});
lineChart.setScaleEnabled(false);
lineChart.invalidate();
LineData data = lineChart.getData();
data.addDataSet(createSet(0));
data.addDataSet(createSet(1));
data.addDataSet(createSet(2));
data.addDataSet(createSet(3));
lineChart.setExtraBottomOffset(12);
lineChart.setExtraTopOffset(12);
lineChart.setPinchZoom(false);
}
private void addEntry(float value, int chartIndex) {
LineData data = lineChart.getData();
long diffSeconds = (System.currentTimeMillis() - startMilis) / 1000;
Entry entry = new Entry(diffSeconds, value);
data.addEntry(entry, chartIndex);
data.notifyDataChanged();
// let the chart know it's data has changed
lineChart.notifyDataSetChanged();
//mChart.setVisibleYRangeMaximum(15, AxisDependency.LEFT);
lineChart.setVisibleXRangeMaximum(120);
lineChart.getXAxis().setDrawGridLines(false);
lineChart.getXAxis().setPosition(XAxis.XAxisPosition.BOTTOM);
lineChart.getXAxis().setTextColor(ContextCompat.getColor(this, android.R.color.white));
lineChart.getAxisRight().setTextColor(ContextCompat.getColor(this, android.R.color.white));
// this automatically refreshes the chart (calls invalidate())
lineChart.moveViewToX(data.getEntryCount());
// lineChart.getAxisRight().setAxisMinimum(lineChart.getYMin()-0.01f);
// lineChart.getAxisRight().setAxisMaximum(lineChart.getYMax()-0.01f);
}
private LineDataSet createSet(int chartIndex) {
String label;
switch (chartIndex) {
case 0:
label = "Piyasa";
break;
case 1:
label = "Enpara Satış";
break;
case 2:
label = "Enpara Alış";
break;
case 3:
label = "Bigpara";
break;
default:
label = "Unknown";
break;
}
LineDataSet set = new LineDataSet(null, label);
// set.setMode(LineDataSet.Mode.CUBIC_BEZIER);
set.setCubicIntensity(0.1f);
set.setDrawCircleHole(false);
set.setLineWidth(1.5f);
set.setCircleRadius(2f);
set.setDrawCircles(true);
int color;
if (chartIndex == 0) {
color = Color.rgb(240, 0, 0);
} else if (chartIndex == 1) {
color = Color.rgb(0, 0, 240);
}
else if (chartIndex == 3) {
color = Color.rgb(0, 240, 0);
}
else {
color = Color.rgb(60, 60, 60);
}
set.setCircleColor(color);
set.setHighLightColor(Color.rgb(0, 0, 255));
set.setAxisDependency(YAxis.AxisDependency.LEFT);
set.setColor(color);
// set.setDrawFilled(true);
set.setFillAlpha((int) (256 * 0.3f));
set.setFillColor(color);
set.setValueTextColor(color);
set.setValueTextSize(16f);
set.setDrawValues(false);
return set;
}
@Override
protected void onDestroy() {
enparaRateProvider.stop();
yorumlarRateProvider.stop();
super.onDestroy();
}
}
| Formatting.
| app/src/main/java/demoapps/exchangegraphics/RatesActivity.java | Formatting. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.