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 | fb3c2a24b71a1516871905db812893ad5b823037 | 0 | leimer/orika,Log10Solutions/orika,brabenetz/orika,ellis429/orika,orika-mapper/orika,acsl/orika,andreabertagnolli/orika | /*
* Orika - simpler, better and faster Java bean mapping
*
* Copyright (C) 2011 Orika 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 ma.glasnost.orika.impl;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import ma.glasnost.orika.DefaultFieldMapper;
import ma.glasnost.orika.Mapper;
import ma.glasnost.orika.MapperFacade;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.MappingContext;
import ma.glasnost.orika.MappingException;
import ma.glasnost.orika.ObjectFactory;
import ma.glasnost.orika.constructor.ConstructorResolverStrategy;
import ma.glasnost.orika.converter.ConverterFactory;
import ma.glasnost.orika.converter.builtin.BuiltinConverters;
import ma.glasnost.orika.impl.generator.CompilerStrategy;
import ma.glasnost.orika.impl.generator.CompilerStrategy.SourceCodeGenerationException;
import ma.glasnost.orika.impl.generator.MapperGenerator;
import ma.glasnost.orika.impl.generator.ObjectFactoryGenerator;
import ma.glasnost.orika.impl.util.ClassUtil;
import ma.glasnost.orika.inheritance.DefaultSuperTypeResolverStrategy;
import ma.glasnost.orika.inheritance.SuperTypeResolverStrategy;
import ma.glasnost.orika.metadata.ClassMap;
import ma.glasnost.orika.metadata.ClassMapBuilder;
import ma.glasnost.orika.metadata.ClassMapBuilderFactory;
import ma.glasnost.orika.metadata.MapperKey;
import ma.glasnost.orika.metadata.Type;
import ma.glasnost.orika.metadata.TypeFactory;
import ma.glasnost.orika.property.PropertyResolverStrategy;
import ma.glasnost.orika.unenhance.BaseUnenhancer;
import ma.glasnost.orika.unenhance.UnenhanceStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The mapper factory is the heart of Orika, a small container where metadata
* are stored, it's used by other components, to look up for generated mappers,
* converters, object factories ... etc.
*
* @author S.M. El Aatifi
*
*/
public class DefaultMapperFactory implements MapperFactory {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultMapperFactory.class);
private final MapperFacade mapperFacade;
private final MapperGenerator mapperGenerator;
private final ObjectFactoryGenerator objectFactoryGenerator;
private final Map<MapperKey, ClassMap<Object, Object>> classMapRegistry;
private final Map<MapperKey, Mapper<?, ?>> mappersRegistry;
private final ConcurrentHashMap<Type<? extends Object>, ObjectFactory<? extends Object>> objectFactoryRegistry;
private final Map<Type<?>, Set<Type<?>>> aToBRegistry;
private final List<DefaultFieldMapper> defaultFieldMappers;
private final UnenhanceStrategy unenhanceStrategy;
private final ConverterFactory converterFactory;
private final CompilerStrategy compilerStrategy;
private final PropertyResolverStrategy propertyResolverStrategy;
private final Map<java.lang.reflect.Type, Type<?>> concreteTypeRegistry;
private volatile ClassMapBuilderFactory classMapBuilderFactory;
private final Map<MapperKey, Set<ClassMap<Object, Object>>> usedMapperMetadataRegistry;
private final boolean useAutoMapping;
private volatile boolean isBuilt = false;
private volatile boolean isBuilding = false;
/**
* Place-holder object factory used to represent the default constructor in
* registry lookup; prevents repeated lookup of constructor
*/
private static final ObjectFactory<Object> USE_DEFAULT_CONSTRUCTOR = new ObjectFactory<Object>() {
public Object create(Object source, MappingContext context) {
return null;
}
};
/**
* Constructs a new instance of DefaultMapperFactory
*
* @param builder
*/
protected DefaultMapperFactory(MapperFactoryBuilder<?, ?> builder) {
this.converterFactory = builder.converterFactory;
this.compilerStrategy = builder.compilerStrategy;
this.classMapRegistry = new ConcurrentHashMap<MapperKey, ClassMap<Object, Object>>();
//this.mappersRegistry = new ConcurrentHashMap<MapperKey, Mapper<?, ?>>();
this.mappersRegistry = new TreeMap<MapperKey, Mapper<?, ?>>();
this.aToBRegistry = new ConcurrentHashMap<Type<?>, Set<Type<?>>>();
this.usedMapperMetadataRegistry = new ConcurrentHashMap<MapperKey, Set<ClassMap<Object, Object>>>();
this.objectFactoryRegistry = new ConcurrentHashMap<Type<? extends Object>, ObjectFactory<? extends Object>>();
this.defaultFieldMappers = new CopyOnWriteArrayList<DefaultFieldMapper>();
this.unenhanceStrategy = buildUnenhanceStrategy(builder.unenhanceStrategy, builder.superTypeStrategy);
this.mapperFacade = new MapperFacadeImpl(this, unenhanceStrategy);
this.concreteTypeRegistry = new ConcurrentHashMap<java.lang.reflect.Type, Type<?>>();
if (builder.classMaps != null) {
for (final ClassMap<?, ?> classMap : builder.classMaps) {
registerClassMap(classMap);
}
}
this.propertyResolverStrategy = builder.propertyResolverStrategy;
this.mapperGenerator = new MapperGenerator(this, builder.compilerStrategy);
this.objectFactoryGenerator = new ObjectFactoryGenerator(this, builder.constructorResolverStrategy, builder.compilerStrategy, propertyResolverStrategy);
this.useAutoMapping = builder.useAutoMapping;
if (builder.usedBuiltinConverters) {
BuiltinConverters.register(converterFactory);
}
}
/**
* MapperFactoryBuilder provides an extensible Builder definition usable for
* providing your own Builder class for subclasses of DefaultMapperFactory.<br><br>
*
* See the defined {@link Builder} below for example of how to subclass.
*
* @author [email protected]
*
* @param <F>
* @param <B>
*/
public static abstract class MapperFactoryBuilder<F extends DefaultMapperFactory, B extends MapperFactoryBuilder<F, B>> {
protected UnenhanceStrategy unenhanceStrategy;
protected SuperTypeResolverStrategy superTypeStrategy;
protected ConstructorResolverStrategy constructorResolverStrategy;
protected CompilerStrategy compilerStrategy;
protected Set<ClassMap<?, ?>> classMaps;
protected ConverterFactory converterFactory;
protected PropertyResolverStrategy propertyResolverStrategy;
protected boolean usedBuiltinConverters = false;
protected boolean useAutoMapping = true;
public MapperFactoryBuilder() {
converterFactory = UtilityResolver.getDefaultConverterFactory();
constructorResolverStrategy = UtilityResolver.getDefaultConstructorResolverStrategy();
compilerStrategy = UtilityResolver.getDefaultCompilerStrategy();
propertyResolverStrategy = UtilityResolver.getDefaultPropertyResolverStrategy();
}
protected abstract B self();
public B classMaps(Set<ClassMap<?, ?>> classMaps) {
this.classMaps = classMaps;
return self();
}
public B unenhanceStrategy(UnenhanceStrategy unenhanceStrategy) {
this.unenhanceStrategy = unenhanceStrategy;
return self();
}
public B superTypeResolverStrategy(SuperTypeResolverStrategy superTypeStrategy) {
this.superTypeStrategy = superTypeStrategy;
return self();
}
public B constructorResolverStrategy(ConstructorResolverStrategy constructorResolverStrategy) {
this.constructorResolverStrategy = constructorResolverStrategy;
return self();
}
public B converterFactory(ConverterFactory converterFactory) {
this.converterFactory = converterFactory;
return self();
}
public B compilerStrategy(CompilerStrategy compilerStrategy) {
this.compilerStrategy = compilerStrategy;
return self();
}
public B propertyResolverStrategy(PropertyResolverStrategy propertyResolverStrategy) {
this.propertyResolverStrategy = propertyResolverStrategy;
return self();
}
public B useAutoMapping(boolean useAutoMapping) {
this.useAutoMapping = useAutoMapping;
return self();
}
public B usedBuiltinConverters(boolean useBuiltinConverters) {
this.usedBuiltinConverters = useBuiltinConverters;
return self();
}
/**
* @return a new instance of the Factory for which this builder is defined.
* The construction should be performed via the single-argument constructor which
* takes in a builder; no initialization code should be performed here, as it
* will not be inherited by subclasses; instead, place such initialization (defaults, etc.)
* in the Builder's constructor.
*/
public abstract F build();
}
/**
* Use this builder to generate instances of DefaultMapperFactory with the
* desired customizations.<br>
* <br>
*
* For example, an instance with no customizations could be generated with
* the following code:
*
* <pre>
* MapperFactory factory = new DefaultMapperFactory.Builder().build();
* </pre>
*
* @author [email protected]
*/
public static class Builder extends MapperFactoryBuilder<DefaultMapperFactory, Builder> {
/* (non-Javadoc)
* @see ma.glasnost.orika.impl.DefaultMapperFactory.MapperFactoryBuilder#build()
*/
@Override
public DefaultMapperFactory build() {
return new DefaultMapperFactory(this);
}
/* (non-Javadoc)
* @see ma.glasnost.orika.impl.DefaultMapperFactory.MapperFactoryBuilder#self()
*/
@Override
protected Builder self() {
return this;
}
}
/**
* Generates the UnenhanceStrategy to be used for this MapperFactory,
* applying the passed delegateStrategy if not null.<br>
* This allows the MapperFactory a chance to fill in the unenhance
* strategy with references to other parts of the factory (registered
* mappers, converters, object factories) which may be important in
* the "unenhancing" process.
*
* @param unenhanceStrategy
* @param overrideDefaultUnenhanceBehavior
* true if the passed UnenhanceStrategy should take full
* responsibility for un-enhancement; false if the default
* behavior should be applied as a fail-safe after consulting the
* passed strategy.
*
* @return
*/
protected UnenhanceStrategy buildUnenhanceStrategy(UnenhanceStrategy unenhanceStrategy, SuperTypeResolverStrategy superTypeStrategy) {
BaseUnenhancer unenhancer = new BaseUnenhancer();
if (unenhanceStrategy != null) {
unenhancer.addUnenhanceStrategy(unenhanceStrategy);
}
if (superTypeStrategy != null) {
unenhancer.addSuperTypeResolverStrategy(superTypeStrategy);
} else {
/*
* This strategy attempts to lookup super-type that has a registered
* mapper or converter whenever it is offered a class that is not
* currently mapped
*/
final SuperTypeResolverStrategy registeredMappersStrategy = new DefaultSuperTypeResolverStrategy() {
@Override
public boolean isAcceptable(Type<?> type) {
return type != null && aToBRegistry.containsKey(type);
}
};
unenhancer.addSuperTypeResolverStrategy(registeredMappersStrategy);
}
/*
* This strategy produces super-types whenever the proposed class type
* is not accessible to the compilerStrategy and/or the current thread
* context class-loader; it is added last as a fail-safe in case a
* suggested type cannot be used. It is automatically included, as
* there's no case when skipping it would be desired....
*/
final SuperTypeResolverStrategy inaccessibleTypeStrategy = new DefaultSuperTypeResolverStrategy() {
/**
* Tests whether the specified type is accessible to both the
* current thread's class-loader, and also to the compilerStrategy.
*
* @param type
* @return
*/
public boolean isTypeAccessible(Type<?> type) {
try {
Class<?> loadedType = Thread.currentThread().getContextClassLoader().loadClass(type.getName());
if (!type.getRawType().equals(loadedType)) {
return false;
}
compilerStrategy.assureTypeIsAccessible(type.getRawType());
return true;
} catch (ClassNotFoundException e) {
return false;
} catch (SourceCodeGenerationException e) {
return false;
}
}
@Override
public boolean isAcceptable(Type<?> type) {
return isTypeAccessible(type) && !java.lang.reflect.Proxy.class.equals(type.getRawType());
}
};
unenhancer.addSuperTypeResolverStrategy(inaccessibleTypeStrategy);
return unenhancer;
}
public Mapper<Object, Object> lookupMapper(MapperKey mapperKey) {
if (!existsRegisteredMapper(mapperKey.getAType(), mapperKey.getBType())) {
if(useAutoMapping) {
synchronized (this) {
try {
/*
* We shouldn't create a mapper for an immutable type; although it
* will succeed in generating an empty mapper, it won't actually result in a valid
* mapping, so it's better to throw an exception to indicate more clearly that
* something went wrong.
* However, there is a possibility that a custom ObjectFactory was registered for the
* immutable type, which would be valid.
*/
if (ClassUtil.isImmutable(mapperKey.getBType()) && !objectFactoryRegistry.containsKey(mapperKey.getBType())) {
throw new MappingException("No converter registered for conversion from " + mapperKey.getAType() + " to " +
mapperKey.getBType() + ", nor any ObjectFactory which can generate " + mapperKey.getBType() + " from " + mapperKey.getAType());
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("No mapper registered for " + mapperKey + ": attempting to generate");
}
final ClassMap<?, ?> classMap = classMap(mapperKey.getAType(), mapperKey.getBType())
.byDefault().toClassMap();
buildObjectFactories(classMap);
buildMapper(classMap);
initializeUsedMappers(classMap);
} catch (MappingException e) {
e.setSourceType(mapperKey.getAType());
e.setDestinationType(mapperKey.getBType());
throw e;
}
}
}
}
return getRegisteredMapper(mapperKey);
}
public boolean existsRegisteredMapper(MapperKey mapperKey) {
return mappersRegistry.containsKey(mapperKey);
}
public boolean existsRegisteredMapper(Type<?> sourceType, Type<?> destinationType) {
for (Mapper<?,?> mapper: mappersRegistry.values()) {
if ((mapper.getAType().isAssignableFrom(sourceType) && mapper.getBType().isAssignableFrom(destinationType))
|| (mapper.getAType().isAssignableFrom(destinationType) && mapper.getBType().isAssignableFrom(sourceType))) {
return true;
}
}
return false;
}
@SuppressWarnings("unchecked")
protected <A,B> Mapper<A, B> getRegisteredMapper(MapperKey mapperKey) {
//return (Mapper<A, B>) mappersRegistry.get(mapperKey);
for (Mapper<?,?> mapper: mappersRegistry.values()) {
if ((mapper.getAType().isAssignableFrom(mapperKey.getAType()) && mapper.getBType().isAssignableFrom(mapperKey.getBType()))
|| (mapper.getAType().isAssignableFrom(mapperKey.getBType()) && mapper.getBType().isAssignableFrom(mapperKey.getAType()))) {
return (Mapper<A, B>) mapper;
}
}
return null;
}
/* (non-Javadoc)
* @see ma.glasnost.orika.MapperFactory#getMapperFacade()
*
* Since getMapperFacade() triggers the build() process, it is
* important that none of the methods called during the build()
* invoke getMapperFacade() again.
*
*/
public MapperFacade getMapperFacade() {
if (!isBuilt) {
synchronized (mapperFacade) {
if (!isBuilt) {
build();
}
}
}
return mapperFacade;
}
public <D> void registerObjectFactory(ObjectFactory<D> objectFactory, Type<D> destinationType) {
objectFactoryRegistry.put(destinationType, objectFactory);
}
@Deprecated
public void registerMappingHint(ma.glasnost.orika.MappingHint... hints) {
DefaultFieldMapper[] mappers = new DefaultFieldMapper[hints.length];
for (int i = 0, len = hints.length; i < len; ++i) {
mappers[i] = new ma.glasnost.orika.MappingHint.DefaultFieldMappingConverter(hints[i]);
}
registerDefaultFieldMapper(mappers);
}
public void registerDefaultFieldMapper(DefaultFieldMapper... mappers) {
this.defaultFieldMappers.addAll(Arrays.asList(mappers));
}
public void registerConcreteType(Type<?> abstractType, Type<?> concreteType) {
this.concreteTypeRegistry.put(abstractType, concreteType);
}
public void registerConcreteType(Class<?> abstractType, Class<?> concreteType) {
this.concreteTypeRegistry.put(abstractType, TypeFactory.valueOf(concreteType));
}
@SuppressWarnings("unchecked")
public <T> ObjectFactory<T> lookupObjectFactory(Type<T> targetType) {
if (targetType == null) {
return null;
}
ObjectFactory<T> result = (ObjectFactory<T>) objectFactoryRegistry.get(targetType);
if (result == null) {
// Check if we can use default constructor...
synchronized (this) {
Constructor<?>[] constructors = targetType.getRawType().getConstructors();
if (useAutoMapping || !isBuilt) {
if (constructors.length == 1 && constructors[0].getParameterTypes().length == 0) {
/*
* Use the default constructor in the case where it is the only option
*/
result = (ObjectFactory<T>) USE_DEFAULT_CONSTRUCTOR;
} else {
try {
result = (ObjectFactory<T>) objectFactoryGenerator.build(targetType);
} catch (MappingException e) {
for (Constructor<?> c: constructors) {
if (c.getParameterTypes().length == 0) {
result = (ObjectFactory<T>) USE_DEFAULT_CONSTRUCTOR;
break;
}
}
if (result == null) {
throw e;
}
}
}
objectFactoryRegistry.put(targetType, result);
} else {
for (Constructor<?> constructor: constructors) {
if (constructor.getParameterTypes().length == 0) {
result = (ObjectFactory<T>) USE_DEFAULT_CONSTRUCTOR;
break;
}
}
}
}
}
if (USE_DEFAULT_CONSTRUCTOR.equals(result)) {
result = null;
}
return result;
}
@SuppressWarnings("unchecked")
public <S, D> Type<? extends D> lookupConcreteDestinationType(Type<S> sourceType, Type<D> destinationType, MappingContext context) {
Type<? extends D> concreteType = context.getConcreteClass(sourceType, destinationType);
if (concreteType != null) {
return concreteType;
}
Set<Type<?>> destinationSet = aToBRegistry.get(sourceType);
if (destinationSet == null || destinationSet.isEmpty()) {
return null;
}
for (final Type<?> type : destinationSet) {
if (destinationType.isAssignableFrom(type) && ClassUtil.isConcrete(type)) {
return (Type<? extends D>) type;
}
}
if (concreteType == null) {
concreteType = (Type<? extends D>) this.concreteTypeRegistry.get(destinationType);
if (concreteType == null) {
concreteType = (Type<? extends D>) this.concreteTypeRegistry.get(destinationType.getRawType());
if (concreteType != null) {
concreteType = TypeFactory.resolveValueOf(concreteType.getRawType(), destinationType);
}
}
}
return concreteType;
}
@SuppressWarnings("unchecked")
public <A, B> void registerClassMap(ClassMap<A, B> classMap) {
classMapRegistry.put(new MapperKey(classMap.getAType(), classMap.getBType()), (ClassMap<Object, Object>) classMap);
}
public <A, B> void registerClassMap(ClassMapBuilder<A, B> builder) {
registerClassMap(builder.toClassMap());
}
public synchronized void build() {
if (!isBuilding) {
isBuilding = true;
converterFactory.setMapperFacade(mapperFacade);
buildClassMapRegistry();
for (final ClassMap<?, ?> classMap : classMapRegistry.values()) {
buildMapper(classMap);
}
for (final ClassMap<?, ?> classMap : classMapRegistry.values()) {
buildObjectFactories(classMap);
initializeUsedMappers(classMap);
}
isBuilt = true;
isBuilding = false;
}
}
public Set<ClassMap<Object, Object>> lookupUsedClassMap(MapperKey mapperKey) {
Set<ClassMap<Object, Object>> usedClassMapSet = usedMapperMetadataRegistry.get(mapperKey);
if (usedClassMapSet == null) {
usedClassMapSet = Collections.emptySet();
}
return usedClassMapSet;
}
private void buildClassMapRegistry() {
// prepare a map for classmap (stored as set)
Map<MapperKey, ClassMap<Object, Object>> classMapsDictionary = new HashMap<MapperKey, ClassMap<Object, Object>>();
Set<ClassMap<Object, Object>> classMaps = new HashSet<ClassMap<Object, Object>>(classMapRegistry.values());
for (final ClassMap<Object, Object> classMap : classMaps) {
classMapsDictionary.put(new MapperKey(classMap.getAType(), classMap.getBType()), classMap);
}
for (final ClassMap<?, ?> classMap : classMaps) {
MapperKey key = new MapperKey(classMap.getAType(), classMap.getBType());
Set<ClassMap<Object, Object>> usedClassMapSet = new HashSet<ClassMap<Object, Object>>();
for (final MapperKey parentMapperKey : classMap.getUsedMappers()) {
ClassMap<Object, Object> usedClassMap = classMapsDictionary.get(parentMapperKey);
if (usedClassMap == null) {
throw new MappingException("Cannot find class mapping using mapper : " + classMap.getMapperClassName());
}
usedClassMapSet.add(usedClassMap);
}
usedMapperMetadataRegistry.put(key, usedClassMapSet);
}
}
@SuppressWarnings({ "unchecked" })
private <S, D> void buildObjectFactories(ClassMap<S, D> classMap) {
Type<?> aType = classMap.getAType();
Type<?> bType = classMap.getBType();
if (classMap.getConstructorA() != null && lookupObjectFactory(aType) == null) {
GeneratedObjectFactory objectFactory = objectFactoryGenerator.build(aType);
registerObjectFactory(objectFactory, (Type<Object>) aType);
}
if (classMap.getConstructorB() != null && lookupObjectFactory(bType) == null) {
GeneratedObjectFactory objectFactory = objectFactoryGenerator.build(bType);
registerObjectFactory(objectFactory, (Type<Object>) bType);
}
}
private static final Comparator<MapperKey> MAPPER_COMPARATOR = new Comparator<MapperKey>() {
public int compare(MapperKey key1, MapperKey key2) {
if (key1.getAType().isAssignableFrom(key2.getAType()) && key1.getBType().isAssignableFrom(key2.getBType())) {
return 1;
} else if (key2.getAType().isAssignableFrom(key1.getAType()) && key2.getBType().isAssignableFrom(key1.getBType())) {
return -1;
} else if (key1.getAType().equals(key2.getAType()) && key1.getBType().equals(key2.getBType())) {
return 0;
} else {
throw new IllegalArgumentException("keys " + key1 + " and " + key2 + " are unrelated");
}
}
};
@SuppressWarnings("unchecked")
private void initializeUsedMappers(ClassMap<?, ?> classMap) {
Mapper<Object, Object> mapper = lookupMapper(new MapperKey(classMap.getAType(), classMap.getBType()));
List<Mapper<Object, Object>> parentMappers = new ArrayList<Mapper<Object, Object>>();
if (!classMap.getUsedMappers().isEmpty()) {
for (MapperKey parentMapperKey : classMap.getUsedMappers()) {
collectUsedMappers(classMap, parentMappers, parentMapperKey);
}
} else {
/*
* Attempt to auto-determine used mappers for this classmap;
* however, we should only add the most-specific of the available
* mappers to avoid calling the same mapper multiple times during a
* single map request
*/
Set<MapperKey> usedMappers = new TreeSet<MapperKey>(MAPPER_COMPARATOR);
for (MapperKey key : this.classMapRegistry.keySet()) {
if (!key.getAType().equals(classMap.getAType()) || !key.getBType().equals(classMap.getBType())) {
if (key.getAType().isAssignableFrom(classMap.getAType()) && key.getBType().isAssignableFrom(classMap.getBType())) {
usedMappers.add(key);
}
}
}
if (!usedMappers.isEmpty()) {
// Set<ClassMap<Object, Object>> usedClassMapSet = new
// HashSet<ClassMap<Object, Object>>();
MapperKey parentKey = usedMappers.iterator().next();
// usedClassMapSet.add(classMapRegistry.get(parentKey));
// usedMapperMetadataRegistry.put(parentKey, usedClassMapSet);
collectUsedMappers(classMap, parentMappers, parentKey);
}
}
mapper.setUsedMappers(parentMappers.toArray(new Mapper[parentMappers.size()]));
}
private void collectUsedMappers(ClassMap<?, ?> classMap, List<Mapper<Object, Object>> parentMappers, MapperKey parentMapperKey) {
Mapper<Object, Object> parentMapper = lookupMapper(parentMapperKey);
if (parentMapper == null) {
throw new MappingException("Cannot find used mappers for : " + classMap.getMapperClassName());
}
parentMappers.add(parentMapper);
Set<ClassMap<Object, Object>> usedClassMapSet = usedMapperMetadataRegistry.get(parentMapperKey);
if (usedClassMapSet != null) {
for (ClassMap<Object, Object> cm : usedClassMapSet) {
collectUsedMappers(cm, parentMappers, new MapperKey(cm.getAType(), cm.getBType()));
}
}
}
@SuppressWarnings("unchecked")
private void buildMapper(ClassMap<?, ?> classMap) {
register(classMap.getAType(), classMap.getBType());
register(classMap.getBType(), classMap.getAType());
final MapperKey mapperKey = new MapperKey(classMap.getAType(), classMap.getBType());
final GeneratedMapperBase mapper = this.mapperGenerator.build(classMap);
mapper.setMapperFacade(mapperFacade);
if (classMap.getCustomizedMapper() != null) {
final Mapper<Object, Object> customizedMapper = (Mapper<Object, Object>) classMap.getCustomizedMapper();
mapper.setCustomMapper(customizedMapper);
}
mappersRegistry.put(mapperKey, mapper);
classMapRegistry.put(mapperKey, (ClassMap<Object, Object>) classMap);
}
protected <S, D> void register(Type<S> sourceClass, Type<D> destinationClass) {
Set<Type<?>> destinationSet = aToBRegistry.get(sourceClass);
if (destinationSet == null) {
destinationSet = new TreeSet<Type<?>>();
aToBRegistry.put(sourceClass, destinationSet);
}
destinationSet.add(destinationClass);
}
@SuppressWarnings("unchecked")
public <A, B> ClassMap<A, B> getClassMap(MapperKey mapperKey) {
return (ClassMap<A, B>) classMapRegistry.get(mapperKey);
}
public Set<Type<? extends Object>> lookupMappedClasses(Type<?> type) {
return aToBRegistry.get(type);
}
public ConverterFactory getConverterFactory() {
return converterFactory;
}
public <T> void registerObjectFactory(ObjectFactory<T> objectFactory, Class<T> targetClass) {
registerObjectFactory(objectFactory, TypeFactory.<T>valueOf(targetClass));
}
protected ClassMapBuilderFactory getClassMapBuilderFactory() {
if (classMapBuilderFactory == null) {
synchronized(this) {
if (classMapBuilderFactory == null) {
classMapBuilderFactory = new ClassMapBuilderFactory(this.propertyResolverStrategy,
defaultFieldMappers.toArray(new DefaultFieldMapper[defaultFieldMappers.size()]));
}
}
}
return classMapBuilderFactory;
}
public <A, B> ClassMapBuilder<A, B> classMap(Type<A> aType, Type<B> bType) {
return getClassMapBuilderFactory().map(aType, bType);
}
public <A, B> ClassMapBuilder<A, B> classMap(Class<A> aType, Type<B> bType) {
return classMap(TypeFactory.<A>valueOf(aType), bType);
}
public <A, B> ClassMapBuilder<A, B> classMap(Type<A> aType, Class<B> bType) {
return classMap(aType, TypeFactory.<B>valueOf(bType));
}
public <A, B> ClassMapBuilder<A, B> classMap(Class<A> aType, Class<B> bType) {
return classMap(TypeFactory.<A>valueOf(aType), TypeFactory.<B>valueOf(bType));
}
/* (non-Javadoc)
* @see ma.glasnost.orika.MapperFactory#registerMapper(ma.glasnost.orika.Mapper)
*/
public <A, B> void registerMapper(Mapper<A, B> mapper) {
synchronized(this) {
this.mappersRegistry.put(new MapperKey(mapper.getAType(), mapper.getBType()), mapper);
mapper.setMapperFacade(this.mapperFacade);
register(mapper.getAType(), mapper.getBType());
register(mapper.getBType(), mapper.getAType());
}
}
}
| core/src/main/java/ma/glasnost/orika/impl/DefaultMapperFactory.java | /*
* Orika - simpler, better and faster Java bean mapping
*
* Copyright (C) 2011 Orika 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 ma.glasnost.orika.impl;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import ma.glasnost.orika.DefaultFieldMapper;
import ma.glasnost.orika.Mapper;
import ma.glasnost.orika.MapperFacade;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.MappingContext;
import ma.glasnost.orika.MappingException;
import ma.glasnost.orika.ObjectFactory;
import ma.glasnost.orika.constructor.ConstructorResolverStrategy;
import ma.glasnost.orika.converter.ConverterFactory;
import ma.glasnost.orika.converter.builtin.BuiltinConverters;
import ma.glasnost.orika.impl.generator.CompilerStrategy;
import ma.glasnost.orika.impl.generator.CompilerStrategy.SourceCodeGenerationException;
import ma.glasnost.orika.impl.generator.MapperGenerator;
import ma.glasnost.orika.impl.generator.ObjectFactoryGenerator;
import ma.glasnost.orika.impl.util.ClassUtil;
import ma.glasnost.orika.inheritance.DefaultSuperTypeResolverStrategy;
import ma.glasnost.orika.inheritance.SuperTypeResolverStrategy;
import ma.glasnost.orika.metadata.ClassMap;
import ma.glasnost.orika.metadata.ClassMapBuilder;
import ma.glasnost.orika.metadata.ClassMapBuilderFactory;
import ma.glasnost.orika.metadata.MapperKey;
import ma.glasnost.orika.metadata.Type;
import ma.glasnost.orika.metadata.TypeFactory;
import ma.glasnost.orika.property.PropertyResolverStrategy;
import ma.glasnost.orika.unenhance.BaseUnenhancer;
import ma.glasnost.orika.unenhance.UnenhanceStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The mapper factory is the heart of Orika, a small container where metadata
* are stored, it's used by other components, to look up for generated mappers,
* converters, object factories ... etc.
*
* @author S.M. El Aatifi
*
*/
public class DefaultMapperFactory implements MapperFactory {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultMapperFactory.class);
private final MapperFacade mapperFacade;
private final MapperGenerator mapperGenerator;
private final ObjectFactoryGenerator objectFactoryGenerator;
private final Map<MapperKey, ClassMap<Object, Object>> classMapRegistry;
private final Map<MapperKey, Mapper<?, ?>> mappersRegistry;
private final ConcurrentHashMap<Type<? extends Object>, ObjectFactory<? extends Object>> objectFactoryRegistry;
private final Map<Type<?>, Set<Type<?>>> aToBRegistry;
private final List<DefaultFieldMapper> defaultFieldMappers;
private final UnenhanceStrategy unenhanceStrategy;
private final ConverterFactory converterFactory;
private final CompilerStrategy compilerStrategy;
private final PropertyResolverStrategy propertyResolverStrategy;
private final Map<java.lang.reflect.Type, Type<?>> concreteTypeRegistry;
private volatile ClassMapBuilderFactory classMapBuilderFactory;
private final Map<MapperKey, Set<ClassMap<Object, Object>>> usedMapperMetadataRegistry;
private final boolean useAutoMapping;
private volatile boolean isBuilt = false;
private volatile boolean isBuilding = false;
/**
* Place-holder object factory used to represent the default constructor in
* registry lookup; prevents repeated lookup of constructor
*/
private static final ObjectFactory<Object> USE_DEFAULT_CONSTRUCTOR = new ObjectFactory<Object>() {
public Object create(Object source, MappingContext context) {
return null;
}
};
/**
* Constructs a new instance of DefaultMapperFactory
*
* @param builder
*/
protected DefaultMapperFactory(MapperFactoryBuilder<?, ?> builder) {
this.converterFactory = builder.converterFactory;
this.compilerStrategy = builder.compilerStrategy;
this.classMapRegistry = new ConcurrentHashMap<MapperKey, ClassMap<Object, Object>>();
//this.mappersRegistry = new ConcurrentHashMap<MapperKey, Mapper<?, ?>>();
this.mappersRegistry = new TreeMap<MapperKey, Mapper<?, ?>>();
this.aToBRegistry = new ConcurrentHashMap<Type<?>, Set<Type<?>>>();
this.usedMapperMetadataRegistry = new ConcurrentHashMap<MapperKey, Set<ClassMap<Object, Object>>>();
this.objectFactoryRegistry = new ConcurrentHashMap<Type<? extends Object>, ObjectFactory<? extends Object>>();
this.defaultFieldMappers = new CopyOnWriteArrayList<DefaultFieldMapper>();
this.unenhanceStrategy = buildUnenhanceStrategy(builder.unenhanceStrategy, builder.superTypeStrategy);
this.mapperFacade = new MapperFacadeImpl(this, unenhanceStrategy);
this.concreteTypeRegistry = new ConcurrentHashMap<java.lang.reflect.Type, Type<?>>();
if (builder.classMaps != null) {
for (final ClassMap<?, ?> classMap : builder.classMaps) {
registerClassMap(classMap);
}
}
this.propertyResolverStrategy = builder.propertyResolverStrategy;
this.mapperGenerator = new MapperGenerator(this, builder.compilerStrategy);
this.objectFactoryGenerator = new ObjectFactoryGenerator(this, builder.constructorResolverStrategy, builder.compilerStrategy, propertyResolverStrategy);
this.useAutoMapping = builder.useAutoMapping;
if (builder.usedBuiltinConverters) {
BuiltinConverters.register(converterFactory);
}
}
/**
* MapperFactoryBuilder provides an extensible Builder definition usable for
* providing your own Builder class for subclasses of DefaultMapperFactory.<br><br>
*
* See the defined {@link Builder} below for example of how to subclass.
*
* @author [email protected]
*
* @param <F>
* @param <B>
*/
public static abstract class MapperFactoryBuilder<F extends DefaultMapperFactory, B extends MapperFactoryBuilder<F, B>> {
protected UnenhanceStrategy unenhanceStrategy;
protected SuperTypeResolverStrategy superTypeStrategy;
protected ConstructorResolverStrategy constructorResolverStrategy;
protected CompilerStrategy compilerStrategy;
protected Set<ClassMap<?, ?>> classMaps;
protected ConverterFactory converterFactory;
protected PropertyResolverStrategy propertyResolverStrategy;
protected boolean usedBuiltinConverters = false;
protected boolean useAutoMapping = true;
public MapperFactoryBuilder() {
converterFactory = UtilityResolver.getDefaultConverterFactory();
constructorResolverStrategy = UtilityResolver.getDefaultConstructorResolverStrategy();
compilerStrategy = UtilityResolver.getDefaultCompilerStrategy();
propertyResolverStrategy = UtilityResolver.getDefaultPropertyResolverStrategy();
}
protected abstract B self();
public B classMaps(Set<ClassMap<?, ?>> classMaps) {
this.classMaps = classMaps;
return self();
}
public B unenhanceStrategy(UnenhanceStrategy unenhanceStrategy) {
this.unenhanceStrategy = unenhanceStrategy;
return self();
}
public B superTypeResolverStrategy(SuperTypeResolverStrategy superTypeStrategy) {
this.superTypeStrategy = superTypeStrategy;
return self();
}
public B constructorResolverStrategy(ConstructorResolverStrategy constructorResolverStrategy) {
this.constructorResolverStrategy = constructorResolverStrategy;
return self();
}
public B converterFactory(ConverterFactory converterFactory) {
this.converterFactory = converterFactory;
return self();
}
public B compilerStrategy(CompilerStrategy compilerStrategy) {
this.compilerStrategy = compilerStrategy;
return self();
}
public B propertyResolverStrategy(PropertyResolverStrategy propertyResolverStrategy) {
this.propertyResolverStrategy = propertyResolverStrategy;
return self();
}
public B useAutoMapping(boolean useAutoMapping) {
this.useAutoMapping = useAutoMapping;
return self();
}
public B usedBuiltinConverters(boolean useBuiltinConverters) {
this.usedBuiltinConverters = useBuiltinConverters;
return self();
}
/**
* @return a new instance of the Factory for which this builder is defined.
* The construction should be performed via the single-argument constructor which
* takes in a builder; no initialization code should be performed here, as it
* will not be inherited by subclasses; instead, place such initialization (defaults, etc.)
* in the Builder's constructor.
*/
public abstract F build();
}
/**
* Use this builder to generate instances of DefaultMapperFactory with the
* desired customizations.<br>
* <br>
*
* For example, an instance with no customizations could be generated with
* the following code:
*
* <pre>
* MapperFactory factory = new DefaultMapperFactory.Builder().build();
* </pre>
*
* @author [email protected]
*/
public static class Builder extends MapperFactoryBuilder<DefaultMapperFactory, Builder> {
/* (non-Javadoc)
* @see ma.glasnost.orika.impl.DefaultMapperFactory.MapperFactoryBuilder#build()
*/
@Override
public DefaultMapperFactory build() {
return new DefaultMapperFactory(this);
}
/* (non-Javadoc)
* @see ma.glasnost.orika.impl.DefaultMapperFactory.MapperFactoryBuilder#self()
*/
@Override
protected Builder self() {
return this;
}
}
/**
* Generates the UnenhanceStrategy to be used for this MapperFactory,
* applying the passed delegateStrategy if not null.<br>
* This allows the MapperFactory a chance to fill in the unenhance
* strategy with references to other parts of the factory (registered
* mappers, converters, object factories) which may be important in
* the "unenhancing" process.
*
* @param unenhanceStrategy
* @param overrideDefaultUnenhanceBehavior
* true if the passed UnenhanceStrategy should take full
* responsibility for un-enhancement; false if the default
* behavior should be applied as a fail-safe after consulting the
* passed strategy.
*
* @return
*/
protected UnenhanceStrategy buildUnenhanceStrategy(UnenhanceStrategy unenhanceStrategy, SuperTypeResolverStrategy superTypeStrategy) {
BaseUnenhancer unenhancer = new BaseUnenhancer();
if (unenhanceStrategy != null) {
unenhancer.addUnenhanceStrategy(unenhanceStrategy);
}
if (superTypeStrategy != null) {
unenhancer.addSuperTypeResolverStrategy(superTypeStrategy);
} else {
/*
* This strategy attempts to lookup super-type that has a registered
* mapper or converter whenever it is offered a class that is not
* currently mapped
*/
final SuperTypeResolverStrategy registeredMappersStrategy = new DefaultSuperTypeResolverStrategy() {
@Override
public boolean isAcceptable(Type<?> type) {
return type != null && aToBRegistry.containsKey(type);
}
};
unenhancer.addSuperTypeResolverStrategy(registeredMappersStrategy);
}
/*
* This strategy produces super-types whenever the proposed class type
* is not accessible to the compilerStrategy and/or the current thread
* context class-loader; it is added last as a fail-safe in case a
* suggested type cannot be used. It is automatically included, as
* there's no case when skipping it would be desired....
*/
final SuperTypeResolverStrategy inaccessibleTypeStrategy = new DefaultSuperTypeResolverStrategy() {
/**
* Tests whether the specified type is accessible to both the
* current thread's class-loader, and also to the compilerStrategy.
*
* @param type
* @return
*/
public boolean isTypeAccessible(Type<?> type) {
try {
Class<?> loadedType = Thread.currentThread().getContextClassLoader().loadClass(type.getName());
if (!type.getRawType().equals(loadedType)) {
return false;
}
compilerStrategy.assureTypeIsAccessible(type.getRawType());
return true;
} catch (ClassNotFoundException e) {
return false;
} catch (SourceCodeGenerationException e) {
return false;
}
}
@Override
public boolean isAcceptable(Type<?> type) {
return isTypeAccessible(type) && !java.lang.reflect.Proxy.class.equals(type.getRawType());
}
};
unenhancer.addSuperTypeResolverStrategy(inaccessibleTypeStrategy);
return unenhancer;
}
public Mapper<Object, Object> lookupMapper(MapperKey mapperKey) {
if (!existsRegisteredMapper(mapperKey.getAType(), mapperKey.getBType())) {
if(useAutoMapping) {
synchronized (this) {
try {
/*
* We shouldn't create a mapper for an immutable type; although it
* will succeed in generating an empty mapper, it won't actually result in a valid
* mapping, so it's better to throw an exception to indicate more clearly that
* something went wrong.
* However, there is a possibility that a custom ObjectFactory was registered for the
* immutable type, which would be valid.
*/
if (ClassUtil.isImmutable(mapperKey.getBType()) && !objectFactoryRegistry.containsKey(mapperKey.getBType())) {
throw new MappingException("No converter registered for " + mapperKey + ", nor any ObjectFactory " +
"which can generate " + mapperKey.getBType() + " from " + mapperKey.getAType());
}
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("No mapper registered for " + mapperKey + ": attempting to generate");
}
final ClassMap<?, ?> classMap = classMap(mapperKey.getAType(), mapperKey.getBType())
.byDefault().toClassMap();
buildObjectFactories(classMap);
buildMapper(classMap);
initializeUsedMappers(classMap);
} catch (MappingException e) {
e.setSourceType(mapperKey.getAType());
e.setDestinationType(mapperKey.getBType());
throw e;
}
}
}
}
return getRegisteredMapper(mapperKey);
}
public boolean existsRegisteredMapper(MapperKey mapperKey) {
return mappersRegistry.containsKey(mapperKey);
}
public boolean existsRegisteredMapper(Type<?> sourceType, Type<?> destinationType) {
for (Mapper<?,?> mapper: mappersRegistry.values()) {
if ((mapper.getAType().isAssignableFrom(sourceType) && mapper.getBType().isAssignableFrom(destinationType))
|| (mapper.getAType().isAssignableFrom(destinationType) && mapper.getBType().isAssignableFrom(sourceType))) {
return true;
}
}
return false;
}
@SuppressWarnings("unchecked")
protected <A,B> Mapper<A, B> getRegisteredMapper(MapperKey mapperKey) {
//return (Mapper<A, B>) mappersRegistry.get(mapperKey);
for (Mapper<?,?> mapper: mappersRegistry.values()) {
if ((mapper.getAType().isAssignableFrom(mapperKey.getAType()) && mapper.getBType().isAssignableFrom(mapperKey.getBType()))
|| (mapper.getAType().isAssignableFrom(mapperKey.getBType()) && mapper.getBType().isAssignableFrom(mapperKey.getAType()))) {
return (Mapper<A, B>) mapper;
}
}
return null;
}
/* (non-Javadoc)
* @see ma.glasnost.orika.MapperFactory#getMapperFacade()
*
* Since getMapperFacade() triggers the build() process, it is
* important that none of the methods called during the build()
* invoke getMapperFacade() again.
*
*/
public MapperFacade getMapperFacade() {
if (!isBuilt) {
synchronized (mapperFacade) {
if (!isBuilt) {
build();
}
}
}
return mapperFacade;
}
public <D> void registerObjectFactory(ObjectFactory<D> objectFactory, Type<D> destinationType) {
objectFactoryRegistry.put(destinationType, objectFactory);
}
@Deprecated
public void registerMappingHint(ma.glasnost.orika.MappingHint... hints) {
DefaultFieldMapper[] mappers = new DefaultFieldMapper[hints.length];
for (int i = 0, len = hints.length; i < len; ++i) {
mappers[i] = new ma.glasnost.orika.MappingHint.DefaultFieldMappingConverter(hints[i]);
}
registerDefaultFieldMapper(mappers);
}
public void registerDefaultFieldMapper(DefaultFieldMapper... mappers) {
this.defaultFieldMappers.addAll(Arrays.asList(mappers));
}
public void registerConcreteType(Type<?> abstractType, Type<?> concreteType) {
this.concreteTypeRegistry.put(abstractType, concreteType);
}
public void registerConcreteType(Class<?> abstractType, Class<?> concreteType) {
this.concreteTypeRegistry.put(abstractType, TypeFactory.valueOf(concreteType));
}
@SuppressWarnings("unchecked")
public <T> ObjectFactory<T> lookupObjectFactory(Type<T> targetType) {
if (targetType == null) {
return null;
}
ObjectFactory<T> result = (ObjectFactory<T>) objectFactoryRegistry.get(targetType);
if (result == null) {
// Check if we can use default constructor...
synchronized (this) {
Constructor<?>[] constructors = targetType.getRawType().getConstructors();
if (useAutoMapping || !isBuilt) {
if (constructors.length == 1 && constructors[0].getParameterTypes().length == 0) {
/*
* Use the default constructor in the case where it is the only option
*/
result = (ObjectFactory<T>) USE_DEFAULT_CONSTRUCTOR;
} else {
try {
result = (ObjectFactory<T>) objectFactoryGenerator.build(targetType);
} catch (MappingException e) {
for (Constructor<?> c: constructors) {
if (c.getParameterTypes().length == 0) {
result = (ObjectFactory<T>) USE_DEFAULT_CONSTRUCTOR;
break;
}
}
if (result == null) {
throw e;
}
}
}
objectFactoryRegistry.put(targetType, result);
} else {
for (Constructor<?> constructor: constructors) {
if (constructor.getParameterTypes().length == 0) {
result = (ObjectFactory<T>) USE_DEFAULT_CONSTRUCTOR;
break;
}
}
}
}
}
if (USE_DEFAULT_CONSTRUCTOR.equals(result)) {
result = null;
}
return result;
}
@SuppressWarnings("unchecked")
public <S, D> Type<? extends D> lookupConcreteDestinationType(Type<S> sourceType, Type<D> destinationType, MappingContext context) {
Type<? extends D> concreteType = context.getConcreteClass(sourceType, destinationType);
if (concreteType != null) {
return concreteType;
}
Set<Type<?>> destinationSet = aToBRegistry.get(sourceType);
if (destinationSet == null || destinationSet.isEmpty()) {
return null;
}
for (final Type<?> type : destinationSet) {
if (destinationType.isAssignableFrom(type) && ClassUtil.isConcrete(type)) {
return (Type<? extends D>) type;
}
}
if (concreteType == null) {
concreteType = (Type<? extends D>) this.concreteTypeRegistry.get(destinationType);
if (concreteType == null) {
concreteType = (Type<? extends D>) this.concreteTypeRegistry.get(destinationType.getRawType());
if (concreteType != null) {
concreteType = TypeFactory.resolveValueOf(concreteType.getRawType(), destinationType);
}
}
}
return concreteType;
}
@SuppressWarnings("unchecked")
public <A, B> void registerClassMap(ClassMap<A, B> classMap) {
classMapRegistry.put(new MapperKey(classMap.getAType(), classMap.getBType()), (ClassMap<Object, Object>) classMap);
}
public <A, B> void registerClassMap(ClassMapBuilder<A, B> builder) {
registerClassMap(builder.toClassMap());
}
public synchronized void build() {
if (!isBuilding) {
isBuilding = true;
converterFactory.setMapperFacade(mapperFacade);
buildClassMapRegistry();
for (final ClassMap<?, ?> classMap : classMapRegistry.values()) {
buildMapper(classMap);
}
for (final ClassMap<?, ?> classMap : classMapRegistry.values()) {
buildObjectFactories(classMap);
initializeUsedMappers(classMap);
}
isBuilt = true;
isBuilding = false;
}
}
public Set<ClassMap<Object, Object>> lookupUsedClassMap(MapperKey mapperKey) {
Set<ClassMap<Object, Object>> usedClassMapSet = usedMapperMetadataRegistry.get(mapperKey);
if (usedClassMapSet == null) {
usedClassMapSet = Collections.emptySet();
}
return usedClassMapSet;
}
private void buildClassMapRegistry() {
// prepare a map for classmap (stored as set)
Map<MapperKey, ClassMap<Object, Object>> classMapsDictionary = new HashMap<MapperKey, ClassMap<Object, Object>>();
Set<ClassMap<Object, Object>> classMaps = new HashSet<ClassMap<Object, Object>>(classMapRegistry.values());
for (final ClassMap<Object, Object> classMap : classMaps) {
classMapsDictionary.put(new MapperKey(classMap.getAType(), classMap.getBType()), classMap);
}
for (final ClassMap<?, ?> classMap : classMaps) {
MapperKey key = new MapperKey(classMap.getAType(), classMap.getBType());
Set<ClassMap<Object, Object>> usedClassMapSet = new HashSet<ClassMap<Object, Object>>();
for (final MapperKey parentMapperKey : classMap.getUsedMappers()) {
ClassMap<Object, Object> usedClassMap = classMapsDictionary.get(parentMapperKey);
if (usedClassMap == null) {
throw new MappingException("Cannot find class mapping using mapper : " + classMap.getMapperClassName());
}
usedClassMapSet.add(usedClassMap);
}
usedMapperMetadataRegistry.put(key, usedClassMapSet);
}
}
@SuppressWarnings({ "unchecked" })
private <S, D> void buildObjectFactories(ClassMap<S, D> classMap) {
Type<?> aType = classMap.getAType();
Type<?> bType = classMap.getBType();
if (classMap.getConstructorA() != null && lookupObjectFactory(aType) == null) {
GeneratedObjectFactory objectFactory = objectFactoryGenerator.build(aType);
registerObjectFactory(objectFactory, (Type<Object>) aType);
}
if (classMap.getConstructorB() != null && lookupObjectFactory(bType) == null) {
GeneratedObjectFactory objectFactory = objectFactoryGenerator.build(bType);
registerObjectFactory(objectFactory, (Type<Object>) bType);
}
}
private static final Comparator<MapperKey> MAPPER_COMPARATOR = new Comparator<MapperKey>() {
public int compare(MapperKey key1, MapperKey key2) {
if (key1.getAType().isAssignableFrom(key2.getAType()) && key1.getBType().isAssignableFrom(key2.getBType())) {
return 1;
} else if (key2.getAType().isAssignableFrom(key1.getAType()) && key2.getBType().isAssignableFrom(key1.getBType())) {
return -1;
} else if (key1.getAType().equals(key2.getAType()) && key1.getBType().equals(key2.getBType())) {
return 0;
} else {
throw new IllegalArgumentException("keys " + key1 + " and " + key2 + " are unrelated");
}
}
};
@SuppressWarnings("unchecked")
private void initializeUsedMappers(ClassMap<?, ?> classMap) {
Mapper<Object, Object> mapper = lookupMapper(new MapperKey(classMap.getAType(), classMap.getBType()));
List<Mapper<Object, Object>> parentMappers = new ArrayList<Mapper<Object, Object>>();
if (!classMap.getUsedMappers().isEmpty()) {
for (MapperKey parentMapperKey : classMap.getUsedMappers()) {
collectUsedMappers(classMap, parentMappers, parentMapperKey);
}
} else {
/*
* Attempt to auto-determine used mappers for this classmap;
* however, we should only add the most-specific of the available
* mappers to avoid calling the same mapper multiple times during a
* single map request
*/
Set<MapperKey> usedMappers = new TreeSet<MapperKey>(MAPPER_COMPARATOR);
for (MapperKey key : this.classMapRegistry.keySet()) {
if (!key.getAType().equals(classMap.getAType()) || !key.getBType().equals(classMap.getBType())) {
if (key.getAType().isAssignableFrom(classMap.getAType()) && key.getBType().isAssignableFrom(classMap.getBType())) {
usedMappers.add(key);
}
}
}
if (!usedMappers.isEmpty()) {
// Set<ClassMap<Object, Object>> usedClassMapSet = new
// HashSet<ClassMap<Object, Object>>();
MapperKey parentKey = usedMappers.iterator().next();
// usedClassMapSet.add(classMapRegistry.get(parentKey));
// usedMapperMetadataRegistry.put(parentKey, usedClassMapSet);
collectUsedMappers(classMap, parentMappers, parentKey);
}
}
mapper.setUsedMappers(parentMappers.toArray(new Mapper[parentMappers.size()]));
}
private void collectUsedMappers(ClassMap<?, ?> classMap, List<Mapper<Object, Object>> parentMappers, MapperKey parentMapperKey) {
Mapper<Object, Object> parentMapper = lookupMapper(parentMapperKey);
if (parentMapper == null) {
throw new MappingException("Cannot find used mappers for : " + classMap.getMapperClassName());
}
parentMappers.add(parentMapper);
Set<ClassMap<Object, Object>> usedClassMapSet = usedMapperMetadataRegistry.get(parentMapperKey);
if (usedClassMapSet != null) {
for (ClassMap<Object, Object> cm : usedClassMapSet) {
collectUsedMappers(cm, parentMappers, new MapperKey(cm.getAType(), cm.getBType()));
}
}
}
@SuppressWarnings("unchecked")
private void buildMapper(ClassMap<?, ?> classMap) {
register(classMap.getAType(), classMap.getBType());
register(classMap.getBType(), classMap.getAType());
final MapperKey mapperKey = new MapperKey(classMap.getAType(), classMap.getBType());
final GeneratedMapperBase mapper = this.mapperGenerator.build(classMap);
mapper.setMapperFacade(mapperFacade);
if (classMap.getCustomizedMapper() != null) {
final Mapper<Object, Object> customizedMapper = (Mapper<Object, Object>) classMap.getCustomizedMapper();
mapper.setCustomMapper(customizedMapper);
}
mappersRegistry.put(mapperKey, mapper);
classMapRegistry.put(mapperKey, (ClassMap<Object, Object>) classMap);
}
protected <S, D> void register(Type<S> sourceClass, Type<D> destinationClass) {
Set<Type<?>> destinationSet = aToBRegistry.get(sourceClass);
if (destinationSet == null) {
destinationSet = new TreeSet<Type<?>>();
aToBRegistry.put(sourceClass, destinationSet);
}
destinationSet.add(destinationClass);
}
@SuppressWarnings("unchecked")
public <A, B> ClassMap<A, B> getClassMap(MapperKey mapperKey) {
return (ClassMap<A, B>) classMapRegistry.get(mapperKey);
}
public Set<Type<? extends Object>> lookupMappedClasses(Type<?> type) {
return aToBRegistry.get(type);
}
public ConverterFactory getConverterFactory() {
return converterFactory;
}
public <T> void registerObjectFactory(ObjectFactory<T> objectFactory, Class<T> targetClass) {
registerObjectFactory(objectFactory, TypeFactory.<T>valueOf(targetClass));
}
protected ClassMapBuilderFactory getClassMapBuilderFactory() {
if (classMapBuilderFactory == null) {
synchronized(this) {
if (classMapBuilderFactory == null) {
classMapBuilderFactory = new ClassMapBuilderFactory(this.propertyResolverStrategy,
defaultFieldMappers.toArray(new DefaultFieldMapper[defaultFieldMappers.size()]));
}
}
}
return classMapBuilderFactory;
}
public <A, B> ClassMapBuilder<A, B> classMap(Type<A> aType, Type<B> bType) {
return getClassMapBuilderFactory().map(aType, bType);
}
public <A, B> ClassMapBuilder<A, B> classMap(Class<A> aType, Type<B> bType) {
return classMap(TypeFactory.<A>valueOf(aType), bType);
}
public <A, B> ClassMapBuilder<A, B> classMap(Type<A> aType, Class<B> bType) {
return classMap(aType, TypeFactory.<B>valueOf(bType));
}
public <A, B> ClassMapBuilder<A, B> classMap(Class<A> aType, Class<B> bType) {
return classMap(TypeFactory.<A>valueOf(aType), TypeFactory.<B>valueOf(bType));
}
/* (non-Javadoc)
* @see ma.glasnost.orika.MapperFactory#registerMapper(ma.glasnost.orika.Mapper)
*/
public <A, B> void registerMapper(Mapper<A, B> mapper) {
synchronized(this) {
this.mappersRegistry.put(new MapperKey(mapper.getAType(), mapper.getBType()), mapper);
mapper.setMapperFacade(this.mapperFacade);
register(mapper.getAType(), mapper.getBType());
register(mapper.getBType(), mapper.getAType());
}
}
}
| Fixed error message on no registered immutable type converter
git-svn-id: cd18ad63d0313fc81f5089058a1f5cc6e016da00@497 f4a4e40d-1d15-de9b-c3e8-c5ea35f5a4c4
| core/src/main/java/ma/glasnost/orika/impl/DefaultMapperFactory.java | Fixed error message on no registered immutable type converter |
|
Java | apache-2.0 | 2aaeb8846b812af5977899e7f389ad73ecc69d34 | 0 | atomix/atomix,kuujo/copycat,atomix/atomix,kuujo/copycat | /*
* Copyright 2017-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.atomix.cluster.messaging.impl;
import io.atomix.messaging.Endpoint;
import io.atomix.messaging.ManagedMessagingService;
import io.atomix.messaging.MessagingException.NoRemoteHandler;
import io.atomix.messaging.MessagingService;
import io.atomix.utils.concurrent.ComposableFuture;
import io.atomix.utils.concurrent.Futures;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Test messaging service.
*/
public class TestMessagingService implements ManagedMessagingService {
private final Endpoint endpoint;
private final Map<Endpoint, TestMessagingService> services;
private final Map<String, BiFunction<Endpoint, byte[], CompletableFuture<byte[]>>> handlers = new ConcurrentHashMap<>();
private final AtomicBoolean open = new AtomicBoolean();
public TestMessagingService(Endpoint endpoint, Map<Endpoint, TestMessagingService> services) {
this.endpoint = endpoint;
this.services = services;
}
/**
* Returns the test service for the given endpoint or {@code null} if none has been created.
*/
private TestMessagingService getService(Endpoint endpoint) {
checkNotNull(endpoint);
return services.get(endpoint);
}
/**
* Returns the given handler for the given endpoint.
*/
private BiFunction<Endpoint, byte[], CompletableFuture<byte[]>> getHandler(Endpoint endpoint, String type) {
TestMessagingService service = getService(endpoint);
if (service == null) {
return (e, p) -> Futures.exceptionalFuture(new NoRemoteHandler());
}
BiFunction<Endpoint, byte[], CompletableFuture<byte[]>> handler = service.handlers.get(checkNotNull(type));
if (handler == null) {
return (e, p) -> Futures.exceptionalFuture(new NoRemoteHandler());
}
return handler;
}
@Override
public CompletableFuture<Void> sendAsync(Endpoint ep, String type, byte[] payload) {
return getHandler(ep, type).apply(endpoint, payload).thenApply(v -> null);
}
@Override
public CompletableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload) {
return getHandler(ep, type).apply(endpoint, payload);
}
@Override
public CompletableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload, Executor executor) {
ComposableFuture<byte[]> future = new ComposableFuture<>();
sendAndReceive(ep, type, payload).whenCompleteAsync(future, executor);
return future;
}
@Override
public void registerHandler(String type, BiConsumer<Endpoint, byte[]> handler, Executor executor) {
checkNotNull(type);
checkNotNull(handler);
handlers.put(type, (e, p) -> {
try {
executor.execute(() -> handler.accept(e, p));
return CompletableFuture.completedFuture(new byte[0]);
} catch (RejectedExecutionException e2) {
return Futures.exceptionalFuture(e2);
}
});
}
@Override
public void registerHandler(String type, BiFunction<Endpoint, byte[], byte[]> handler, Executor executor) {
checkNotNull(type);
checkNotNull(handler);
handlers.put(type, (e, p) -> {
CompletableFuture<byte[]> future = new CompletableFuture<>();
try {
executor.execute(() -> future.complete(handler.apply(e, p)));
} catch (RejectedExecutionException e2) {
future.completeExceptionally(e2);
}
return future;
});
}
@Override
public void registerHandler(String type, BiFunction<Endpoint, byte[], CompletableFuture<byte[]>> handler) {
checkNotNull(type);
checkNotNull(handler);
handlers.put(type, handler);
}
@Override
public void unregisterHandler(String type) {
handlers.remove(checkNotNull(type));
}
@Override
public CompletableFuture<MessagingService> open() {
services.put(endpoint, this);
open.set(true);
return CompletableFuture.completedFuture(this);
}
@Override
public boolean isOpen() {
return open.get();
}
@Override
public CompletableFuture<Void> close() {
services.remove(endpoint);
open.set(false);
return CompletableFuture.completedFuture(null);
}
@Override
public boolean isClosed() {
return !open.get();
}
}
| cluster/src/test/java/io/atomix/cluster/messaging/impl/TestMessagingService.java | /*
* Copyright 2017-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.atomix.cluster.messaging.impl;
import io.atomix.messaging.Endpoint;
import io.atomix.messaging.ManagedMessagingService;
import io.atomix.messaging.MessagingException.NoRemoteHandler;
import io.atomix.messaging.MessagingService;
import io.atomix.utils.concurrent.ComposableFuture;
import io.atomix.utils.concurrent.Futures;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Test messaging service.
*/
public class TestMessagingService implements ManagedMessagingService {
private final Endpoint endpoint;
private final Map<Endpoint, TestMessagingService> services;
private final Map<String, BiFunction<Endpoint, byte[], CompletableFuture<byte[]>>> handlers = new ConcurrentHashMap<>();
private final AtomicBoolean open = new AtomicBoolean();
public TestMessagingService(Endpoint endpoint, Map<Endpoint, TestMessagingService> services) {
this.endpoint = endpoint;
this.services = services;
}
/**
* Returns the test service for the given endpoint or {@code null} if none has been created.
*/
private TestMessagingService getService(Endpoint endpoint) {
checkNotNull(endpoint);
return services.get(endpoint);
}
/**
* Returns the given handler for the given endpoint.
*/
private BiFunction<Endpoint, byte[], CompletableFuture<byte[]>> getHandler(Endpoint endpoint, String type) {
TestMessagingService service = getService(endpoint);
if (service == null) {
return (e, p) -> Futures.exceptionalFuture(new NoRemoteHandler());
}
BiFunction<Endpoint, byte[], CompletableFuture<byte[]>> handler = service.handlers.get(checkNotNull(type));
if (handler == null) {
return (e, p) -> Futures.exceptionalFuture(new NoRemoteHandler());
}
return handler;
}
@Override
public CompletableFuture<Void> sendAsync(Endpoint ep, String type, byte[] payload) {
return getHandler(ep, type).apply(endpoint, payload).thenApply(v -> null);
}
@Override
public CompletableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload) {
return getHandler(ep, type).apply(endpoint, payload);
}
@Override
public CompletableFuture<byte[]> sendAndReceive(Endpoint ep, String type, byte[] payload, Executor executor) {
ComposableFuture<byte[]> future = new ComposableFuture<>();
sendAndReceive(ep, type, payload).whenCompleteAsync(future, executor);
return future;
}
@Override
public void registerHandler(String type, BiConsumer<Endpoint, byte[]> handler, Executor executor) {
checkNotNull(type);
checkNotNull(handler);
handlers.put(type, (e, p) -> {
executor.execute(() -> handler.accept(e, p));
return CompletableFuture.completedFuture(new byte[0]);
});
}
@Override
public void registerHandler(String type, BiFunction<Endpoint, byte[], byte[]> handler, Executor executor) {
checkNotNull(type);
checkNotNull(handler);
handlers.put(type, (e, p) -> {
CompletableFuture<byte[]> future = new CompletableFuture<>();
executor.execute(() -> future.complete(handler.apply(e, p)));
return future;
});
}
@Override
public void registerHandler(String type, BiFunction<Endpoint, byte[], CompletableFuture<byte[]>> handler) {
checkNotNull(type);
checkNotNull(handler);
handlers.put(type, handler);
}
@Override
public void unregisterHandler(String type) {
handlers.remove(checkNotNull(type));
}
@Override
public CompletableFuture<MessagingService> open() {
services.put(endpoint, this);
open.set(true);
return CompletableFuture.completedFuture(this);
}
@Override
public boolean isOpen() {
return open.get();
}
@Override
public CompletableFuture<Void> close() {
services.remove(endpoint);
open.set(false);
return CompletableFuture.completedFuture(null);
}
@Override
public boolean isClosed() {
return !open.get();
}
}
| Handle execution exceptions in TestMessagingService.
| cluster/src/test/java/io/atomix/cluster/messaging/impl/TestMessagingService.java | Handle execution exceptions in TestMessagingService. |
|
Java | apache-2.0 | f9195ced28746d30b9f07135ee1eca53b3bfac3a | 0 | lburgazzoli/logging-log4j2,xnslong/logging-log4j2,GFriedrich/logging-log4j2,lburgazzoli/apache-logging-log4j2,apache/logging-log4j2,GFriedrich/logging-log4j2,codescale/logging-log4j2,xnslong/logging-log4j2,GFriedrich/logging-log4j2,lburgazzoli/logging-log4j2,lburgazzoli/apache-logging-log4j2,apache/logging-log4j2,lqbweb/logging-log4j2,apache/logging-log4j2,codescale/logging-log4j2,xnslong/logging-log4j2,codescale/logging-log4j2,lqbweb/logging-log4j2,lburgazzoli/logging-log4j2,lburgazzoli/apache-logging-log4j2,lqbweb/logging-log4j2 | /*
* 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.logging.log4j.util;
import java.util.Map.Entry;
/**
* <em>Consider this class private.</em>
*/
public class StringBuilders {
private StringBuilders() {
}
/**
* Appends in the following format: double quoted value.
*
* @param sb a string builder
* @param value a value
* @return {@code "value"}
*/
public static StringBuilder appendDqValue(final StringBuilder sb, final Object value) {
return sb.append(Chars.DQUOTE).append(value).append(Chars.DQUOTE);
}
/**
* Appends in the following format: key=double quoted value.
*
* @param sb a string builder
* @param entry a map entry
* @return {@code key="value"}
*/
public static StringBuilder appendKeyDqValue(final StringBuilder sb, final Entry<String, String> entry) {
return appendKeyDqValue(sb, entry.getKey(), entry.getValue());
}
/**
* Appends in the following format: key=double quoted value.
*
* @param sb a string builder
* @param key a key
* @param value a value
* @return {@code key="value"}
*/
public static StringBuilder appendKeyDqValue(final StringBuilder sb, final String key, final Object value) {
return sb.append(key).append(Chars.EQ).append(Chars.DQUOTE).append(value).append(Chars.DQUOTE);
}
}
| log4j-api/src/main/java/org/apache/logging/log4j/util/StringBuilders.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.logging.log4j.util;
import java.util.Map.Entry;
/**
* <em>Consider this class private.</em>
*/
public class StringBuilders {
/**
* Appends in the following format: double quoted value.
*
* @param sb
* a string builder
* @param value
* a value
* @return {@code "value"}
*/
public static StringBuilder appendDqValue(final StringBuilder sb, final Object value) {
return sb.append(Chars.DQUOTE).append(value).append(Chars.DQUOTE);
}
/**
* Appends in the following format: key=double quoted value.
*
* @param sb
* a string builder
* @param entry
* a map entry
* @return {@code key="value"}
*/
public static StringBuilder appendKeyDqValue(final StringBuilder sb, final Entry<String, String> entry) {
return appendKeyDqValue(sb, entry.getKey(), entry.getValue());
}
/**
* Appends in the following format: key=double quoted value.
*
* @param sb
* a string builder
* @param key
* a key
* @param value
* a value
* @return {@code key="value"}
*/
public static StringBuilder appendKeyDqValue(final StringBuilder sb, final String key, final Object value) {
return sb.append(key).append(Chars.EQ).append(Chars.DQUOTE).append(value).append(Chars.DQUOTE);
}
}
| Checkstyle: util class should have private constructor, IDE autoformat
| log4j-api/src/main/java/org/apache/logging/log4j/util/StringBuilders.java | Checkstyle: util class should have private constructor, IDE autoformat |
|
Java | apache-2.0 | fd5c15d097ce63a0f74915eda9b0806e63949692 | 0 | harrissoerja/belajar-nfc,artivisi/belajar-nfc,artivisi/belajar-nfc,harrissoerja/belajar-nfc,harrissoerja/belajar-nfc,artivisi/belajar-nfc | package belajar.nfc.controller;
import belajar.nfc.domain.Customer;
import belajar.nfc.domain.EntriTransaksi;
import belajar.nfc.domain.Saldo;
import belajar.nfc.service.EntriTransaksiDao;
import belajar.nfc.service.SaldoDao;
import java.math.BigDecimal;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.threeten.bp.Instant;
import org.threeten.bp.temporal.ChronoUnit;
/**
*
* @author mohamad
*/
@RestController
@RequestMapping("/api/bayar")
public class PembayaranController extends OptionsController {
@Autowired
private SaldoDao saldoDao;
@Autowired
private EntriTransaksiDao entriTransaksiDao;
@RequestMapping(method = RequestMethod.GET)
public Iterable<Saldo> findAllSaldo() {
return saldoDao.findAll();
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public Saldo findOne(@PathVariable(value = "id") String id) {
return saldoDao.findOne(id);
}
@RequestMapping(value = "/{id}", method = RequestMethod.POST)
public void bayarTagihan(@PathVariable String id) throws Exception {
EntriTransaksi entriTransaksi = entriTransaksiDao.findOne(id);
Saldo saldo = saldoDao.findSaldoByCustomerAndTanggal(entriTransaksi.getCustomer(), new Date());
if(saldo != null){
saldo.setMutasiKredit(saldo.getMutasiKredit().add(entriTransaksi.getNilaiTransaksi()));
saldoDao.save(saldo);
}
else if(saldo == null) {
Saldo newSaldo = new Saldo();
newSaldo.setTanggal(new Date());
newSaldo.setSaldoAwal(hitungSaldoAkhir(entriTransaksi.getCustomer()));
newSaldo.setMutasiDebet(BigDecimal.ZERO);
newSaldo.setMutasiKredit(entriTransaksi.getNilaiTransaksi());
newSaldo.setCustomer(entriTransaksi.getCustomer());
saldoDao.save(newSaldo);
}
entriTransaksi.setLunas(Boolean.TRUE);
entriTransaksiDao.save(entriTransaksi);
}
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public void deleteTagihan(@PathVariable(value = "id") String id) throws Exception {
Saldo saldo = saldoDao.findOne(id);
if (saldo == null)
throw new Exception("Data tidak ditemukan");
else
saldoDao.delete(saldo);
}
public BigDecimal hitungSaldoAkhir(Customer customer)throws Exception {
Instant kemarin = Instant.now().minus(1, ChronoUnit.DAYS);
Saldo saldoAkhir = saldoDao.findSaldoByCustomerAndTanggal(customer, new Date(kemarin.toEpochMilli()));
BigDecimal result = BigDecimal.ZERO;
if(saldoAkhir != null){
result = saldoAkhir.getSaldoAwal().add(saldoAkhir.getMutasiDebet()).subtract(saldoAkhir.getMutasiKredit());
}
return result;
}
}
| belajar-nfc-server/src/main/java/belajar/nfc/controller/PembayaranController.java | package belajar.nfc.controller;
import belajar.nfc.domain.Customer;
import belajar.nfc.domain.EntriTransaksi;
import belajar.nfc.domain.Saldo;
import belajar.nfc.service.EntriTransaksiDao;
import belajar.nfc.service.SaldoDao;
import java.math.BigDecimal;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.threeten.bp.Instant;
import org.threeten.bp.temporal.ChronoUnit;
/**
*
* @author mohamad
*/
@RestController
@RequestMapping("/api/bayar")
public class PembayaranController extends OptionsController {
@Autowired
private SaldoDao saldoDao;
@Autowired
private EntriTransaksiDao entriTransaksiDao;
@RequestMapping(method = RequestMethod.GET)
public Iterable<Saldo> findAllSaldo() {
return saldoDao.findAll();
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public Saldo findOne(@PathVariable(value = "id") String id) {
return saldoDao.findOne(id);
}
@RequestMapping(value = "/{id}", method = RequestMethod.POST)
public void bayarTagihan(@PathVariable String id) throws Exception {
EntriTransaksi entriTransaksi = entriTransaksiDao.findOne(id);
Saldo saldo = saldoDao.findSaldoByCustomerAndTanggal(entriTransaksi.getCustomer(), new Date());
if(saldo != null){
saldo.setMutasiKredit(saldo.getMutasiKredit().add(entriTransaksi.getNilaiTransaksi()));
saldoDao.save(saldo);
}
else if(saldo == null) {
Saldo newSaldo = new Saldo();
newSaldo.setTanggal(new Date());
newSaldo.setSaldoAwal(hitungSaldoAkhir(entriTransaksi.getCustomer()));
newSaldo.setMutasiDebet(BigDecimal.ZERO);
newSaldo.setMutasiKredit(entriTransaksi.getNilaiTransaksi());
newSaldo.setCustomer(entriTransaksi.getCustomer());
saldoDao.save(newSaldo);
}
else { throw new Exception("Gagal menyimpan/merubah saldo"); }
}
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public void deleteTagihan(@PathVariable(value = "id") String id) throws Exception {
Saldo saldo = saldoDao.findOne(id);
if (saldo == null)
throw new Exception("Data tidak ditemukan");
else
saldoDao.delete(saldo);
}
public BigDecimal hitungSaldoAkhir(Customer customer)throws Exception {
Instant kemarin = Instant.now().minus(1, ChronoUnit.DAYS);
Saldo saldoAkhir = saldoDao.findSaldoByCustomerAndTanggal(customer, new Date(kemarin.toEpochMilli()));
BigDecimal result = BigDecimal.ZERO;
if(saldoAkhir != null){
result = saldoAkhir.getSaldoAwal().add(saldoAkhir.getMutasiDebet()).subtract(saldoAkhir.getMutasiKredit());
}
return result;
}
}
| tambah action bayar di entri transaksi
| belajar-nfc-server/src/main/java/belajar/nfc/controller/PembayaranController.java | tambah action bayar di entri transaksi |
|
Java | bsd-2-clause | 874dbc9dba0d526fc4c6ead5166e722032239cba | 0 | mwilliamson/java-mammoth | package org.zwobble.mammoth.internal.util;
import java.util.*;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.Arrays.asList;
import static org.zwobble.mammoth.internal.util.MammothIterables.stream;
public class MammothLists {
public static <T> List<T> list() {
return Collections.emptyList();
}
public static <T> List<T> list(T value1) {
return Collections.singletonList(value1);
}
public static <T> List<T> list(T value1, T value2) {
return asList(value1, value2);
}
public static <T> List<T> list(T value1, T value2, T value3) {
return asList(value1, value2, value3);
}
@SafeVarargs
public static <T> List<T> list(T... values) {
return asList(values);
}
public static <T> List<T> cons(T head, Iterable<T> tail) {
return eagerConcat(list(head), tail);
}
public static <T> List<T> eagerConcat(Iterable<T> first, Iterable<T> second) {
return Stream.concat(stream(first), stream(second)).collect(Collectors.toList());
}
public static <T> List<T> eagerFilter(Iterable<T> iterable, Predicate<T> predicate) {
return stream(iterable).filter(predicate).collect(Collectors.toList());
}
public static <T, R> List<R> eagerMap(Iterable<T> iterable, Function<T, R> function) {
return stream(iterable).map(function).collect(Collectors.toList());
}
public static <T, R> List<R> eagerFlatMap(Iterable<T> iterable, Function<T, Iterable<R>> function) {
return stream(iterable)
.flatMap(element -> stream(function.apply(element)))
.collect(Collectors.toList());
}
public static <T, R extends Comparable<R>> List<T> orderedBy(Iterable<T> iterable, Function<T, R> getKey) {
return stream(iterable)
.sorted(orderBy(getKey))
.collect(Collectors.toList());
}
private static <T, R extends Comparable<R>> Comparator<T> orderBy(Function<T, R> getKey) {
return (first, second) -> getKey.apply(first).compareTo(getKey.apply(second));
}
public static <T> List<T> toList(Iterable<T> iterable) {
return stream(iterable).collect(Collectors.toList());
}
public static <T> Optional<T> tryGetLast(List<T> list) {
if (list.isEmpty()) {
return Optional.empty();
} else {
return Optional.of(list.get(list.size() - 1));
}
}
public static <T> List<T> skip(List<T> list, int count) {
return list.subList(Math.min(list.size(), count), list.size());
}
public static <T> Iterable<T> reversed(List<T> list) {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
ListIterator<T> iterator = list.listIterator(list.size());
return new Iterator<T>() {
@Override
public boolean hasNext() {
return iterator.hasPrevious();
}
@Override
public T next() {
return iterator.previous();
}
};
}
};
}
}
| src/main/java/org/zwobble/mammoth/internal/util/MammothLists.java | package org.zwobble.mammoth.internal.util;
import com.google.common.collect.Ordering;
import java.util.*;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.Arrays.asList;
import static org.zwobble.mammoth.internal.util.MammothIterables.stream;
public class MammothLists {
public static <T> List<T> list() {
return Collections.emptyList();
}
public static <T> List<T> list(T value1) {
return Collections.singletonList(value1);
}
public static <T> List<T> list(T value1, T value2) {
return asList(value1, value2);
}
public static <T> List<T> list(T value1, T value2, T value3) {
return asList(value1, value2, value3);
}
@SafeVarargs
public static <T> List<T> list(T... values) {
return asList(values);
}
public static <T> List<T> cons(T head, Iterable<T> tail) {
return eagerConcat(list(head), tail);
}
public static <T> List<T> eagerConcat(Iterable<T> first, Iterable<T> second) {
return Stream.concat(stream(first), stream(second)).collect(Collectors.toList());
}
public static <T> List<T> eagerFilter(Iterable<T> iterable, Predicate<T> predicate) {
return stream(iterable).filter(predicate).collect(Collectors.toList());
}
public static <T, R> List<R> eagerMap(Iterable<T> iterable, Function<T, R> function) {
return stream(iterable).map(function).collect(Collectors.toList());
}
public static <T, R> List<R> eagerFlatMap(Iterable<T> iterable, Function<T, Iterable<R>> function) {
return stream(iterable)
.flatMap(element -> stream(function.apply(element)))
.collect(Collectors.toList());
}
public static <T, R extends Comparable<R>> List<T> orderedBy(Iterable<T> iterable, Function<T, R> getKey) {
return orderBy(getKey).sortedCopy(iterable);
}
private static <T, R extends Comparable<R>> Ordering<T> orderBy(Function<T, R> getKey) {
return Ordering.from((first, second) -> getKey.apply(first).compareTo(getKey.apply(second)));
}
public static <T> List<T> toList(Iterable<T> iterable) {
return stream(iterable).collect(Collectors.toList());
}
public static <T> Optional<T> tryGetLast(List<T> list) {
if (list.isEmpty()) {
return Optional.empty();
} else {
return Optional.of(list.get(list.size() - 1));
}
}
public static <T> List<T> skip(List<T> list, int count) {
return list.subList(Math.min(list.size(), count), list.size());
}
public static <T> Iterable<T> reversed(List<T> list) {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
ListIterator<T> iterator = list.listIterator(list.size());
return new Iterator<T>() {
@Override
public boolean hasNext() {
return iterator.hasPrevious();
}
@Override
public T next() {
return iterator.previous();
}
};
}
};
}
}
| Remove Guava usage from MammothLists
| src/main/java/org/zwobble/mammoth/internal/util/MammothLists.java | Remove Guava usage from MammothLists |
|
Java | bsd-3-clause | 338515f79ea5be59605aaf66069d7ce6ee32b36e | 0 | eclipse/rdf4j,eclipse/rdf4j,eclipse/rdf4j,eclipse/rdf4j,eclipse/rdf4j,eclipse/rdf4j | /*******************************************************************************
* Copyright (c) 2018 Eclipse RDF4J contributors.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Distribution License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*******************************************************************************/
package org.eclipse.rdf4j.sail.shacl;
import org.eclipse.rdf4j.IsolationLevel;
import org.eclipse.rdf4j.IsolationLevels;
import org.eclipse.rdf4j.common.io.IOUtil;
import org.eclipse.rdf4j.model.Model;
import org.eclipse.rdf4j.model.ValueFactory;
import org.eclipse.rdf4j.repository.RepositoryException;
import org.eclipse.rdf4j.repository.sail.SailRepository;
import org.eclipse.rdf4j.repository.sail.SailRepositoryConnection;
import org.eclipse.rdf4j.rio.RDFFormat;
import org.eclipse.rdf4j.rio.Rio;
import org.eclipse.rdf4j.rio.WriterConfig;
import org.eclipse.rdf4j.rio.helpers.BasicWriterSettings;
import org.eclipse.rdf4j.sail.memory.MemoryStore;
import org.eclipse.rdf4j.sail.shacl.results.ValidationReport;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static junit.framework.TestCase.assertTrue;
import static org.junit.Assert.assertFalse;
/**
* @author Håvard Ottestad
*/
@RunWith(Parameterized.class)
abstract public class AbstractShaclTest {
// @formatter:off
// formatter doesn't understand that the trailing ) needs to be on a new line.
private static final List<String> testCasePaths = Stream.of(
"test-cases/complex/dcat",
"test-cases/complex/foaf",
"test-cases/datatype/simple",
"test-cases/datatype/targetNode",
"test-cases/datatype/targetSubjectsOf",
"test-cases/datatype/targetSubjectsOfSingle",
"test-cases/datatype/targetObjectsOf",
"test-cases/datatype/validateTarget",
"test-cases/minLength/simple",
"test-cases/maxLength/simple",
"test-cases/pattern/simple",
"test-cases/pattern/multiple",
"test-cases/languageIn/simple",
"test-cases/nodeKind/simple",
"test-cases/nodeKind/validateTarget",
"test-cases/minCount/simple",
"test-cases/minCount/targetNode",
"test-cases/maxCount/simple",
"test-cases/maxCount/targetNode",
"test-cases/or/multiple",
"test-cases/or/inheritance",
"test-cases/or/inheritance-deep",
"test-cases/or/inheritance-deep-minCountMaxCount",
"test-cases/or/inheritanceNodeShape",
"test-cases/or/datatype",
"test-cases/or/datatypeTargetNode",
"test-cases/or/minCountMaxCount",
"test-cases/or/maxCount",
"test-cases/or/minCount",
"test-cases/or/nodeKindMinLength",
"test-cases/or/implicitAnd",
"test-cases/or/datatypeDifferentPaths",
"test-cases/or/class",
"test-cases/or/classValidateTarget",
"test-cases/or/datatype2",
"test-cases/or/minCountDifferentPath",
"test-cases/or/nodeKindValidateTarget",
"test-cases/or/datatypeNodeShape",
"test-cases/minExclusive/simple",
"test-cases/minExclusive/dateVsTime",
"test-cases/maxExclusive/simple",
"test-cases/minInclusive/simple",
"test-cases/maxInclusive/simple",
"test-cases/implicitTargetClass/simple",
"test-cases/class/simple",
"test-cases/class/and",
"test-cases/class/subclass",
"test-cases/class/targetNode",
"test-cases/class/multipleClass",
"test-cases/class/validateTarget",
"test-cases/deactivated/nodeshape",
"test-cases/deactivated/or",
"test-cases/deactivated/propertyshape",
"test-cases/in/simple",
"test-cases/uniqueLang/simple",
"test-cases/propertyShapeWithTarget/simple",
"test-cases/and-or/datatypeNodeShape"
)
.distinct()
.sorted()
.collect(Collectors.toList());
// @formatter:on
final String testCasePath;
final String path;
final ExpectedResult expectedResult;
final IsolationLevel isolationLevel;
public AbstractShaclTest(String testCasePath, String path, ExpectedResult expectedResult,
IsolationLevel isolationLevel) {
this.testCasePath = testCasePath;
this.path = path;
this.expectedResult = expectedResult;
this.isolationLevel = isolationLevel;
}
@Parameterized.Parameters(name = "{2} - {1} - {3}")
public static Collection<Object[]> data() {
return getTestsToRun();
}
private static List<String> findTestCases(String testCase, String baseCase) {
List<String> ret = new ArrayList<>();
for (int i = 0; i < 100; i++) {
String path = testCase + "/" + baseCase + "/case" + i;
InputStream resourceAsStream = AbstractShaclTest.class.getClassLoader().getResourceAsStream(path);
if (resourceAsStream != null) {
ret.add(path);
try {
resourceAsStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
return ret;
}
private static Collection<Object[]> getTestsToRun() {
List<Object[]> ret = new ArrayList<>();
for (String testCasePath : testCasePaths) {
for (ExpectedResult baseCase : ExpectedResult.values()) {
findTestCases(testCasePath, baseCase.name()).forEach(path -> {
for (IsolationLevel isolationLevel : Arrays.asList(IsolationLevels.NONE, IsolationLevels.SNAPSHOT,
IsolationLevels.SERIALIZABLE)) {
Object[] temp = { testCasePath, path, baseCase, isolationLevel };
ret.add(temp);
}
});
}
}
return ret;
}
static void runTestCase(String shaclPath, String dataPath, ExpectedResult expectedResult,
IsolationLevel isolationLevel, boolean preloadWithDummyData) throws Exception {
if (!dataPath.endsWith("/")) {
dataPath = dataPath + "/";
}
if (!shaclPath.endsWith("/")) {
shaclPath = shaclPath + "/";
}
String shaclFile = shaclPath + "shacl.ttl";
System.out.println(shaclFile);
SailRepository shaclRepository = getShaclSail();
Utils.loadShapeData(shaclRepository, shaclFile);
boolean exception = false;
boolean ran = false;
if (preloadWithDummyData) {
try (SailRepositoryConnection connection = shaclRepository.getConnection()) {
connection.begin(isolationLevel);
ValueFactory vf = connection.getValueFactory();
connection.add(vf.createBNode(), vf.createIRI("http://example.com/jkhsdfiu3r2y9fjr3u0"),
vf.createLiteral("auto-generated!"), vf.createBNode());
connection.commit();
}
}
for (int j = 0; j < 100; j++) {
String name = dataPath + "query" + j + ".rq";
try (InputStream resourceAsStream = AbstractShaclTest.class.getClassLoader().getResourceAsStream(name)) {
if (resourceAsStream == null) {
continue;
}
ran = true;
System.out.println(name);
try (SailRepositoryConnection connection = shaclRepository.getConnection()) {
connection.begin(isolationLevel);
String query = IOUtil.readString(resourceAsStream);
connection.prepareUpdate(query).execute();
connection.commit();
} catch (RepositoryException sailException) {
if (!(sailException.getCause() instanceof ShaclSailValidationException)) {
throw sailException;
}
exception = true;
System.out.println(sailException.getMessage());
printResults(sailException);
}
} catch (IOException e) {
e.printStackTrace();
}
}
shaclRepository.shutDown();
if (ran) {
if (expectedResult == ExpectedResult.valid) {
assertFalse("Expected transaction to succeed", exception);
} else {
assertTrue("Expected transaction to fail", exception);
}
}
}
static void runTestCaseSingleTransaction(String shaclPath, String dataPath, ExpectedResult expectedResult,
IsolationLevel isolationLevel) throws Exception {
if (!dataPath.endsWith("/")) {
dataPath = dataPath + "/";
}
if (!shaclPath.endsWith("/")) {
shaclPath = shaclPath + "/";
}
SailRepository shaclRepository = getShaclSail();
Utils.loadShapeData(shaclRepository, shaclPath + "shacl.ttl");
boolean exception = false;
boolean ran = false;
try (SailRepositoryConnection shaclSailConnection = shaclRepository.getConnection()) {
shaclSailConnection.begin(isolationLevel);
for (int j = 0; j < 100; j++) {
String name = dataPath + "query" + j + ".rq";
InputStream resourceAsStream = AbstractShaclTest.class.getClassLoader().getResourceAsStream(name);
if (resourceAsStream == null) {
continue;
}
ran = true;
System.out.println(name);
try {
String query = IOUtil.readString(resourceAsStream);
shaclSailConnection.prepareUpdate(query).execute();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
shaclSailConnection.commit();
} catch (RepositoryException sailException) {
if (!(sailException.getCause() instanceof ShaclSailValidationException)) {
throw sailException;
}
exception = true;
System.out.println(sailException.getMessage());
printResults(sailException);
}
}
shaclRepository.shutDown();
if (ran) {
if (expectedResult == ExpectedResult.valid) {
assertFalse(exception);
} else {
assertTrue(exception);
}
}
}
static void runTestCaseRevalidate(String shaclPath, String dataPath, ExpectedResult expectedResult,
IsolationLevel isolationLevel) throws Exception {
if (!dataPath.endsWith("/")) {
dataPath = dataPath + "/";
}
if (!shaclPath.endsWith("/")) {
shaclPath = shaclPath + "/";
}
SailRepository shaclRepository = getShaclSail();
Utils.loadShapeData(shaclRepository, shaclPath + "shacl.ttl");
ValidationReport report;
try (SailRepositoryConnection shaclSailConnection = shaclRepository.getConnection()) {
((ShaclSail) shaclRepository.getSail()).disableValidation();
shaclSailConnection.begin(isolationLevel);
for (int j = 0; j < 100; j++) {
String name = dataPath + "query" + j + ".rq";
InputStream resourceAsStream = AbstractShaclTest.class.getClassLoader().getResourceAsStream(name);
if (resourceAsStream == null) {
continue;
}
try {
String query = IOUtil.readString(resourceAsStream);
shaclSailConnection.prepareUpdate(query).execute();
} catch (IOException e) {
e.printStackTrace();
}
}
shaclSailConnection.commit();
((ShaclSail) shaclRepository.getSail()).enableValidation();
shaclSailConnection.begin();
report = ((ShaclSailConnection) shaclSailConnection.getSailConnection()).revalidate();
shaclSailConnection.commit();
}
shaclRepository.shutDown();
if (expectedResult == ExpectedResult.valid) {
assertTrue(report.conforms());
} else {
assertFalse(report.conforms());
}
}
private static void printResults(RepositoryException sailException) {
System.out.println("\n############################################");
System.out.println("\tValidation Report\n");
ShaclSailValidationException cause = (ShaclSailValidationException) sailException.getCause();
Model validationReport = cause.validationReportAsModel();
WriterConfig writerConfig = new WriterConfig();
writerConfig.set(BasicWriterSettings.PRETTY_PRINT, true);
writerConfig.set(BasicWriterSettings.INLINE_BLANK_NODES, true);
Rio.write(validationReport, System.out, RDFFormat.TURTLE, writerConfig);
System.out.println("\n############################################");
}
String getShaclPath() {
String shaclPath = testCasePath;
if (!shaclPath.endsWith("/")) {
shaclPath = shaclPath + "/";
}
return shaclPath + "shacl.ttl";
}
enum ExpectedResult {
valid,
invalid
}
private static SailRepository getShaclSail() {
ShaclSail shaclSail = new ShaclSail(new MemoryStore());
SailRepository shaclRepository = new SailRepository(shaclSail);
shaclSail.setLogValidationPlans(true);
shaclSail.setCacheSelectNodes(true);
shaclSail.setParallelValidation(true);
shaclSail.setLogValidationViolations(true);
shaclSail.setGlobalLogValidationExecution(true);
shaclRepository.init();
return shaclRepository;
}
}
| shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/AbstractShaclTest.java | /*******************************************************************************
* Copyright (c) 2018 Eclipse RDF4J contributors.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Distribution License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*******************************************************************************/
package org.eclipse.rdf4j.sail.shacl;
import org.eclipse.rdf4j.IsolationLevel;
import org.eclipse.rdf4j.IsolationLevels;
import org.eclipse.rdf4j.common.io.IOUtil;
import org.eclipse.rdf4j.model.Model;
import org.eclipse.rdf4j.model.ValueFactory;
import org.eclipse.rdf4j.repository.RepositoryException;
import org.eclipse.rdf4j.repository.sail.SailRepository;
import org.eclipse.rdf4j.repository.sail.SailRepositoryConnection;
import org.eclipse.rdf4j.rio.RDFFormat;
import org.eclipse.rdf4j.rio.Rio;
import org.eclipse.rdf4j.sail.memory.MemoryStore;
import org.eclipse.rdf4j.sail.shacl.results.ValidationReport;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static junit.framework.TestCase.assertTrue;
import static org.junit.Assert.assertFalse;
/**
* @author Håvard Ottestad
*/
@RunWith(Parameterized.class)
abstract public class AbstractShaclTest {
// @formatter:off
// formatter doesn't understand that the trailing ) needs to be on a new line.
private static final List<String> testCasePaths = Stream.of(
"test-cases/complex/dcat",
"test-cases/complex/foaf",
"test-cases/datatype/simple",
"test-cases/datatype/targetNode",
"test-cases/datatype/targetSubjectsOf",
"test-cases/datatype/targetSubjectsOfSingle",
"test-cases/datatype/targetObjectsOf",
"test-cases/datatype/validateTarget",
"test-cases/minLength/simple",
"test-cases/maxLength/simple",
"test-cases/pattern/simple",
"test-cases/pattern/multiple",
"test-cases/languageIn/simple",
"test-cases/nodeKind/simple",
"test-cases/nodeKind/validateTarget",
"test-cases/minCount/simple",
"test-cases/minCount/targetNode",
"test-cases/maxCount/simple",
"test-cases/maxCount/targetNode",
"test-cases/or/multiple",
"test-cases/or/inheritance",
"test-cases/or/inheritance-deep",
"test-cases/or/inheritance-deep-minCountMaxCount",
"test-cases/or/inheritanceNodeShape",
"test-cases/or/datatype",
"test-cases/or/datatypeTargetNode",
"test-cases/or/minCountMaxCount",
"test-cases/or/maxCount",
"test-cases/or/minCount",
"test-cases/or/nodeKindMinLength",
"test-cases/or/implicitAnd",
"test-cases/or/datatypeDifferentPaths",
"test-cases/or/class",
"test-cases/or/classValidateTarget",
"test-cases/or/datatype2",
"test-cases/or/minCountDifferentPath",
"test-cases/or/nodeKindValidateTarget",
"test-cases/or/datatypeNodeShape",
"test-cases/minExclusive/simple",
"test-cases/minExclusive/dateVsTime",
"test-cases/maxExclusive/simple",
"test-cases/minInclusive/simple",
"test-cases/maxInclusive/simple",
"test-cases/implicitTargetClass/simple",
"test-cases/class/simple",
"test-cases/class/and",
"test-cases/class/subclass",
"test-cases/class/targetNode",
"test-cases/class/multipleClass",
"test-cases/class/validateTarget",
"test-cases/deactivated/nodeshape",
"test-cases/deactivated/or",
"test-cases/deactivated/propertyshape",
"test-cases/in/simple",
"test-cases/uniqueLang/simple",
"test-cases/propertyShapeWithTarget/simple",
"test-cases/and-or/datatypeNodeShape"
)
.distinct()
.sorted()
.collect(Collectors.toList());
// @formatter:on
final String testCasePath;
final String path;
final ExpectedResult expectedResult;
final IsolationLevel isolationLevel;
public AbstractShaclTest(String testCasePath, String path, ExpectedResult expectedResult,
IsolationLevel isolationLevel) {
this.testCasePath = testCasePath;
this.path = path;
this.expectedResult = expectedResult;
this.isolationLevel = isolationLevel;
}
@Parameterized.Parameters(name = "{2} - {1} - {3}")
public static Collection<Object[]> data() {
return getTestsToRun();
}
private static List<String> findTestCases(String testCase, String baseCase) {
List<String> ret = new ArrayList<>();
for (int i = 0; i < 100; i++) {
String path = testCase + "/" + baseCase + "/case" + i;
InputStream resourceAsStream = AbstractShaclTest.class.getClassLoader().getResourceAsStream(path);
if (resourceAsStream != null) {
ret.add(path);
try {
resourceAsStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
return ret;
}
private static Collection<Object[]> getTestsToRun() {
List<Object[]> ret = new ArrayList<>();
for (String testCasePath : testCasePaths) {
for (ExpectedResult baseCase : ExpectedResult.values()) {
findTestCases(testCasePath, baseCase.name()).forEach(path -> {
for (IsolationLevel isolationLevel : Arrays.asList(IsolationLevels.NONE, IsolationLevels.SNAPSHOT,
IsolationLevels.SERIALIZABLE)) {
Object[] temp = { testCasePath, path, baseCase, isolationLevel };
ret.add(temp);
}
});
}
}
return ret;
}
static void runTestCase(String shaclPath, String dataPath, ExpectedResult expectedResult,
IsolationLevel isolationLevel, boolean preloadWithDummyData) throws Exception {
if (!dataPath.endsWith("/")) {
dataPath = dataPath + "/";
}
if (!shaclPath.endsWith("/")) {
shaclPath = shaclPath + "/";
}
String shaclFile = shaclPath + "shacl.ttl";
System.out.println(shaclFile);
SailRepository shaclRepository = getShaclSail();
Utils.loadShapeData(shaclRepository, shaclFile);
boolean exception = false;
boolean ran = false;
if (preloadWithDummyData) {
try (SailRepositoryConnection connection = shaclRepository.getConnection()) {
connection.begin(isolationLevel);
ValueFactory vf = connection.getValueFactory();
connection.add(vf.createBNode(), vf.createIRI("http://example.com/jkhsdfiu3r2y9fjr3u0"),
vf.createLiteral("auto-generated!"), vf.createBNode());
connection.commit();
}
}
for (int j = 0; j < 100; j++) {
String name = dataPath + "query" + j + ".rq";
try (InputStream resourceAsStream = AbstractShaclTest.class.getClassLoader().getResourceAsStream(name)) {
if (resourceAsStream == null) {
continue;
}
ran = true;
System.out.println(name);
try (SailRepositoryConnection connection = shaclRepository.getConnection()) {
connection.begin(isolationLevel);
String query = IOUtil.readString(resourceAsStream);
connection.prepareUpdate(query).execute();
connection.commit();
} catch (RepositoryException sailException) {
if (!(sailException.getCause() instanceof ShaclSailValidationException)) {
throw sailException;
}
exception = true;
System.out.println(sailException.getMessage());
printResults(sailException);
}
} catch (IOException e) {
e.printStackTrace();
}
}
shaclRepository.shutDown();
if (ran) {
if (expectedResult == ExpectedResult.valid) {
assertFalse("Expected transaction to succeed", exception);
} else {
assertTrue("Expected transaction to fail", exception);
}
}
}
static void runTestCaseSingleTransaction(String shaclPath, String dataPath, ExpectedResult expectedResult,
IsolationLevel isolationLevel) throws Exception {
if (!dataPath.endsWith("/")) {
dataPath = dataPath + "/";
}
if (!shaclPath.endsWith("/")) {
shaclPath = shaclPath + "/";
}
SailRepository shaclRepository = getShaclSail();
Utils.loadShapeData(shaclRepository, shaclPath + "shacl.ttl");
boolean exception = false;
boolean ran = false;
try (SailRepositoryConnection shaclSailConnection = shaclRepository.getConnection()) {
shaclSailConnection.begin(isolationLevel);
for (int j = 0; j < 100; j++) {
String name = dataPath + "query" + j + ".rq";
InputStream resourceAsStream = AbstractShaclTest.class.getClassLoader().getResourceAsStream(name);
if (resourceAsStream == null) {
continue;
}
ran = true;
System.out.println(name);
try {
String query = IOUtil.readString(resourceAsStream);
shaclSailConnection.prepareUpdate(query).execute();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
shaclSailConnection.commit();
} catch (RepositoryException sailException) {
if (!(sailException.getCause() instanceof ShaclSailValidationException)) {
throw sailException;
}
exception = true;
System.out.println(sailException.getMessage());
printResults(sailException);
}
}
shaclRepository.shutDown();
if (ran) {
if (expectedResult == ExpectedResult.valid) {
assertFalse(exception);
} else {
assertTrue(exception);
}
}
}
static void runTestCaseRevalidate(String shaclPath, String dataPath, ExpectedResult expectedResult,
IsolationLevel isolationLevel) throws Exception {
if (!dataPath.endsWith("/")) {
dataPath = dataPath + "/";
}
if (!shaclPath.endsWith("/")) {
shaclPath = shaclPath + "/";
}
SailRepository shaclRepository = getShaclSail();
Utils.loadShapeData(shaclRepository, shaclPath + "shacl.ttl");
ValidationReport report;
try (SailRepositoryConnection shaclSailConnection = shaclRepository.getConnection()) {
((ShaclSail) shaclRepository.getSail()).disableValidation();
shaclSailConnection.begin(isolationLevel);
for (int j = 0; j < 100; j++) {
String name = dataPath + "query" + j + ".rq";
InputStream resourceAsStream = AbstractShaclTest.class.getClassLoader().getResourceAsStream(name);
if (resourceAsStream == null) {
continue;
}
try {
String query = IOUtil.readString(resourceAsStream);
shaclSailConnection.prepareUpdate(query).execute();
} catch (IOException e) {
e.printStackTrace();
}
}
shaclSailConnection.commit();
((ShaclSail) shaclRepository.getSail()).enableValidation();
shaclSailConnection.begin();
report = ((ShaclSailConnection) shaclSailConnection.getSailConnection()).revalidate();
shaclSailConnection.commit();
}
shaclRepository.shutDown();
if (expectedResult == ExpectedResult.valid) {
assertTrue(report.conforms());
} else {
assertFalse(report.conforms());
}
}
private static void printResults(RepositoryException sailException) {
System.out.println("\n############################################");
System.out.println("\tValidation Report\n");
ShaclSailValidationException cause = (ShaclSailValidationException) sailException.getCause();
Model validationReport = cause.validationReportAsModel();
Rio.write(validationReport, System.out, RDFFormat.TURTLE);
System.out.println("\n############################################");
}
String getShaclPath() {
String shaclPath = testCasePath;
if (!shaclPath.endsWith("/")) {
shaclPath = shaclPath + "/";
}
return shaclPath + "shacl.ttl";
}
enum ExpectedResult {
valid,
invalid
}
private static SailRepository getShaclSail() {
ShaclSail shaclSail = new ShaclSail(new MemoryStore());
SailRepository shaclRepository = new SailRepository(shaclSail);
shaclSail.setLogValidationPlans(true);
shaclSail.setCacheSelectNodes(true);
shaclSail.setParallelValidation(true);
shaclSail.setLogValidationViolations(true);
shaclSail.setGlobalLogValidationExecution(true);
shaclRepository.init();
return shaclRepository;
}
}
| pretty print
Signed-off-by: Håvard Ottestad <[email protected]>
| shacl/src/test/java/org/eclipse/rdf4j/sail/shacl/AbstractShaclTest.java | pretty print |
|
Java | mit | 599498cf1c63a9697e2915f0cf78d60d520542d6 | 0 | JKFennis/Kaliber | src/OpenMove9.java | import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.text.DateFormat;
import java.util.Date;
import java.text.DecimalFormat;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.ButtonGroup;
import javax.swing.JMenuBar;
import javax.swing.KeyStroke;
import javax.swing.ImageIcon;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.Timer;
import javax.swing.WindowConstants;
import javax.swing.border.Border;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import static javax.swing.UIManager.getCrossPlatformLookAndFeelClassName;
import static javax.swing.UIManager.getSystemLookAndFeelClassName;
import static javax.swing.UIManager.setLookAndFeel;
import net.miginfocom.swing.MigLayout;
public class OpenMove9 extends JFrame implements ActionListener, MouseListener {
private static final long serialVersionUID = 3186649664045658397L;
static int DELAY = 100;
public static boolean startSending = false;
public static boolean sendingMode = false;
// the currently selected device in controllerTable
Device curDevice = null;
// osc instance, will be singleton
static OSCmachine osc;
/** Creates new form OpenMOve */
public OpenMove9() {
setJMenuBar(createMenuBar());
setTitle("Kaliber 1.0.0");
initComponents();
// setup osc
osc = OSCmachine.getInstance();
ControllerTable.setModel(new ControllerTableModel());
TableColumn column = null;
for (int i = 0; i < 4; i++) {
column = ControllerTable.getColumnModel().getColumn(i);
switch (i) {
case 0:
column.setPreferredWidth(25);
column.setMaxWidth(25);
break;
case 1:
column.setPreferredWidth(225);
break;
case 2:
column.setPreferredWidth(125);
column.setMaxWidth(125);
break;
case 3:
column.setPreferredWidth(125);
column.setMaxWidth(125);
break;
}
column = null;
}
ComponentTable.setModel(new ComponentTableModel());
for (int i = 0; i < 6; i++) {
column = ComponentTable.getColumnModel().getColumn(i);
switch (i) {
case 0:
column.setPreferredWidth(25);
column.setMaxWidth(25);
break;
case 1:
column.setPreferredWidth(225);
break;
case 2:
column.setPreferredWidth(62);
column.setMaxWidth(62);
break;
case 3:
column.setPreferredWidth(62);
column.setMaxWidth(62);
break;
case 4:
column.setPreferredWidth(63);
column.setMaxWidth(63);
break;
case 5:
column.setPreferredWidth(63);
column.setMaxWidth(63);
break;
}
}
ControllerTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
ComponentTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// TODO: fix actionlisteners
/*
* Register Action and MouseListeners
*/
startButton.addActionListener(this);
stopButton.addActionListener(this);
openButton.addActionListener(this);
saveButton.addActionListener(this);
newButton.addActionListener(this);
modeButton.addActionListener(this);
startButton.addMouseListener(this);
stopButton.addMouseListener(this);
openButton.addMouseListener(this);
saveButton.addMouseListener(this);
newButton.addMouseListener(this);
modeButton.addMouseListener(this);
outputPort.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
int start = 0;
int end = outputPort.getText().length();
outputPort.setSelectionStart(start);
outputPort.setSelectionEnd(end);
}
public void focusLost(FocusEvent e) {
String newOutPort = outputPort.getText();
if (outputPort.getText().length() != 0)
try {
osc.setOutPort(newOutPort);
} catch (NumberFormatException ex) {
}
}
});
startPolling();
/*
* Listener that calls function valueChanged each time a different
* controller is selected Valuechanged() updates the tablemodel of
* componentTable
*/
ControllerTable.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting())
return;
ListSelectionModel lsm = ControllerTable
.getSelectionModel();
int fi = e.getFirstIndex();
int li = e.getLastIndex();
int index = lsm.isSelectedIndex(fi) ? fi : li;
try {
curDevice = Device.getDevice(index);
/*
* Check if abstract object Device is of subclass
* controller or move
*/
if (curDevice instanceof MoveController) {
ComponentTable
.setModel(new MoveComponentTableModel(
curDevice));
} else if (curDevice instanceof JInputDevice) {
ComponentTable
.setModel(new ComponentTableModel(
curDevice));
}
TableColumn column = null;
for (int i = 0; i < 6; i++) {
column = ComponentTable.getColumnModel()
.getColumn(i);
switch (i) {
case 0:
column.setPreferredWidth(25);
column.setMaxWidth(25);
break;
case 1:
column.setPreferredWidth(225);
break;
case 2:
column.setPreferredWidth(62);
column.setMaxWidth(62);
break;
case 3:
column.setPreferredWidth(62);
column.setMaxWidth(62);
break;
case 4:
column.setPreferredWidth(63);
column.setMaxWidth(63);
break;
case 5:
column.setPreferredWidth(63);
column.setMaxWidth(63);
break;
}
column = null;
}
} catch (IndexOutOfBoundsException ex) {
printConsole("Failed to initialize GUI (tablemodel)", false);
}
}
});
}
// TODO: fix listener functions
public void actionPerformed(ActionEvent e) {
if (e.getSource() == startButton) {
if (!startSending) {
startSending = true;
startButton
.setIcon(new ImageIcon(startSelected));
}
}
if (e.getSource() == stopButton) {
if (startSending) {
startSending = false;
startButton.setIcon(new ImageIcon(start));
}
}
if (e.getSource() == openButton || e.getSource() == Open) {
theChooser.setDialogType(JFileChooser.OPEN_DIALOG);
theChooser.showOpenDialog(getParent());
}
if (e.getSource() == saveButton || e.getSource() == Save) {
theChooser.setDialogType(JFileChooser.SAVE_DIALOG);
theChooser.showSaveDialog(getParent());
}
if (e.getSource() == newButton || e.getSource() == New) {
for (Device d : Device.Devices) {
d.initMinValues(d.getNumComponents());
d.initMaxValues(d.getNumComponents());
d.initPlugNames(d.getNumComponents());
d.setIsSelected(false);
for (int row = 0; row < ControllerTable.getRowCount(); row++) {
if (d.getIsSelected())
ControllerTable.getModel().setValueAt(false, row, 0);
}
for (int c = 0; c < d.getNumComponents(); c++) {
d.setcompSelected(c, false);
}
}
ControllerTable.repaint();
}
if (e.getSource() == modeButton || e.getSource() == change
|| e.getSource() == cont) {
if (sendingMode) {
sendingMode = false;
modeButton.setIcon(new ImageIcon(changeImg));
modeButton.setPressedIcon(new ImageIcon(
changeSelected));
modeButton.setRolloverIcon(new ImageIcon(
changeRollOver));
actionLabel.setText("Send On Action");
change.setSelected(true);
} else if (!sendingMode) {
sendingMode = true;
modeButton.setIcon(new ImageIcon(contImg));
modeButton.setPressedIcon(new ImageIcon(
contSelected));
modeButton.setRolloverIcon(new ImageIcon(
contRollOver));
actionLabel.setText("Send Continuous");
cont.setSelected(true);
}
}
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
if (evt.getSource() == startButton) {
actionLabel.setText("Start");
}
if (evt.getSource() == stopButton) {
actionLabel.setText("Stop");
}
if (evt.getSource() == openButton) {
actionLabel.setText("Open");
}
if (evt.getSource() == saveButton) {
actionLabel.setText("Save");
}
if (evt.getSource() == newButton) {
actionLabel.setText("New");
}
if (evt.getSource() == modeButton) {
if (sendingMode)
actionLabel.setText("Send Continuous");
if (!sendingMode)
actionLabel.setText("Send On Action");
}
}
public void mouseExited(java.awt.event.MouseEvent evt) {
actionLabel.setText("");
}
public void mouseClicked(java.awt.event.MouseEvent evt) {/* not implemented */
}
public void mousePressed(MouseEvent e) {/* not implemented */
}
public void mouseReleased(MouseEvent e) {/* not implemented */
}
public JMenuBar createMenuBar() {
// Create the menu bar.
menuBar = new JMenuBar();
// Build the first menu.
menu = new JMenu("File");
menu.getAccessibleContext().setAccessibleDescription(
"The only menu in this program that has menu items");
menuBar.add(menu);
// a group of JMenuItems
New = new JMenuItem("New", KeyEvent.VK_N);
New.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,
ActionEvent.META_MASK));
New.getAccessibleContext().setAccessibleDescription(
"This doesn't really do anything");
menu.add(New);
New.addActionListener(this);
Open = new JMenuItem("Open", KeyEvent.VK_O);
Open.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
ActionEvent.META_MASK));
Open.getAccessibleContext().setAccessibleDescription(
"This doesn't really do anything");
menu.add(Open);
Open.addActionListener(this);
Save = new JMenuItem("Save", KeyEvent.VK_S);
Save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
ActionEvent.META_MASK));
Save.getAccessibleContext().setAccessibleDescription(
"This doesn't really do anything");
menu.add(Save);
Save.addActionListener(this);
menu = new JMenu("Mode");
menu.getAccessibleContext().setAccessibleDescription(
"The only menu in this program that has menu items");
menuBar.add(menu);
// a group of radio button menu items
ButtonGroup group = new ButtonGroup();
change = new JRadioButtonMenuItem("On Change");
change.setSelected(true);
group.add(change);
menu.add(change);
cont = new JRadioButtonMenuItem("Continuous");
group.add(cont);
menu.add(cont);
change.addActionListener(this);
cont.addActionListener(this);
return menuBar;
}
public void startPolling() {
(new Timer(DELAY, new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Update the table to see 'live' values
ComponentTable.repaint();
if (Device.getNumDevices() >= 1) {
for (Device d : Device.Devices)
d.poll();
console.setCaretPosition(console.getDocument().getLength());
}
}
})).start();
}
public static void printConsole(String event, boolean directionOut) {
timeStamp = new Date();
console.append(" ");
console.append("[" + DateFormat.getTimeInstance().format(timeStamp)
+ "]");
console.append(" ");
if (directionOut)
console.append(">");
if (!directionOut)
console.append("<");
console.append(" ");
console.append(event);
console.append("\n");
}
/*
* Initializing GUI components
*/
private void initComponents() {
controllerScrollPanel = new JScrollPane();
ControllerTable = new JTable();
componentScrollPanel = new JScrollPane();
ComponentTable = new JTable();
console = new JTextArea();
console.setEditable(false);
console.setBackground(Color.BLACK);
console.setFont(new Font("Sans Serif", Font.PLAIN, 11));
console.setForeground(Color.WHITE);
console.setLineWrap(true);
consolePane = new JScrollPane(console);
SplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, true,
componentScrollPanel, consolePane);
Border border = BorderFactory.createEmptyBorder(0, 0, 0, 0);
controllerScrollPanel.setBorder(border);
componentScrollPanel.setBorder(border);
consolePane.setBorder(border);
setBackground(new Color(170, 170, 170));
SplitPane.setOpaque(true);
SplitPane.setBorder(null);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setMinimumSize(new java.awt.Dimension(200, 300));
// setPreferredSize(new java.awt.Dimension(500, 400));
// setMaximumSize(new java.awt.Dimension(500, 800));
ControllerTable.setAutoCreateRowSorter(false);
ControllerTable.setModel(new DefaultTableModel(new Object[][] {
{ null, null, null, null }, { null, null, null, null },
{ null, null, null, null }, { null, null, null, null } },
new String[] { "Title 1", "Title 2", "Title 3", "Title 4" }));
// ControllerTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
controllerScrollPanel.setViewportView(ControllerTable);
ComponentTable.setModel(new DefaultTableModel(new Object[][] {
{ null, null, null, null }, { null, null, null, null },
{ null, null, null, null }, { null, null, null, null } },
new String[] { "Title 1", "Title 2", "Title 3", "Title 4" }));
// ComponentTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
componentScrollPanel.setViewportView(ComponentTable);
try {
// Eclispe: images must reside in package folder
start = javax.imageio.ImageIO.read(ClassLoader
.getSystemResource("JButtons_start.png"));
startRollOver = javax.imageio.ImageIO.read(ClassLoader
.getSystemResource("JButtons_start_rollover.png"));
startSelected = javax.imageio.ImageIO.read(ClassLoader
.getSystemResource("JButtons_start_selected.png"));
stop = javax.imageio.ImageIO.read(ClassLoader
.getSystemResource("JButtons_stop.png"));
stopRollOver = javax.imageio.ImageIO.read(ClassLoader
.getSystemResource("JButtons_stop_rollover.png"));
stopSelected = javax.imageio.ImageIO.read(ClassLoader
.getSystemResource("JButtons_stop_selected.png"));
saveImg = javax.imageio.ImageIO.read(ClassLoader
.getSystemResource("JButtons_save.png"));
saveRollOver = javax.imageio.ImageIO.read(ClassLoader
.getSystemResource("JButtons_save_rollover.png"));
saveSelected = javax.imageio.ImageIO.read(ClassLoader
.getSystemResource("JButtons_save_selected.png"));
openImg = javax.imageio.ImageIO.read(ClassLoader
.getSystemResource("JButtons_open.png"));
openRollOver = javax.imageio.ImageIO.read(ClassLoader
.getSystemResource("JButtons_open_rollover.png"));
openSelected = javax.imageio.ImageIO.read(ClassLoader
.getSystemResource("JButtons_open_selected.png"));
newImg = javax.imageio.ImageIO.read(ClassLoader
.getSystemResource("JButtons_new.png"));
newRollOver = javax.imageio.ImageIO.read(ClassLoader
.getSystemResource("JButtons_new_rollover.png"));
newSelected = javax.imageio.ImageIO.read(ClassLoader
.getSystemResource("JButtons_new_selected.png"));
changeImg = javax.imageio.ImageIO.read(ClassLoader
.getSystemResource("JButtons_onchange.png"));
changeRollOver = javax.imageio.ImageIO.read(ClassLoader
.getSystemResource("JButtons_onchange_rollover.png"));
changeSelected = javax.imageio.ImageIO.read(ClassLoader
.getSystemResource("JButtons_onchange_selected.png"));
contImg = javax.imageio.ImageIO.read(ClassLoader
.getSystemResource("JButtons_continuous.png"));
contRollOver = javax.imageio.ImageIO.read(ClassLoader
.getSystemResource("JButtons_continuous_rollover.png"));
contSelected = javax.imageio.ImageIO.read(ClassLoader
.getSystemResource("JButtons_continuous_selected.png"));
// Eclispe: works if placed in root project folder
// image = javax.imageio.ImageIO.read(new
// java.io.File("JButtons_start.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// javax.swing.ImageIcon icon = new javax.swing.ImageIcon(start);
startButton = new ImageButton(new ImageIcon(start));
// startButton = new ImageButton(new ImageIcon("JButtons_start.png"));
stopButton = new ImageButton(new ImageIcon(stop));
openButton = new ImageButton(new ImageIcon(openImg));
saveButton = new ImageButton(new ImageIcon(saveImg));
newButton = new ImageButton(new ImageIcon(newImg));
modeButton = new ImageButton(new ImageIcon(changeImg));
actionLabel = new JLabel("");
actionLabel.setFont(new Font("Sans Serif", Font.PLAIN, 12));
startButton.setPressedIcon(new ImageIcon(startSelected));
startButton
.setRolloverIcon(new ImageIcon(startRollOver));
startButton
.setSelectedIcon(new ImageIcon(startRollOver));
startButton
.setDisabledIcon(new ImageIcon(startRollOver));
stopButton.setPressedIcon(new ImageIcon(stopSelected));
stopButton.setRolloverIcon(new ImageIcon(stopRollOver));
stopButton.setSelectedIcon(new ImageIcon(stopRollOver));
stopButton.setDisabledIcon(new ImageIcon(stopRollOver));
openButton.setPressedIcon(new ImageIcon(openSelected));
openButton.setRolloverIcon(new ImageIcon(openRollOver));
openButton.setSelectedIcon(new ImageIcon(openRollOver));
openButton.setDisabledIcon(new ImageIcon(openRollOver));
saveButton.setPressedIcon(new ImageIcon(saveSelected));
saveButton.setRolloverIcon(new ImageIcon(saveRollOver));
saveButton.setSelectedIcon(new ImageIcon(saveRollOver));
saveButton.setDisabledIcon(new ImageIcon(saveRollOver));
newButton.setPressedIcon(new ImageIcon(newSelected));
newButton.setRolloverIcon(new ImageIcon(newRollOver));
newButton.setSelectedIcon(new ImageIcon(newRollOver));
newButton.setDisabledIcon(new ImageIcon(newRollOver));
modeButton.setPressedIcon(new ImageIcon(
changeSelected));
modeButton.setRolloverIcon(new ImageIcon(
changeRollOver));
statusbar = new JPanel();
JLabel statusLabel = new JLabel(
"OSC Address 127.0.0.1 | Listening @ port 8000");
statusLabel.setHorizontalAlignment(SwingConstants.CENTER);
statusLabel.setFont(new Font("Sans Serif", Font.PLAIN, 11));
statusbar.add(statusLabel);
outPortLabel = new JLabel(" Output port");
outPortLabel.setHorizontalAlignment(SwingConstants.CENTER);
outPortLabel.setFont(new Font("Sans Serif", Font.PLAIN, 11));
outputPort = new JFormattedTextField(new DecimalFormat("##"));
outputPort.setText("12000");
outputPort.setHorizontalAlignment(JTextField.CENTER);
outputPort.setColumns(4);
// The layout has 1 extra column, allowing easy spacing between elements
getContentPane().setLayout(
new MigLayout("insets 0 0 0 0",
"0[]-10[]-10[]5[]-8[]-8[][]push[][]0",
"0[]0[]0[grow]0[]0"));
// Row 0
getContentPane().add(startButton, "cell 0 0");
getContentPane().add(stopButton, "cell 1 0");
getContentPane().add(modeButton, "cell 2 0");
getContentPane().add(newButton, "cell 3 0");
getContentPane().add(openButton, "cell 4 0");
getContentPane().add(saveButton, "cell 5 0");
getContentPane().add(actionLabel, "cell 6 0");
getContentPane().add(outPortLabel, "cell 7 0");
getContentPane().add(outputPort, "cell 8 0, gapright 5");
// Row 2
// controllerScrollPanel.setPreferredSize(new
// Dimension(WIDTH,(Device.Devices.size()*50)));
getContentPane().add(controllerScrollPanel,
"cell 0 1 9 1, grow, height 120:120:120");
// Row 3
// getContentPane().add(componentScrollPanel,
// "cell 0 2 9 1, width 200:500:500, height 0:600:1600");
// Row 4
getContentPane().add(SplitPane, "cell 0 2 9 0, grow");
// Row 5
getContentPane().add(statusbar, "cell 0 3 9 1, grow, height 24:24:24");
// SplitPane.setDividerLocation(0.3);
SplitPane.setResizeWeight(1);
theChooser = new JFileChooser();
FileNameExtensionFilter xmlfilter = new FileNameExtensionFilter(
"xml files (*.xml)", "xml");
theChooser.setFileFilter(xmlfilter);
theChooser.addActionListener(new AbstractAction() {
private static final long serialVersionUID = 2733533319904047170L;
public void actionPerformed(ActionEvent evt) {
JFileChooser chooser = (JFileChooser) evt.getSource();
// Ok was clicked
if (JFileChooser.APPROVE_SELECTION.equals(evt
.getActionCommand())) {
if (chooser.getDialogType() == 0) {
File theFile = chooser.getSelectedFile();
openPreset(theFile);
} else if (chooser.getDialogType() == 1) {
File theFile = chooser.getSelectedFile();
String nameOfFile = "";
nameOfFile = theFile.getPath();
savePreset(theFile, nameOfFile);
}
} else if (JFileChooser.CANCEL_SELECTION.equals(evt
.getActionCommand())) {
// Cancel was clicked
printConsole("Canceled", false);
}
}
});
pack();
}
protected void savePreset(File theFile, String FileName) {
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
// root elements
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("controllerList");
doc.appendChild(rootElement);
for (Device d : Device.Devices) {
// controller elements
Element XMLDevice = doc.createElement("Device");
rootElement.appendChild(XMLDevice);
// set controller id
Attr deviceType = doc.createAttribute("id");
deviceType.setValue(d.getName()
+ Integer.toString(d.getDeviceIndex()).trim());
XMLDevice.setAttributeNode(deviceType);
// pass in number of components
Attr numofComp = doc.createAttribute("NoC");
numofComp.setValue(Integer.toString(d.getNumComponents()));
XMLDevice.setAttributeNode(numofComp);
// save if controller is selected
Attr selected = doc.createAttribute("selected");
selected.setValue(new Boolean(d.getIsSelected()).toString()
.trim());
XMLDevice.setAttributeNode(selected);
for (int i = 0; i < d.getNumComponents(); i++) {
// isComponent selected elements
Element compSelected = doc.createElement("compSelected");
compSelected.appendChild(doc.createTextNode(new Boolean(d
.getSelectedComponent(i)).toString().trim()));
XMLDevice.appendChild(compSelected);
// minVal elements
Element minVal = doc.createElement("minVal");
minVal.appendChild(doc.createTextNode(Float.toString(d
.getMinValue(i))));
XMLDevice.appendChild(minVal);
// maxVal elements
Element maxVal = doc.createElement("maxVal");
maxVal.appendChild(doc.createTextNode(Float.toString(d
.getMaxValue(i))));
XMLDevice.appendChild(maxVal);
// plug elements
Element plug = doc.createElement("plug");
plug.appendChild(doc.createTextNode(d.getPlugName(i)));
XMLDevice.appendChild(plug);
}
}
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory
.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(FileName));
if (FileName.endsWith(".xml")) {
transformer.transform(source, result);
} else {
result = new StreamResult(new File(FileName + ".xml"));
transformer.transform(source, result);
}
printConsole("File: " + FileName + " saved!", true);
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
}
}
protected void openPreset(File theFile) {
try {
File fXmlFile = theFile;
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList DeviceList = doc.getElementsByTagName("Device");
for (int temp = 0; temp < DeviceList.getLength(); temp++) {
Node xmlDevice = DeviceList.item(temp);
if (xmlDevice.getNodeType() == Node.ELEMENT_NODE) {
for (Device d : Device.Devices) {
Element eElement = (Element) xmlDevice;
String deviceName = eElement.getAttribute("id").trim();
int numOfComponents = Integer.parseInt(eElement
.getAttribute("NoC").trim());
boolean isSelected = Boolean.parseBoolean(eElement
.getAttribute("selected").trim());
if (deviceName.equals(d.getName()
+ Integer.toString(d.getDeviceIndex()).trim())) {
d.setIsSelected(isSelected);
for (int i = 0; i < numOfComponents; i++) {
boolean compSelected = getBooleanValue(
"compSelected", eElement, i);
d.setcompSelected(i, compSelected);
float minval = getFloatValue("minVal",
eElement, i);
d.setMinValue(i, minval);
float maxval = getFloatValue("maxVal",
eElement, i);
d.setMaxValue(i, maxval);
String plug = getPlugValue("plug", eElement, i);
d.setPlugName(i, plug);
}
}
}
}
}
printConsole("File: " + theFile.getName() + " opened", false);
} catch (Exception e) {
e.printStackTrace();
}
}
private static boolean getBooleanValue(String sTag, Element eElement, int i) {
NodeList nlList = eElement.getElementsByTagName(sTag).item(i)
.getChildNodes();
Node nValue = (Node) nlList.item(0);
return Boolean.parseBoolean(nValue.getNodeValue().trim());
}
private static int getIntValue(String sTag, Element eElement, int i) {
NodeList nlList = eElement.getElementsByTagName(sTag).item(i)
.getChildNodes();
Node nValue = (Node) nlList.item(0);
return Integer.parseInt(nValue.getNodeValue().trim());
}
private static float getFloatValue(String sTag, Element eElement, int i) {
NodeList nlList = eElement.getElementsByTagName(sTag).item(i)
.getChildNodes();
Node nValue = (Node) nlList.item(0);
return Float.parseFloat(nValue.getNodeValue().trim());
}
private static String getPlugValue(String sTag, Element eElement, int i) {
NodeList nlList = eElement.getElementsByTagName(sTag).item(i)
.getChildNodes();
Node nValue = (Node) nlList.item(0);
return nValue.getNodeValue().trim();
}
private static boolean isPlatform(String platform) {
return System.getProperties().getProperty(OS_NAME).toLowerCase()
.contains(platform.toLowerCase());
}
private static String getLookAndFeel() {
// if (true) return "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel";
// Linux has issues with the gtk look and feel themes.
if (isPlatform(LINUX))
return getCrossPlatformLookAndFeelClassName();
return getSystemLookAndFeelClassName();
}
public static void main(String args[]) {
try {
if (isPlatform(MAC_OS_X)) {
System.setProperty("apple.awt.rendering", "true");
System.setProperty("apple.awt.brushMetalLook", "true");
System.setProperty("apple.laf.useScreenMenuBar", "true");
System.setProperty(
"apple.awt.window.position.forceSafeCreation", "true");
System.setProperty("apple.laf.useScreenMenuBar", "true");
}
setLookAndFeel(getLookAndFeel());
// make sure we have nice window decorations.
setDefaultLookAndFeelDecorated(true);
} catch (Exception ex) {
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new OpenMove9().setVisible(true);
}
});
} // End of Main()
// Variables declaration
private JSplitPane ControllerSplitPane, SplitPane;
private JTable ControllerTable, ComponentTable;
private JScrollPane controllerScrollPanel, componentScrollPanel,
consolePane;
private JFileChooser theChooser;
private JFormattedTextField outputPort;
private JLabel outPortLabel, actionLabel;
private JPanel statusbar;
private static JTextArea console;
private ImageButton startButton, stopButton, newButton, openButton,
saveButton, modeButton;
private JMenuBar menuBar;
private JMenu menu;
private JMenuItem New, Open, Save;
private JRadioButtonMenuItem change, cont;
private static Date timeStamp;
private BufferedImage start, startRollOver, startSelected, stop,
stopRollOver, stopSelected, contImg, contRollOver, contSelected,
changeImg, changeRollOver, changeSelected, openImg, openRollOver,
openSelected, saveImg, saveRollOver, saveSelected, newImg, newRollOver, newSelected;
private static final String OS_NAME = "os.name";
private static final String MAC_OS_X = "Mac OS X";
private static final String LINUX = "Linux";
// End of variables declaration
} // End of openMove class
| old main class deleted
| src/OpenMove9.java | old main class deleted |
||
Java | isc | b97b2fc418490b96eb1c1b10bfbe9ecbdf2a8952 | 0 | meyerdg/ingress-intel-total-conversion,MarkTraceur/ingress-intel-total-conversion,iitc-project/ingress-intel-total-conversion,ruharen/ingress-intel-total-conversion,MarkTraceur/ingress-intel-total-conversion,adostes/ingress-intel-total-conversion,hayeswise/ingress-intel-total-conversion,Hubertzhang/ingress-intel-total-conversion,kyotoalgo/ingress-intel-total-conversion,insane210/ingress-intel-total-conversion,ZasoGD/ingress-intel-total-conversion,pleasantone/ingress-intel-total-conversion,manierim/ingress-intel-total-conversion,sndirsch/ingress-intel-total-conversion,FLamparski/ingress-intel-total-conversion,jonatkins/ingress-intel-total-conversion,fkloft/ingress-intel-total-conversion,SpamapS/ingress-intel-total-conversion,Hubertzhang/ingress-intel-total-conversion,Yossi/ingress-intel-total-conversion,kdawes/ingress-intel-total-conversion,tony2001/ingress-intel-total-conversion,nhamer/ingress-intel-total-conversion,michaeldever/ingress-intel-total-conversion,pfsmorigo/ingress-intel-total-conversion,adostes/ingress-intel-total-conversion,kdawes/ingress-intel-total-conversion,McBen/ingress-intel-total-conversion,pfsmorigo/ingress-intel-total-conversion,Yossi/ingress-intel-total-conversion,kyotoalgo/ingress-intel-total-conversion,meyerdg/ingress-intel-total-conversion,FLamparski/ingress-intel-total-conversion,insane210/ingress-intel-total-conversion,adostes/ingress-intel-total-conversion,ruharen/ingress-intel-total-conversion,michmerr/ingress-intel-total-conversion,mutongx/ingress-intel-total-conversion,3ch01c/ingress-intel-total-conversion,pfsmorigo/ingress-intel-total-conversion,Yossi/ingress-intel-total-conversion,Galfinite/ingress-intel-total-conversion,Hubertzhang/ingress-intel-total-conversion,manierim/ingress-intel-total-conversion,MNoelJones/ingress-intel-total-conversion,michmerr/ingress-intel-total-conversion,nhamer/ingress-intel-total-conversion,adostes/ingress-intel-total-conversion,kyotoalgo/ingress-intel-total-conversion,imsaguy/ingress-intel-total-conversion,kdawes/ingress-intel-total-conversion,hayeswise/ingress-intel-total-conversion,rspielmann/ingress-intel-total-conversion,rspielmann/ingress-intel-total-conversion,manierim/ingress-intel-total-conversion,nexushoratio/ingress-intel-total-conversion,nikolawannabe/ingress-intel-total-conversion,dwimberger/ingress-intel-total-conversion,MarkTraceur/ingress-intel-total-conversion,rspielmann/ingress-intel-total-conversion,insane210/ingress-intel-total-conversion,ZasoGD/ingress-intel-total-conversion,SteelToad/ingress-intel-total-conversion,McBen/ingress-intel-total-conversion,michmerr/ingress-intel-total-conversion,MarkTraceur/ingress-intel-total-conversion,iitc-project/ingress-intel-total-conversion,kottt/ingress-intel-total-conversion,sndirsch/ingress-intel-total-conversion,jonatkins/ingress-intel-total-conversion,jarridgraham/ingress-intel-total-conversion,jarridgraham/ingress-intel-total-conversion,ruharen/ingress-intel-total-conversion,rspielmann/ingress-intel-total-conversion,insane210/ingress-intel-total-conversion,Hubertzhang/ingress-intel-total-conversion,dwandw/ingress-intel-total-conversion,kyotoalgo/ingress-intel-total-conversion,pleasantone/ingress-intel-total-conversion,pfsmorigo/ingress-intel-total-conversion,kottt/ingress-intel-total-conversion,jarridgraham/ingress-intel-total-conversion,imsaguy/ingress-intel-total-conversion,pleasantone/ingress-intel-total-conversion,sndirsch/ingress-intel-total-conversion,insane210/ingress-intel-total-conversion,dwandw/ingress-intel-total-conversion,tony2001/ingress-intel-total-conversion,nikolawannabe/ingress-intel-total-conversion,McBen/ingress-intel-total-conversion,SteelToad/ingress-intel-total-conversion,tony2001/ingress-intel-total-conversion,nikolawannabe/ingress-intel-total-conversion,MNoelJones/ingress-intel-total-conversion,Hubertzhang/ingress-intel-total-conversion,ZasoGD/ingress-intel-total-conversion,ZasoGD/ingress-intel-total-conversion,michmerr/ingress-intel-total-conversion,tony2001/ingress-intel-total-conversion,MarkTraceur/ingress-intel-total-conversion,fkloft/ingress-intel-total-conversion,pleasantone/ingress-intel-total-conversion,3ch01c/ingress-intel-total-conversion,ruharen/ingress-intel-total-conversion,jonatkins/ingress-intel-total-conversion,dwimberger/ingress-intel-total-conversion,3ch01c/ingress-intel-total-conversion,imsaguy/ingress-intel-total-conversion,michmerr/ingress-intel-total-conversion,fkloft/ingress-intel-total-conversion,pleasantone/ingress-intel-total-conversion,sgtwilko/ingress-intel-total-conversion,Hubertzhang/ingress-intel-total-conversion,jonatkins/ingress-intel-total-conversion,nhamer/ingress-intel-total-conversion,fkloft/ingress-intel-total-conversion,Galfinite/ingress-intel-total-conversion,MNoelJones/ingress-intel-total-conversion,hayeswise/ingress-intel-total-conversion,nhamer/ingress-intel-total-conversion,ZasoGD/ingress-intel-total-conversion,jonatkins/ingress-intel-total-conversion,dwimberger/ingress-intel-total-conversion,Yossi/ingress-intel-total-conversion,McBen/ingress-intel-total-conversion,3ch01c/ingress-intel-total-conversion,nexushoratio/ingress-intel-total-conversion,mutongx/ingress-intel-total-conversion,michaeldever/ingress-intel-total-conversion,iitc-project/ingress-intel-total-conversion,michaeldever/ingress-intel-total-conversion,SpamapS/ingress-intel-total-conversion,adostes/ingress-intel-total-conversion,pfsmorigo/ingress-intel-total-conversion,michaeldever/ingress-intel-total-conversion,sndirsch/ingress-intel-total-conversion,Hubertzhang/ingress-intel-total-conversion,nexushoratio/ingress-intel-total-conversion,Galfinite/ingress-intel-total-conversion,tony2001/ingress-intel-total-conversion,3ch01c/ingress-intel-total-conversion,kottt/ingress-intel-total-conversion,FLamparski/ingress-intel-total-conversion,SteelToad/ingress-intel-total-conversion,mutongx/ingress-intel-total-conversion,sgtwilko/ingress-intel-total-conversion,sndirsch/ingress-intel-total-conversion,SpamapS/ingress-intel-total-conversion,michaeldever/ingress-intel-total-conversion,michmerr/ingress-intel-total-conversion,manierim/ingress-intel-total-conversion,sgtwilko/ingress-intel-total-conversion,fkloft/ingress-intel-total-conversion,MNoelJones/ingress-intel-total-conversion,sgtwilko/ingress-intel-total-conversion,nexushoratio/ingress-intel-total-conversion,nexushoratio/ingress-intel-total-conversion,dwandw/ingress-intel-total-conversion,jarridgraham/ingress-intel-total-conversion,Yossi/ingress-intel-total-conversion,nikolawannabe/ingress-intel-total-conversion,nikolawannabe/ingress-intel-total-conversion,dwandw/ingress-intel-total-conversion,iitc-project/ingress-intel-total-conversion,iitc-project/ingress-intel-total-conversion,iitc-project/ingress-intel-total-conversion,McBen/ingress-intel-total-conversion,tony2001/ingress-intel-total-conversion,hayeswise/ingress-intel-total-conversion,MNoelJones/ingress-intel-total-conversion,meyerdg/ingress-intel-total-conversion,SpamapS/ingress-intel-total-conversion,Yossi/ingress-intel-total-conversion,3ch01c/ingress-intel-total-conversion,SteelToad/ingress-intel-total-conversion,mutongx/ingress-intel-total-conversion,rspielmann/ingress-intel-total-conversion,Galfinite/ingress-intel-total-conversion,imsaguy/ingress-intel-total-conversion,SpamapS/ingress-intel-total-conversion,meyerdg/ingress-intel-total-conversion,kyotoalgo/ingress-intel-total-conversion,ruharen/ingress-intel-total-conversion,rspielmann/ingress-intel-total-conversion,nhamer/ingress-intel-total-conversion,SpamapS/ingress-intel-total-conversion,hayeswise/ingress-intel-total-conversion,nexushoratio/ingress-intel-total-conversion,meyerdg/ingress-intel-total-conversion,dwandw/ingress-intel-total-conversion,kdawes/ingress-intel-total-conversion,manierim/ingress-intel-total-conversion,kottt/ingress-intel-total-conversion,FLamparski/ingress-intel-total-conversion,adostes/ingress-intel-total-conversion,nikolawannabe/ingress-intel-total-conversion,pfsmorigo/ingress-intel-total-conversion,SteelToad/ingress-intel-total-conversion,kdawes/ingress-intel-total-conversion,dwimberger/ingress-intel-total-conversion,michaeldever/ingress-intel-total-conversion,kottt/ingress-intel-total-conversion,mutongx/ingress-intel-total-conversion,sgtwilko/ingress-intel-total-conversion,jonatkins/ingress-intel-total-conversion,dwandw/ingress-intel-total-conversion,MNoelJones/ingress-intel-total-conversion,MarkTraceur/ingress-intel-total-conversion,sgtwilko/ingress-intel-total-conversion,SteelToad/ingress-intel-total-conversion,meyerdg/ingress-intel-total-conversion,Hubertzhang/ingress-intel-total-conversion,kottt/ingress-intel-total-conversion,dwimberger/ingress-intel-total-conversion,kdawes/ingress-intel-total-conversion,pleasantone/ingress-intel-total-conversion,FLamparski/ingress-intel-total-conversion,imsaguy/ingress-intel-total-conversion,jarridgraham/ingress-intel-total-conversion,mutongx/ingress-intel-total-conversion,jarridgraham/ingress-intel-total-conversion,nhamer/ingress-intel-total-conversion,fkloft/ingress-intel-total-conversion,dwimberger/ingress-intel-total-conversion,insane210/ingress-intel-total-conversion,imsaguy/ingress-intel-total-conversion,ZasoGD/ingress-intel-total-conversion,Galfinite/ingress-intel-total-conversion,Galfinite/ingress-intel-total-conversion,hayeswise/ingress-intel-total-conversion,kyotoalgo/ingress-intel-total-conversion,dwimberger/ingress-intel-total-conversion,FLamparski/ingress-intel-total-conversion,manierim/ingress-intel-total-conversion,ruharen/ingress-intel-total-conversion | package com.cradle.iitc_mobile;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.preference.DialogPreference;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.AttributeSet;
import android.widget.TextView;
public class IITC_AboutDialogPreference extends DialogPreference{
private Context context;
public IITC_AboutDialogPreference(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
}
/*
* start a little about-dialog
* srsly...I found no better way for clickable links in a TextView then
* using Html.fromHtml...Linkify is just broken and does not understand
* html href tags...so let's tag the @string/about_msg with CDATA and
* use Html.fromHtml(...) for clickable hrefs with tags.
*/
@Override
protected void onPrepareDialogBuilder(Builder builder) {
final TextView message = new TextView(context);
String about_msg = context.getText(R.string.pref_about_msg).toString();
message.setText(Html.fromHtml(about_msg));
message.setMovementMethod(LinkMovementMethod.getInstance());
builder.setView(message)
.setTitle(R.string.about)
.setIcon(R.drawable.ic_stat_about)
.setNeutralButton(R.string.close, new OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
super.onPrepareDialogBuilder(builder);
}
}
| mobile/src/com/cradle/iitc_mobile/IITC_AboutDialogPreference.java | package com.cradle.iitc_mobile;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.preference.DialogPreference;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.AttributeSet;
import android.widget.TextView;
public class IITC_AboutDialogPreference extends DialogPreference{
private Context context;
public IITC_AboutDialogPreference(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
}
/*
* start a little about-dialog
* srsly...I found no better way for clickable links in a TextView then
* using Html.fromHtml...Linkify ist just broken and does not understand
* html href tags...so let's tag the @string/about_msg with CDATA and
* use Html.fromHtml(...) for clickable hrefs with tags.
*/
@Override
protected void onPrepareDialogBuilder(Builder builder) {
final TextView message = new TextView(context);
String about_msg = context.getText(R.string.pref_about_msg).toString();
message.setText(Html.fromHtml(about_msg));
message.setMovementMethod(LinkMovementMethod.getInstance());
builder.setView(message)
.setTitle(R.string.about)
.setIcon(R.drawable.ic_stat_about)
.setNeutralButton(R.string.close, new OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
super.onPrepareDialogBuilder(builder);
}
}
| mobile: fix typo in comment
| mobile/src/com/cradle/iitc_mobile/IITC_AboutDialogPreference.java | mobile: fix typo in comment |
|
Java | mit | db00c68fc170c4908051abaac982034cabe73c20 | 0 | brettonw/bag,brettonw/bag,brettonw/bag | package com.brettonw.bag.formats.text;
import com.brettonw.bag.BagArray;
import com.brettonw.bag.BagObject;
import com.brettonw.bag.formats.FormatReader;
import com.brettonw.bag.formats.MimeType;
/**
* The FormatReaderText is a configurable text format reader for any format that uses a divider
* between entries, and a divider between pairs. An optional "comment" character is supported to
* allow some entries to be skipped on load
*/
public class FormatReaderText extends FormatReader {
String entrySeparator;
String ignoreEntryMarker;
boolean accumulateEntries;
String pairSeparator;
public FormatReaderText (String input, String entrySeparator, boolean accumulateEntries, String pairSeparator) {
this (input, entrySeparator, " ", accumulateEntries, pairSeparator);
}
public FormatReaderText (String input, String entrySeparator, String ignoreEntryMarker, boolean accumulateEntries, String pairSeparator) {
super (input);
this.entrySeparator = entrySeparator;
this.ignoreEntryMarker = ignoreEntryMarker;
this.accumulateEntries = accumulateEntries;
this.pairSeparator = pairSeparator;
}
@Override
public BagArray read (BagArray bagArray) {
if (bagArray == null) bagArray = new BagArray ();
String[] entries = input.split (entrySeparator);
for (String entry : entries) {
entry = entry.trim ();
if ((entry.length () > 0) && (! (entry.startsWith (ignoreEntryMarker)))) {
if (pairSeparator != null) {
String[] fields = entry.split (pairSeparator);
if (fields.length > 1) {
BagArray fieldArray = new BagArray (fields.length);
for (String field : fields) {
fieldArray.add (field);
}
bagArray.add (fieldArray);
} else {
bagArray.add (fields[0]);
}
} else {
bagArray.add (entry);
}
}
}
return bagArray;
}
@Override
public BagObject read (BagObject bagObject) {
if (bagObject == null) bagObject = new BagObject ();
String[] entries = input.split (entrySeparator);
for (String entry : entries) {
entry = entry.trim ();
if ((entry.length () > 0) && (! (entry.startsWith (ignoreEntryMarker)))) {
String[] pair = entry.split (pairSeparator, 2);
if (pair.length == 2) {
String key = pair[0].trim ();
String value = pair[1].trim ();
if ((key.length () > 0) && (value.length () > 0)) {
if (accumulateEntries) {
bagObject.add (key, value);
} else {
bagObject.put (key, value);
}
}
}
}
}
return bagObject;
}
public FormatReaderText () { super (); }
static {
MimeType.addExtensionMapping (MimeType.PROP, "properties");
MimeType.addMimeTypeMapping (MimeType.PROP);
FormatReader.registerFormatReader (MimeType.PROP, false, (input) -> new FormatReaderText (input, "\n", "#", false, "="));
MimeType.addExtensionMapping (MimeType.URL, "url");
MimeType.addMimeTypeMapping (MimeType.URL);
FormatReader.registerFormatReader (MimeType.URL, false, (input) -> new FormatReaderText (input, "&", false, "="));
}
}
| src/main/java/com/brettonw/bag/formats/text/FormatReaderText.java | package com.brettonw.bag.formats.text;
import com.brettonw.bag.BagArray;
import com.brettonw.bag.BagObject;
import com.brettonw.bag.formats.FormatReader;
import com.brettonw.bag.formats.MimeType;
/**
* The FormatReaderText is a configurable text format reader for any format that uses a divider
* between entries, and a divider between pairs. An optional "comment" character is supported to
* allow some entries to be skipped on load
*/
public class FormatReaderText extends FormatReader {
String entrySeparator;
String ignoreEntryMarker;
boolean accumulateEntries;
String pairSeparator;
public FormatReaderText (String input, String entrySeparator, boolean accumulateEntries, String pairSeparator) {
this (input, entrySeparator, " ", accumulateEntries, pairSeparator);
}
public FormatReaderText (String input, String entrySeparator, String ignoreEntryMarker, boolean accumulateEntries, String pairSeparator) {
super (input);
this.entrySeparator = entrySeparator;
this.ignoreEntryMarker = ignoreEntryMarker;
this.accumulateEntries = accumulateEntries;
this.pairSeparator = pairSeparator;
}
@Override
public BagArray read (BagArray bagArray) {
if (bagArray == null) bagArray = new BagArray ();
String[] entries = input.split (entrySeparator);
for (String entry : entries) {
entry = entry.trim ();
if ((entry.length () > 0) && (! (entry.startsWith (ignoreEntryMarker)))) {
bagArray.add (entry);
}
}
return bagArray;
}
@Override
public BagObject read (BagObject bagObject) {
if (bagObject == null) bagObject = new BagObject ();
String[] entries = input.split (entrySeparator);
for (String entry : entries) {
entry = entry.trim ();
if ((entry.length () > 0) && (! (entry.startsWith (ignoreEntryMarker)))) {
String[] pair = entry.split (pairSeparator, 2);
if (pair.length == 2) {
String key = pair[0].trim ();
String value = pair[1].trim ();
if ((key.length () > 0) && (value.length () > 0)) {
if (accumulateEntries) {
bagObject.add (key, value);
} else {
bagObject.put (key, value);
}
}
}
}
}
return bagObject;
}
public FormatReaderText () { super (); }
static {
MimeType.addExtensionMapping (MimeType.PROP, "properties");
MimeType.addMimeTypeMapping (MimeType.PROP);
FormatReader.registerFormatReader (MimeType.PROP, false, (input) -> new FormatReaderText (input, "\n", "#", false, "="));
MimeType.addExtensionMapping (MimeType.URL, "url");
MimeType.addMimeTypeMapping (MimeType.URL);
FormatReader.registerFormatReader (MimeType.URL, false, (input) -> new FormatReaderText (input, "&", false, "="));
}
}
| minor update to allow reading array files with the pair delimiter, may want to come back to that someday...
| src/main/java/com/brettonw/bag/formats/text/FormatReaderText.java | minor update to allow reading array files with the pair delimiter, may want to come back to that someday... |
|
Java | mit | 7dac8e2f6cdd95c9b80a8ecbcc56c742241b3c76 | 0 | FranckCo/Metadata-API | package fr.insee.rmes.api.operations;
public class OperationsQueries {
public static String getOperationTree() {
return "SELECT DISTINCT ?familyId ?familyLabelLg1 ?familyLabelLg2 ?family ?seriesId ?seriesLabelLg1 ?seriesLabelLg2 ?series ?simsId ?operationId ?opLabelLg1 ?opLabelLg2 ?operation\r\n" +
" ?indicId ?indicLabelLg1 ?indicLabelLg2 ?indic \r\n" +
" { \r\n" +
" ?family a insee:StatisticalOperationFamily . \r\n" +
" ?family skos:prefLabel ?familyLabelLg1 . \r\n" +
" FILTER (lang(?familyLabelLg1 ) = 'fr') \r\n" +
" ?family skos:prefLabel ?familyLabelLg2 . \r\n" +
" FILTER (lang(?familyLabelLg2 ) = 'en') \r\n" +
" BIND(STRAFTER(STR(?family),'/operations/famille/') AS ?familyId ) . \r\n" +
"\r\n" +
" ?family dcterms:hasPart ?series . \r\n" +
" ?series a insee:StatisticalOperationSeries . \r\n" +
" ?series skos:prefLabel ?seriesLabelLg1 . \r\n" +
" FILTER (lang(?seriesLabelLg1) = 'fr') \r\n" +
" ?series skos:prefLabel ?seriesLabelLg2 . \r\n" +
" FILTER (lang(?seriesLabelLg2) = 'en') \r\n" +
" BIND(STRAFTER(STR(?series),'/operations/serie/') AS ?seriesId) . \r\n" +
"\r\n" +
" {OPTIONAL {?series dcterms:hasPart ?operation . \r\n" +
" ?operation a insee:StatisticalOperation . \r\n" +
" ?operation skos:prefLabel ?opLabelLg1 . \r\n" +
" FILTER (lang(?opLabelLg1) = 'fr') \r\n" +
" ?operation skos:prefLabel ?opLabelLg2 . \r\n" +
" FILTER (lang(?opLabelLg2) = 'en') \r\n" +
" BIND(STRAFTER(STR(?operation),'/operations/operation/') AS ?operationId) . \r\n" +
" OPTIONAL { ?sims sdmx-mm:target ?operation . \r\n" +
" ?sims a sdmx-mm:MetadataReport . \r\n" +
" BIND(STRAFTER(STR(?sims),'/qualite/rapport/') AS ?simsId) . \r\n" +
" }\r\n" +
" }}\r\n" +
" UNION\r\n" +
" {OPTIONAL{?indic prov:wasGeneratedBy ?series . \r\n" +
" ?indic a insee:StatisticalIndicator . \r\n" +
" ?indic skos:prefLabel ?indicLabelLg1 . \r\n" +
" FILTER (lang(?indicLabelLg1) = 'fr') \r\n" +
" ?indic skos:prefLabel ?indicLabelLg2 . \r\n" +
" FILTER (lang(?indicLabelLg2) = 'en') \r\n" +
" BIND(STRAFTER(STR(?indic),'/produits/indicateur/') AS ?indicId) . \r\n" +
" OPTIONAL { ?sims sdmx-mm:target ?indic . \r\n" +
" ?sims a sdmx-mm:MetadataReport . \r\n" +
" BIND(STRAFTER(STR(?sims),'/qualite/rapport/') AS ?simsId) . \r\n" +
" }\r\n" +
" }}\r\n" +
" UNION\r\n" +
" {OPTIONAL { ?sims sdmx-mm:target ?series . \r\n" +
" ?sims a sdmx-mm:MetadataReport . \r\n" +
" BIND(STRAFTER(STR(?sims),'/qualite/rapport/') AS ?simsId) . \r\n" +
" }}\r\n" +
"}\r\n" +
" order by ?familyId ?seriesId ";
}
public static String getDocumentationTitle(String idSims) {
return " SELECT ?id ?uri ?labelLg1 ?labelLg2 ?idCible ?cible ?labelCibleLg1 ?labelCibleLg2 "
+" FROM <http://rdf.insee.fr/graphes/qualite/rapport/"+idSims+"> "
+" WHERE { "
+" ?uri rdf:type sdmx-mm:MetadataReport . "
+" "
+" OPTIONAL{ ?uri sdmx-mm:target ?cible . "
+ " BIND(STRAFTER(STR(?cible),'/') AS ?idCible) . "
+" ?cible rdfs:label ?labelCibleLg1 . "
+" FILTER(lang(?labelCibleLg1) = 'fr') "
+" OPTIONAL{?cible rdfs:label ?labelCibleLg2 . "
+" FILTER(lang(?labelCibleLg2) = 'en') } "
+" } "
+" "
+" OPTIONAL{ ?uri rdfs:label ?labelLg1 . "
+" FILTER(lang(?labelLg1) = 'fr') "
+" } "
+" OPTIONAL{ ?uri rdfs:label ?labelLg2 . "
+" FILTER(lang(?labelLg2) = 'en') "
+" } "
+" "
+" FILTER(STRENDS(STR(?uri), '"+idSims+"')) "
+ " BIND ("+idSims+" AS ?id ) "
+" } ";
}
public static String getDocumentationRubrics(String idSims) {
return "SELECT ?uri ?id ?idParent ?titreLg1 ?titreLg2 ?type ?valeurSimple ?labelLg1 ?labelLg2 ?codeUri ?organisationUri ?hasDoc ?labelObjLg1 ?labelObjLg2 "
+" FROM <http://rdf.insee.fr/graphes/qualite/rapport/"+idSims+"> "
+" FROM <http://rdf.insee.fr/graphes/codes> "
+" FROM <http://rdf.insee.fr/graphes/organisations> "
+" FROM <http://rdf.insee.fr/graphes/def/simsv2fr> "
+" FROM <http://rdf.insee.fr/graphes/concepts/qualite> "
+"WHERE { "
+" { "
+" ?report rdf:type sdmx-mm:MetadataReport . "
+" ?reporturi sdmx-mm:metadataReport ?report . "
+" OPTIONAL {?mas sdmx-mm:metadataAttributeProperty ?uri . "
+" ?mas sdmx-mm:parent ?uriParent . } "
+" BIND(REPLACE( STR(?uriParent) , '(.*/)(\\\\w.+$)', '$2' ) AS ?idParent) . "
+" ?uri sdmx-mm:concept ?concept . "
+" ?concept skos:prefLabel ?titreLg1 ; skos:prefLabel ?titreLg2 ; "
+" FILTER(lang(?titreLg1) = 'fr') "
+" FILTER(lang(?titreLg2) = 'en') "
+" BIND(REPLACE( STR(?uri) , '(.*/)(\\\\w.+$)', '$2' ) AS ?id) . "
+" ?reporturi ?uri ?valeurSimple . "
+" FILTER ( datatype(?valeurSimple) = xsd:date ) "
+" BIND('DATE' AS ?type) . "
+" } "
+" "
+" UNION { "
+" ?report rdf:type sdmx-mm:MetadataReport . "
+" ?reporturi sdmx-mm:metadataReport ?report . "
+" OPTIONAL { ?mas sdmx-mm:metadataAttributeProperty ?uri . "
+" ?mas sdmx-mm:parent ?uriParent . } "
+" BIND(REPLACE( STR(?uriParent) , '(.*/)(\\\\w.+$)', '$2' ) AS ?idParent) . "
+" ?uri sdmx-mm:concept ?concept . "
+" ?concept skos:prefLabel ?titreLg1 ; "
+" skos:prefLabel ?titreLg2 ; "
+" FILTER(lang(?titreLg1) = 'fr') "
+" FILTER(lang(?titreLg2) = 'en') "
+" ?reporturi ?uri ?text . "
+" ?text rdf:type <http://purl.org/dc/dcmitype/Text> "
+" BIND(REPLACE( STR(?uri) , '(.*/)(\\\\w.+$)', '$2' ) AS ?id) . "
+" OPTIONAL{ ?text rdf:value ?labelLg1 . "
+" FILTER(lang(?labelLg1) = 'fr') "
+" } "
+" OPTIONAL{?text rdf:value ?labelLg2 . "
+" FILTER(lang(?labelLg2) = 'en') "
+" } "
+" BIND(EXISTS{?text insee:additionalMaterial ?doc} AS ?hasDoc) "
+" BIND('RICH_TEXT' AS ?type) . "
+" } "
+" "
+" UNION { "
+" ?report rdf:type sdmx-mm:MetadataReport . "
+" ?reporturi sdmx-mm:metadataReport ?report . "
+" OPTIONAL { ?mas sdmx-mm:metadataAttributeProperty ?uri . "
+" ?mas sdmx-mm:parent ?uriParent . } "
+" BIND(REPLACE( STR(?uriParent) , '(.*/)(\\\\w.+$)', '$2' ) AS ?idParent) . "
+" ?uri sdmx-mm:concept ?concept . "
+" ?concept skos:prefLabel ?titreLg1 ; skos:prefLabel ?titreLg2 ; "
+" FILTER(lang(?titreLg1) = 'fr') "
+" FILTER(lang(?titreLg2) = 'en') "
+" BIND(REPLACE( STR(?uri) , '(.*/)(\\\\w.+$)', '$2' ) AS ?id) . "
+" ?reporturi ?uri ?labelLg1 . "
+" FILTER(lang(?labelLg1) = 'fr') "
+" OPTIONAL{?reporturi ?uri ?labelLg2 . "
+" FILTER(lang(?labelLg2) = 'en') } "
+" BIND('TEXT' AS ?type) . "
+" } "
+" UNION { "
+" ?report rdf:type sdmx-mm:MetadataReport . "
+" ?reporturi sdmx-mm:metadataReport ?report . "
+" OPTIONAL {?mas sdmx-mm:metadataAttributeProperty ?uri . "
+" ?mas sdmx-mm:parent ?uriParent . } "
+" BIND(REPLACE( STR(?uriParent) , '(.*/)(\\\\w.+$)', '$2' ) AS ?idParent) . "
+" ?uri sdmx-mm:concept ?concept . "
+" ?concept skos:prefLabel ?titreLg1 ; skos:prefLabel ?titreLg2 ; "
+" FILTER(lang(?titreLg1) = 'fr') "
+" FILTER(lang(?titreLg2) = 'en') "
+" BIND(REPLACE( STR(?uri) , '(.*/)(\\\\w.+$)', '$2' ) AS ?id) . "
+" ?reporturi ?uri ?codeUri . "
+" ?codeUri skos:notation ?valeurSimple . "
+" ?codeUri skos:inScheme ?listUri . "
+" ?listUri skos:notation ?codeList . "
+" ?codeUri skos:prefLabel ?labelObjLg1 . "
+" FILTER (lang(?labelObjLg1) = 'fr') . "
+" ?codeUri skos:prefLabel ?labelObjLg2 . "
+" FILTER (lang(?labelObjLg2) = 'en') . "
+" BIND('CODE_LIST' AS ?type) . "
+" } "
+" UNION { "
+" ?report rdf:type sdmx-mm:MetadataReport . "
+" ?reporturi sdmx-mm:metadataReport ?report . "
+" OPTIONAL { ?mas sdmx-mm:metadataAttributeProperty ?uri . "
+" ?mas sdmx-mm:parent ?uriParent . } "
+" BIND(REPLACE( STR(?uriParent) , '(.*/)(\\\\w.+$)', '$2' ) AS ?idParent) . "
+" ?uri sdmx-mm:concept ?concept . "
+" ?concept skos:prefLabel ?titreLg1 ; skos:prefLabel ?titreLg2 ; "
+" FILTER(lang(?titreLg1) = 'fr') "
+" FILTER(lang(?titreLg2) = 'en') "
+" ?reporturi ?uri ?organisationUri . "
+" BIND(REPLACE( STR(?uri) , '(.*/)(\\\\w.+$)', '$2' ) AS ?id) . "
+" ?organisationUri dcterms:identifier ?valeurSimple . "
+" OPTIONAL { ?organisationUri skos:prefLabel ?labelObjLg1 . "
+" FILTER (lang(?labelObjLg1) = 'fr')} "
+" OPTIONAL {?organisationUri skos:prefLabel ?labelObjLg2 . "
+" FILTER (lang(?labelObjLg2) = 'en') } "
+" BIND('ORGANISATION' AS ?type) . "
+" } "
+"} ";
}
public static String getDocuments(String idSims, String idRubric) {
return "SELECT ?url ?labelLg1 ?labelLg2 ?dateMiseAJour ?langue "
+"FROM <http://rdf.insee.fr/graphes/qualite/rapport/"+idSims+"> "
+"WHERE { "
+" ?text rdf:type <http://purl.org/dc/dcmitype/Text> . "
+" ?text insee:additionalMaterial ?document . "
+" ?document rdf:type <http://xmlns.com/foaf/0.1/Document> . "
+" "
+" ?document <http://schema.org/url> ?url "
+" "
+" OPTIONAL{ ?document rdfs:label ?labelLg1 . "
+" FILTER(lang(?labelLg1) = 'fr') "
+" } "
+" OPTIONAL{ ?document rdfs:label ?labelLg2 . "
+" FILTER(lang(?labelLg2) = 'en') "
+" } "
+" "
+" OPTIONAL{ ?document pav:lastRefreshedOn ?dateMiseAJour . } "
+" OPTIONAL{ ?document dc:language ?langue . } "
+" "
+" FILTER(REGEX(STR(?text), '"+idRubric+"')) "
+" "
+" } ";
}
}
| src/main/java/fr/insee/rmes/api/operations/OperationsQueries.java | package fr.insee.rmes.api.operations;
public class OperationsQueries {
public static String getOperationTree() {
return "SELECT ?familyId ?familyLabelLg1 ?familyLabelLg2 ?family ?seriesId ?seriesLabelLg1 ?seriesLabelLg2 ?series ?simsId ?operationId ?opLabelLg1 ?opLabelLg2 ?operation\r\n" +
" ?indicId ?indicLabelLg1 ?indicLabelLg2 ?indic \r\n" +
" { \r\n" +
" ?family a insee:StatisticalOperationFamily . \r\n" +
" ?family skos:prefLabel ?familyLabelLg1 . \r\n" +
" FILTER (lang(?familyLabelLg1 ) = 'fr') \r\n" +
" ?family skos:prefLabel ?familyLabelLg2 . \r\n" +
" FILTER (lang(?familyLabelLg2 ) = 'en') \r\n" +
" BIND(STRAFTER(STR(?family),'/operations/famille/') AS ?familyId ) . \r\n" +
"\r\n" +
" ?family dcterms:hasPart ?series . \r\n" +
" ?series a insee:StatisticalOperationSeries . \r\n" +
" ?series skos:prefLabel ?seriesLabelLg1 . \r\n" +
" FILTER (lang(?seriesLabelLg1) = 'fr') \r\n" +
" ?series skos:prefLabel ?seriesLabelLg2 . \r\n" +
" FILTER (lang(?seriesLabelLg2) = 'en') \r\n" +
" BIND(STRAFTER(STR(?series),'/operations/serie/') AS ?seriesId) . \r\n" +
"\r\n" +
" {OPTIONAL {?series dcterms:hasPart ?operation . \r\n" +
" ?operation a insee:StatisticalOperation . \r\n" +
" ?operation skos:prefLabel ?opLabelLg1 . \r\n" +
" FILTER (lang(?opLabelLg1) = 'fr') \r\n" +
" ?operation skos:prefLabel ?opLabelLg2 . \r\n" +
" FILTER (lang(?opLabelLg2) = 'en') \r\n" +
" BIND(STRAFTER(STR(?operation),'/operations/operation/') AS ?operationId) . \r\n" +
" OPTIONAL { ?sims sdmx-mm:target ?operation . \r\n" +
" ?sims a sdmx-mm:MetadataReport . \r\n" +
" BIND(STRAFTER(STR(?sims),'/qualite/rapport/') AS ?simsId) . \r\n" +
" }\r\n" +
" }}\r\n" +
" UNION\r\n" +
" {OPTIONAL{?indic prov:wasGeneratedBy ?series . \r\n" +
" ?indic a insee:StatisticalIndicator . \r\n" +
" ?indic skos:prefLabel ?indicLabelLg1 . \r\n" +
" FILTER (lang(?indicLabelLg1) = 'fr') \r\n" +
" ?indic skos:prefLabel ?indicLabelLg2 . \r\n" +
" FILTER (lang(?indicLabelLg2) = 'en') \r\n" +
" BIND(STRAFTER(STR(?indic),'/produits/indicateur/') AS ?indicId) . \r\n" +
" OPTIONAL { ?sims sdmx-mm:target ?indic . \r\n" +
" ?sims a sdmx-mm:MetadataReport . \r\n" +
" BIND(STRAFTER(STR(?sims),'/qualite/rapport/') AS ?simsId) . \r\n" +
" }\r\n" +
" }}\r\n" +
" OPTIONAL { ?sims sdmx-mm:target ?series . \r\n" +
" ?sims a sdmx-mm:MetadataReport . \r\n" +
" BIND(STRAFTER(STR(?sims),'/qualite/rapport/') AS ?simsId) . \r\n" +
" }\r\n" +
"}\r\n" +
" order by ?familyId ?seriesId ";
}
public static String getDocumentationTitle(String idSims) {
return " SELECT ?id ?uri ?labelLg1 ?labelLg2 ?idCible ?cible ?labelCibleLg1 ?labelCibleLg2 "
+" FROM <http://rdf.insee.fr/graphes/qualite/rapport/"+idSims+"> "
+" WHERE { "
+" ?uri rdf:type sdmx-mm:MetadataReport . "
+" "
+" OPTIONAL{ ?uri sdmx-mm:target ?cible . "
+ " BIND(STRAFTER(STR(?cible),'/') AS ?idCible) . "
+" ?cible rdfs:label ?labelCibleLg1 . "
+" FILTER(lang(?labelCibleLg1) = 'fr') "
+" OPTIONAL{?cible rdfs:label ?labelCibleLg2 . "
+" FILTER(lang(?labelCibleLg2) = 'en') } "
+" } "
+" "
+" OPTIONAL{ ?uri rdfs:label ?labelLg1 . "
+" FILTER(lang(?labelLg1) = 'fr') "
+" } "
+" OPTIONAL{ ?uri rdfs:label ?labelLg2 . "
+" FILTER(lang(?labelLg2) = 'en') "
+" } "
+" "
+" FILTER(STRENDS(STR(?uri), '"+idSims+"')) "
+ " BIND ("+idSims+" AS ?id ) "
+" } ";
}
public static String getDocumentationRubrics(String idSims) {
return "SELECT ?uri ?id ?idParent ?titreLg1 ?titreLg2 ?type ?valeurSimple ?labelLg1 ?labelLg2 ?codeUri ?organisationUri ?hasDoc ?labelObjLg1 ?labelObjLg2 "
+" FROM <http://rdf.insee.fr/graphes/qualite/rapport/"+idSims+"> "
+" FROM <http://rdf.insee.fr/graphes/codes> "
+" FROM <http://rdf.insee.fr/graphes/organisations> "
+" FROM <http://rdf.insee.fr/graphes/def/simsv2fr> "
+" FROM <http://rdf.insee.fr/graphes/concepts/qualite> "
+"WHERE { "
+" { "
+" ?report rdf:type sdmx-mm:MetadataReport . "
+" ?reporturi sdmx-mm:metadataReport ?report . "
+" OPTIONAL {?mas sdmx-mm:metadataAttributeProperty ?uri . "
+" ?mas sdmx-mm:parent ?uriParent . } "
+" BIND(REPLACE( STR(?uriParent) , '(.*/)(\\\\w.+$)', '$2' ) AS ?idParent) . "
+" ?uri sdmx-mm:concept ?concept . "
+" ?concept skos:prefLabel ?titreLg1 ; skos:prefLabel ?titreLg2 ; "
+" FILTER(lang(?titreLg1) = 'fr') "
+" FILTER(lang(?titreLg2) = 'en') "
+" BIND(REPLACE( STR(?uri) , '(.*/)(\\\\w.+$)', '$2' ) AS ?id) . "
+" ?reporturi ?uri ?valeurSimple . "
+" FILTER ( datatype(?valeurSimple) = xsd:date ) "
+" BIND('DATE' AS ?type) . "
+" } "
+" "
+" UNION { "
+" ?report rdf:type sdmx-mm:MetadataReport . "
+" ?reporturi sdmx-mm:metadataReport ?report . "
+" OPTIONAL { ?mas sdmx-mm:metadataAttributeProperty ?uri . "
+" ?mas sdmx-mm:parent ?uriParent . } "
+" BIND(REPLACE( STR(?uriParent) , '(.*/)(\\\\w.+$)', '$2' ) AS ?idParent) . "
+" ?uri sdmx-mm:concept ?concept . "
+" ?concept skos:prefLabel ?titreLg1 ; "
+" skos:prefLabel ?titreLg2 ; "
+" FILTER(lang(?titreLg1) = 'fr') "
+" FILTER(lang(?titreLg2) = 'en') "
+" ?reporturi ?uri ?text . "
+" ?text rdf:type <http://purl.org/dc/dcmitype/Text> "
+" BIND(REPLACE( STR(?uri) , '(.*/)(\\\\w.+$)', '$2' ) AS ?id) . "
+" OPTIONAL{ ?text rdf:value ?labelLg1 . "
+" FILTER(lang(?labelLg1) = 'fr') "
+" } "
+" OPTIONAL{?text rdf:value ?labelLg2 . "
+" FILTER(lang(?labelLg2) = 'en') "
+" } "
+" BIND(EXISTS{?text insee:additionalMaterial ?doc} AS ?hasDoc) "
+" BIND('RICH_TEXT' AS ?type) . "
+" } "
+" "
+" UNION { "
+" ?report rdf:type sdmx-mm:MetadataReport . "
+" ?reporturi sdmx-mm:metadataReport ?report . "
+" OPTIONAL { ?mas sdmx-mm:metadataAttributeProperty ?uri . "
+" ?mas sdmx-mm:parent ?uriParent . } "
+" BIND(REPLACE( STR(?uriParent) , '(.*/)(\\\\w.+$)', '$2' ) AS ?idParent) . "
+" ?uri sdmx-mm:concept ?concept . "
+" ?concept skos:prefLabel ?titreLg1 ; skos:prefLabel ?titreLg2 ; "
+" FILTER(lang(?titreLg1) = 'fr') "
+" FILTER(lang(?titreLg2) = 'en') "
+" BIND(REPLACE( STR(?uri) , '(.*/)(\\\\w.+$)', '$2' ) AS ?id) . "
+" ?reporturi ?uri ?labelLg1 . "
+" FILTER(lang(?labelLg1) = 'fr') "
+" OPTIONAL{?reporturi ?uri ?labelLg2 . "
+" FILTER(lang(?labelLg2) = 'en') } "
+" BIND('TEXT' AS ?type) . "
+" } "
+" UNION { "
+" ?report rdf:type sdmx-mm:MetadataReport . "
+" ?reporturi sdmx-mm:metadataReport ?report . "
+" OPTIONAL {?mas sdmx-mm:metadataAttributeProperty ?uri . "
+" ?mas sdmx-mm:parent ?uriParent . } "
+" BIND(REPLACE( STR(?uriParent) , '(.*/)(\\\\w.+$)', '$2' ) AS ?idParent) . "
+" ?uri sdmx-mm:concept ?concept . "
+" ?concept skos:prefLabel ?titreLg1 ; skos:prefLabel ?titreLg2 ; "
+" FILTER(lang(?titreLg1) = 'fr') "
+" FILTER(lang(?titreLg2) = 'en') "
+" BIND(REPLACE( STR(?uri) , '(.*/)(\\\\w.+$)', '$2' ) AS ?id) . "
+" ?reporturi ?uri ?codeUri . "
+" ?codeUri skos:notation ?valeurSimple . "
+" ?codeUri skos:inScheme ?listUri . "
+" ?listUri skos:notation ?codeList . "
+" ?codeUri skos:prefLabel ?labelObjLg1 . "
+" FILTER (lang(?labelObjLg1) = 'fr') . "
+" ?codeUri skos:prefLabel ?labelObjLg2 . "
+" FILTER (lang(?labelObjLg2) = 'en') . "
+" BIND('CODE_LIST' AS ?type) . "
+" } "
+" UNION { "
+" ?report rdf:type sdmx-mm:MetadataReport . "
+" ?reporturi sdmx-mm:metadataReport ?report . "
+" OPTIONAL { ?mas sdmx-mm:metadataAttributeProperty ?uri . "
+" ?mas sdmx-mm:parent ?uriParent . } "
+" BIND(REPLACE( STR(?uriParent) , '(.*/)(\\\\w.+$)', '$2' ) AS ?idParent) . "
+" ?uri sdmx-mm:concept ?concept . "
+" ?concept skos:prefLabel ?titreLg1 ; skos:prefLabel ?titreLg2 ; "
+" FILTER(lang(?titreLg1) = 'fr') "
+" FILTER(lang(?titreLg2) = 'en') "
+" ?reporturi ?uri ?organisationUri . "
+" BIND(REPLACE( STR(?uri) , '(.*/)(\\\\w.+$)', '$2' ) AS ?id) . "
+" ?organisationUri dcterms:identifier ?valeurSimple . "
+" OPTIONAL { ?organisationUri skos:prefLabel ?labelObjLg1 . "
+" FILTER (lang(?labelObjLg1) = 'fr')} "
+" OPTIONAL {?organisationUri skos:prefLabel ?labelObjLg2 . "
+" FILTER (lang(?labelObjLg2) = 'en') } "
+" BIND('ORGANISATION' AS ?type) . "
+" } "
+"} ";
}
public static String getDocuments(String idSims, String idRubric) {
return "SELECT ?url ?labelLg1 ?labelLg2 ?dateMiseAJour ?langue "
+"FROM <http://rdf.insee.fr/graphes/qualite/rapport/"+idSims+"> "
+"WHERE { "
+" ?text rdf:type <http://purl.org/dc/dcmitype/Text> . "
+" ?text insee:additionalMaterial ?document . "
+" ?document rdf:type <http://xmlns.com/foaf/0.1/Document> . "
+" "
+" ?document <http://schema.org/url> ?url "
+" "
+" OPTIONAL{ ?document rdfs:label ?labelLg1 . "
+" FILTER(lang(?labelLg1) = 'fr') "
+" } "
+" OPTIONAL{ ?document rdfs:label ?labelLg2 . "
+" FILTER(lang(?labelLg2) = 'en') "
+" } "
+" "
+" OPTIONAL{ ?document pav:lastRefreshedOn ?dateMiseAJour . } "
+" OPTIONAL{ ?document dc:language ?langue . } "
+" "
+" FILTER(REGEX(STR(?text), '"+idRubric+"')) "
+" "
+" } ";
}
}
| Fix idSims in Operation Service
| src/main/java/fr/insee/rmes/api/operations/OperationsQueries.java | Fix idSims in Operation Service |
|
Java | mit | 4e2d0d9426e88354d366fbc932e68104134078c7 | 0 | pakoito/RxPaper2 | /*
* The MIT License (MIT)
* Copyright (c) 2017 pakoito & 2015 César Ferreira
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.pacoworks.rxpaper2;
import android.content.Context;
import android.util.Pair;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicBoolean;
import io.paperdb.Book;
import io.paperdb.Paper;
import io.reactivex.BackpressureStrategy;
import io.reactivex.Completable;
import io.reactivex.Flowable;
import io.reactivex.Scheduler;
import io.reactivex.Single;
import io.reactivex.functions.Action;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.PublishSubject;
import io.reactivex.subjects.Subject;
/**
* Adapter class with a new interface to perform PaperDB operations.
*
* @author pakoito
*/
public class RxPaperBook {
private static final AtomicBoolean INITIALIZED = new AtomicBoolean();
final Book book;
final Scheduler scheduler;
final Subject<Pair<String, ?>> updates = PublishSubject.<Pair<String, ?>> create().toSerialized();
private RxPaperBook(Scheduler scheduler) {
this.scheduler = scheduler;
book = Paper.book();
}
private RxPaperBook(String customBook, Scheduler scheduler) {
this.scheduler = scheduler;
book = Paper.book(customBook);
}
private RxPaperBook(Scheduler scheduler, String path) {
this.scheduler = scheduler;
book = Paper.bookOn(path);
}
private RxPaperBook(String customBook, Scheduler scheduler, String path) {
this.scheduler = scheduler;
book = Paper.bookOn(path, customBook);
}
/**
* Initializes the underlying {@link Paper} database.
* <p/>
* This operation is required only once, but can be called multiple times safely.
*
* @param context application context
*/
public static void init(Context context) {
if (INITIALIZED.compareAndSet(false, true)) {
Paper.init(context.getApplicationContext());
}
}
private static void assertInitialized() {
if (!INITIALIZED.get()) {
throw new IllegalStateException(
"RxPaper not initialized. Call RxPaper#init(Context) once");
}
}
/**
* Open the main {@link Book} running its operations on {@link Schedulers#io()}.
* <p/>
* Requires calling {@link RxPaperBook#init(Context)} at least once beforehand.
*
* @return new RxPaperBook
*/
public static RxPaperBook with() {
assertInitialized();
return new RxPaperBook(Schedulers.io());
}
/**
* Open a custom {@link Book} running its operations on {@link Schedulers#io()}.
* <p/>
* Requires calling {@link RxPaperBook#init(Context)} at least once beforehand.
*
* @param customBook book name
* @return new RxPaperBook
*/
public static RxPaperBook with(String customBook) {
assertInitialized();
return new RxPaperBook(customBook, Schedulers.io());
}
/**
* Open the main {@link Book} running its operations on a provided scheduler.
* <p/>
* Requires calling {@link RxPaperBook#init(Context)} at least once beforehand.
*
* @param scheduler scheduler where operations will be run
* @return new RxPaperBook
*/
public static RxPaperBook with(Scheduler scheduler) {
assertInitialized();
return new RxPaperBook(scheduler);
}
/**
* Open a custom {@link Book} running its operations on a provided scheduler.
* <p/>
* Requires calling {@link RxPaperBook#init(Context)} at least once beforehand.
*
* @param customBook book name
* @param scheduler scheduler where operations will be run
* @return new RxPaperBook
*/
public static RxPaperBook with(String customBook, Scheduler scheduler) {
assertInitialized();
return new RxPaperBook(customBook, scheduler);
}
/**
* Open a custom {@link Book} with custom storage location path running its operations on
* {@link Schedulers#io()}.
* <p/>
* Requires calling {@link RxPaperBook#init(Context)} at least once beforehand.
*
* @param path storage location name
* @return new RxPaperBook
*/
public static RxPaperBook withPath(String path) {
assertInitialized();
return new RxPaperBook(Schedulers.io(), path);
}
/**
* Open a custom {@link Book} with custom storage location path running its operations on a
* provided scheduler.
* <p/>
* Requires calling {@link RxPaperBook#init(Context)} at least once beforehand.
*
* @param path storage location
* @param scheduler scheduler where operations will be run
* @return new RxPaperBook
*/
public static RxPaperBook withPath(String path, Scheduler scheduler) {
assertInitialized();
return new RxPaperBook(scheduler, path);
}
/**
* Open a custom {@link Book} with custom storage location path running its operations on
* {@link Schedulers#io()}.
* <p/>
* Requires calling {@link RxPaperBook#init(Context)} at least once beforehand.
*
* @param path storage location
* @param customBook book name
* @return new RxPaperBook
*/
public static RxPaperBook withPath(String path, String customBook) {
assertInitialized();
return new RxPaperBook(customBook, Schedulers.io(), path);
}
/**
* Open a custom {@link Book} with custom storage location path running its operations on a
* provided scheduler.
* <p/>
* Requires calling {@link RxPaperBook#init(Context)} at least once beforehand.
*
* @param path storage location
* @param scheduler scheduler where operations will be run
* @param customBook book name
* @return new RxPaperBook
*/
public static RxPaperBook withPath(String path, Scheduler scheduler, String customBook) {
assertInitialized();
return new RxPaperBook(customBook, scheduler, path);
}
/**
* Saves most types of POJOs or collections in {@link Book} storage.
* <p/>
* To deserialize correctly it is recommended to have an all-args constructor, but other types
* may be available.
*
* @param key object key is used as part of object's file name
* @param value object to save, must have no-arg constructor, can't be null.
* @return this Book instance
*/
public <T> Completable write(final String key, final T value) {
return Completable.fromAction(new Action() {
@Override
public void run() {
book.write(key, value);
}
})
// FIXME in RxJava1 the error would be propagated to updates.
// In RxJava2 the error happens on the Completable this method returns.
// This andThen block reproduces the behavior in RxJava1.
.andThen(Completable.fromAction(new Action() {
@Override
public void run() throws Exception {
try {
updates.onNext(Pair.create(key, value));
} catch (Throwable t) {
updates.onError(t);
}
}
})).subscribeOn(scheduler);
}
/**
* Instantiates saved object using original object class (e.g. LinkedList). Support limited
* backward and forward compatibility: removed fields are ignored, new fields have their default
* values.
*
* @param key object key to read
* @param defaultValue value to be returned if key doesn't exist
* @return the saved object instance or defaultValue
*/
public <T> Single<T> read(final String key, final T defaultValue) {
return Single.fromCallable(new Callable<T>() {
@Override
public T call() {
return book.read(key, defaultValue);
}
}).subscribeOn(scheduler);
}
/**
* Instantiates saved object using original object class (e.g. LinkedList). Support limited
* backward and forward compatibility: removed fields are ignored, new fields have their default
* values.
*
* @param key object key to read
* @return the saved object instance
*/
public <T> Single<T> read(final String key) {
return Single.fromCallable(new Callable<T>() {
@Override
public T call() {
final T read = book.read(key);
if (null == read) {
throw new IllegalArgumentException("Key " + key + " not found");
}
return read;
}
}).subscribeOn(scheduler);
}
/**
* Delete saved object for given key if it is exist.
*/
public Completable delete(final String key) {
return Completable.fromAction(new Action() {
@Override
public void run() {
book.delete(key);
}
}).subscribeOn(scheduler);
}
/**
* Check if an object with the given key is saved in Book storage.
*
* @param key object key
* @return true if object with given key exists in Book storage, false otherwise
* @deprecated As of PaperDB release 2.6, replaced by {@link #contains(String)}}
*/
public Single<Boolean> exists(final String key) {
return Single.fromCallable(new Callable<Boolean>() {
@Override
public Boolean call() {
return book.exist(key);
}
}).subscribeOn(scheduler);
}
/**
* Returns all keys for objects in {@link Book}.
*
* @return all keys
*/
public Single<List<String>> keys() {
return Single.fromCallable(new Callable<List<String>>() {
@Override
public List<String> call() {
return book.getAllKeys();
}
}).subscribeOn(scheduler);
}
/**
* Destroys all data saved in {@link Book}.
*/
public Completable destroy() {
return Completable.fromAction(new Action() {
@Override
public void run() {
book.destroy();
}
}).subscribeOn(scheduler);
}
/**
* Naive update subscription for saved objects. Subscription is filtered by key and type.
*
* @param key object key
* @param backPressureStrategy how the backpressure is handled downstream
* @return hot observable
*/
public <T> Flowable<T> observe(final String key, final Class<T> clazz, BackpressureStrategy backPressureStrategy) {
return updates.toFlowable(backPressureStrategy)
.filter(new Predicate<Pair<String, ?>>() {
@Override
public boolean test(Pair<String, ?> stringPair) {
return stringPair.first.equals(key);
}
}).map(new Function<Pair<String, ?>, Object>() {
@Override
public Object apply(Pair<String, ?> stringPair) {
return stringPair.second;
}
}).ofType(clazz);
}
/**
* Naive update subscription for saved objects.
* <p/>
* This method will return all objects for a key casted unsafely, and throw
* {@link ClassCastException} if types do not match. For a safely checked and filtered version
* use {@link this#observe(String, Class, BackpressureStrategy)}.
*
* @param key object key
* @param backPressureStrategy how the backpressure is handled downstream
* @return hot observable
*/
@SuppressWarnings("unchecked")
public <T> Flowable<T> observeUnsafe(final String key, BackpressureStrategy backPressureStrategy) {
return updates.toFlowable(backPressureStrategy)
.filter(new Predicate<Pair<String, ?>>() {
@Override
public boolean test(Pair<String, ?> stringPair) {
return stringPair.first.equals(key);
}
}).map(new Function<Pair<String, ?>, T>() {
@Override
public T apply(Pair<String, ?> stringPair) {
return (T) stringPair.second;
}
});
}
/**
* Checks whether the current book contains the key given
*
* @param key the key to look up
* @return true is the book contains a value for the given key
*/
public Single<Boolean> contains(final String key) {
return Single.fromCallable(new Callable<Boolean>() {
@Override
public Boolean call() {
return book.contains(key);
}
}).subscribeOn(scheduler);
}
/**
* Returns the path of the current book
*
* @return the path to the book
*/
public Single<String> getPath() {
return Single.fromCallable(new Callable<String>() {
@Override
public String call() {
return book.getPath();
}
}).subscribeOn(scheduler);
}
/**
* Returns the path of the data stored at the key passed as a parameter.
* The returned path does not exist if the method has been called prior
* saving data for the given key.
*
* @param key the key to look up
* @return the path to the value stored at the key
*/
public Single<String> getPath(final String key) {
return Single.fromCallable(new Callable<String>() {
@Override
public String call() {
return book.getPath(key);
}
}).subscribeOn(scheduler);
}
}
| library/src/main/java/com/pacoworks/rxpaper2/RxPaperBook.java | /*
* The MIT License (MIT)
* Copyright (c) 2017 pakoito & 2015 César Ferreira
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.pacoworks.rxpaper2;
import android.content.Context;
import android.util.Pair;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicBoolean;
import io.paperdb.Book;
import io.paperdb.Paper;
import io.reactivex.BackpressureStrategy;
import io.reactivex.Completable;
import io.reactivex.Flowable;
import io.reactivex.Scheduler;
import io.reactivex.Single;
import io.reactivex.functions.Action;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.PublishSubject;
import io.reactivex.subjects.Subject;
/**
* Adapter class with a new interface to perform PaperDB operations.
*
* @author pakoito
*/
public class RxPaperBook {
private static final AtomicBoolean INITIALIZED = new AtomicBoolean();
final Book book;
final Scheduler scheduler;
final Subject<Pair<String, ?>> updates = PublishSubject.<Pair<String, ?>> create().toSerialized();
private RxPaperBook(Scheduler scheduler) {
this.scheduler = scheduler;
book = Paper.book();
}
private RxPaperBook(String customBook, Scheduler scheduler) {
this.scheduler = scheduler;
book = Paper.book(customBook);
}
/**
* Initializes the underlying {@link Paper} database.
* <p/>
* This operation is required only once, but can be called multiple times safely.
*
* @param context application context
*/
public static void init(Context context) {
if (INITIALIZED.compareAndSet(false, true)) {
Paper.init(context.getApplicationContext());
}
}
private static void assertInitialized() {
if (!INITIALIZED.get()) {
throw new IllegalStateException(
"RxPaper not initialized. Call RxPaper#init(Context) once");
}
}
/**
* Open the main {@link Book} running its operations on {@link Schedulers#io()}.
* <p/>
* Requires calling {@link RxPaperBook#init(Context)} at least once beforehand.
*
* @return new RxPaperBook
*/
public static RxPaperBook with() {
assertInitialized();
return new RxPaperBook(Schedulers.io());
}
/**
* Open a custom {@link Book} running its operations on {@link Schedulers#io()}.
* <p/>
* Requires calling {@link RxPaperBook#init(Context)} at least once beforehand.
*
* @param customBook book name
* @return new RxPaperBook
*/
public static RxPaperBook with(String customBook) {
assertInitialized();
return new RxPaperBook(customBook, Schedulers.io());
}
/**
* Open the main {@link Book} running its operations on a provided scheduler.
* <p/>
* Requires calling {@link RxPaperBook#init(Context)} at least once beforehand.
*
* @param scheduler scheduler where operations will be run
* @return new RxPaperBook
*/
public static RxPaperBook with(Scheduler scheduler) {
assertInitialized();
return new RxPaperBook(scheduler);
}
/**
* Open a custom {@link Book} running its operations on a provided scheduler.
* <p/>
* Requires calling {@link RxPaperBook#init(Context)} at least once beforehand.
*
* @param customBook book name
* @param scheduler scheduler where operations will be run
* @return new RxPaperBook
*/
public static RxPaperBook with(String customBook, Scheduler scheduler) {
assertInitialized();
return new RxPaperBook(customBook, scheduler);
}
/**
* Saves most types of POJOs or collections in {@link Book} storage.
* <p/>
* To deserialize correctly it is recommended to have an all-args constructor, but other types
* may be available.
*
* @param key object key is used as part of object's file name
* @param value object to save, must have no-arg constructor, can't be null.
* @return this Book instance
*/
public <T> Completable write(final String key, final T value) {
return Completable.fromAction(new Action() {
@Override
public void run() {
book.write(key, value);
}
})
// FIXME in RxJava1 the error would be propagated to updates.
// In RxJava2 the error happens on the Completable this method returns.
// This andThen block reproduces the behavior in RxJava1.
.andThen(Completable.fromAction(new Action() {
@Override
public void run() throws Exception {
try {
updates.onNext(Pair.create(key, value));
} catch (Throwable t) {
updates.onError(t);
}
}
})).subscribeOn(scheduler);
}
/**
* Instantiates saved object using original object class (e.g. LinkedList). Support limited
* backward and forward compatibility: removed fields are ignored, new fields have their default
* values.
*
* @param key object key to read
* @param defaultValue value to be returned if key doesn't exist
* @return the saved object instance or defaultValue
*/
public <T> Single<T> read(final String key, final T defaultValue) {
return Single.fromCallable(new Callable<T>() {
@Override
public T call() {
return book.read(key, defaultValue);
}
}).subscribeOn(scheduler);
}
/**
* Instantiates saved object using original object class (e.g. LinkedList). Support limited
* backward and forward compatibility: removed fields are ignored, new fields have their default
* values.
*
* @param key object key to read
* @return the saved object instance
*/
public <T> Single<T> read(final String key) {
return Single.fromCallable(new Callable<T>() {
@Override
public T call() {
final T read = book.read(key);
if (null == read) {
throw new IllegalArgumentException("Key " + key + " not found");
}
return read;
}
}).subscribeOn(scheduler);
}
/**
* Delete saved object for given key if it is exist.
*/
public Completable delete(final String key) {
return Completable.fromAction(new Action() {
@Override
public void run() {
book.delete(key);
}
}).subscribeOn(scheduler);
}
/**
* Check if an object with the given key is saved in Book storage.
*
* @param key object key
* @return true if object with given key exists in Book storage, false otherwise
* @deprecated As of PaperDB release 2.6, replaced by {@link #contains(String)}}
*/
public Single<Boolean> exists(final String key) {
return Single.fromCallable(new Callable<Boolean>() {
@Override
public Boolean call() {
return book.exist(key);
}
}).subscribeOn(scheduler);
}
/**
* Returns all keys for objects in {@link Book}.
*
* @return all keys
*/
public Single<List<String>> keys() {
return Single.fromCallable(new Callable<List<String>>() {
@Override
public List<String> call() {
return book.getAllKeys();
}
}).subscribeOn(scheduler);
}
/**
* Destroys all data saved in {@link Book}.
*/
public Completable destroy() {
return Completable.fromAction(new Action() {
@Override
public void run() {
book.destroy();
}
}).subscribeOn(scheduler);
}
/**
* Naive update subscription for saved objects. Subscription is filtered by key and type.
*
* @param key object key
* @param backPressureStrategy how the backpressure is handled downstream
* @return hot observable
*/
public <T> Flowable<T> observe(final String key, final Class<T> clazz, BackpressureStrategy backPressureStrategy) {
return updates.toFlowable(backPressureStrategy)
.filter(new Predicate<Pair<String, ?>>() {
@Override
public boolean test(Pair<String, ?> stringPair) {
return stringPair.first.equals(key);
}
}).map(new Function<Pair<String, ?>, Object>() {
@Override
public Object apply(Pair<String, ?> stringPair) {
return stringPair.second;
}
}).ofType(clazz);
}
/**
* Naive update subscription for saved objects.
* <p/>
* This method will return all objects for a key casted unsafely, and throw
* {@link ClassCastException} if types do not match. For a safely checked and filtered version
* use {@link this#observe(String, Class, BackpressureStrategy)}.
*
* @param key object key
* @param backPressureStrategy how the backpressure is handled downstream
* @return hot observable
*/
@SuppressWarnings("unchecked")
public <T> Flowable<T> observeUnsafe(final String key, BackpressureStrategy backPressureStrategy) {
return updates.toFlowable(backPressureStrategy)
.filter(new Predicate<Pair<String, ?>>() {
@Override
public boolean test(Pair<String, ?> stringPair) {
return stringPair.first.equals(key);
}
}).map(new Function<Pair<String, ?>, T>() {
@Override
public T apply(Pair<String, ?> stringPair) {
return (T) stringPair.second;
}
});
}
/**
* Checks whether the current book contains the key given
*
* @param key the key to look up
* @return true is the book contains a value for the given key
*/
public Single<Boolean> contains(final String key) {
return Single.fromCallable(new Callable<Boolean>() {
@Override
public Boolean call() {
return book.contains(key);
}
}).subscribeOn(scheduler);
}
/**
* Returns the path of the current book
*
* @return the path to the book
*/
public Single<String> getPath() {
return Single.fromCallable(new Callable<String>() {
@Override
public String call() {
return book.getPath();
}
}).subscribeOn(scheduler);
}
/**
* Returns the path of the data stored at the key passed as a parameter.
* The returned path does not exist if the method has been called prior
* saving data for the given key.
*
* @param key the key to look up
* @return the path to the value stored at the key
*/
public Single<String> getPath(final String key) {
return Single.fromCallable(new Callable<String>() {
@Override
public String call() {
return book.getPath(key);
}
}).subscribeOn(scheduler);
}
}
| Add support for custom storage location path
| library/src/main/java/com/pacoworks/rxpaper2/RxPaperBook.java | Add support for custom storage location path |
|
Java | mit | 2255581861f57055f2ac243ea41be61dd86fd4cc | 0 | elisonevaristo/Exemplo | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.senac.tads.pi3.testegit;
/**
*
* @author elison.esouza
*/
public class Principal {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println("Hello Word! " + (i+1) + " º");
}
}
}
| testegit/src/main/java/br/senac/tads/pi3/testegit/Principal.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.senac.tads.pi3.testegit;
/**
*
* @author elison.esouza
*/
public class Principal {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Hello Word!");
}
}
| Versão atualizada(for) | testegit/src/main/java/br/senac/tads/pi3/testegit/Principal.java | Versão atualizada(for) |
|
Java | mit | cd61ef7169bfcaf9a7500395581ccdea27227b1f | 0 | iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable | package org.broadinstitute.sting.gatk.walkers.genotyper;
import org.broadinstitute.sting.WalkerTest;
import org.broadinstitute.sting.gatk.GenomeAnalysisEngine;
import org.testng.annotations.Test;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
// ********************************************************************************** //
// Note that this class also serves as an integration test for the VariantAnnotator! //
// ********************************************************************************** //
public class UnifiedGenotyperIntegrationTest extends WalkerTest {
private final static String baseCommand = "-T UnifiedGenotyper -R " + b36KGReference + " -NO_HEADER";
// --------------------------------------------------------------------------------------------------------------
//
// testing normal calling
//
// --------------------------------------------------------------------------------------------------------------
@Test
public void testMultiSamplePilot1() {
WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
baseCommand + " -I " + validationDataLocation + "low_coverage_CEU.chr1.10k-11k.bam -o %s -L 1:10,022,000-10,025,000", 1,
Arrays.asList("9895541f0395ddb9977abb7d8274831e"));
executeTest("test MultiSample Pilot1", spec);
}
@Test
public void testMultiSamplePilot2AndRecallingWithAlleles() {
String md5 = "2a8461e846a437ddcac9f1be185d0a4b";
WalkerTest.WalkerTestSpec spec1 = new WalkerTest.WalkerTestSpec(
baseCommand + " -I " + validationDataLocation + "pilot2_daughters.chr20.10k-11k.bam -o %s -L 20:10,000,000-10,050,000", 1,
Arrays.asList(md5));
List<File> result = executeTest("test MultiSample Pilot2", spec1).getFirst();
GenomeAnalysisEngine.resetRandomGenerator();
WalkerTest.WalkerTestSpec spec2 = new WalkerTest.WalkerTestSpec(
baseCommand + " --genotyping_mode GENOTYPE_GIVEN_ALLELES -B:alleles,vcf " + result.get(0).getAbsolutePath() + " -I " + validationDataLocation + "pilot2_daughters.chr20.10k-11k.bam -o %s -L 20:10,000,000-10,050,000", 1,
Arrays.asList(md5));
executeTest("test MultiSample Pilot2 with alleles passed in", spec2);
}
@Test
public void testWithAllelesPassedIn() {
WalkerTest.WalkerTestSpec spec1 = new WalkerTest.WalkerTestSpec(
baseCommand + " --genotyping_mode GENOTYPE_GIVEN_ALLELES -B:alleles,vcf " + validationDataLocation + "allelesForUG.vcf -I " + validationDataLocation + "pilot2_daughters.chr20.10k-11k.bam -o %s -L 20:10,000,000-10,025,000", 1,
Arrays.asList("bcb02e2a969edfbd290b9ec22f1a5884"));
executeTest("test MultiSample Pilot2 with alleles passed in", spec1);
WalkerTest.WalkerTestSpec spec2 = new WalkerTest.WalkerTestSpec(
baseCommand + " --output_mode EMIT_ALL_SITES --genotyping_mode GENOTYPE_GIVEN_ALLELES -B:alleles,vcf " + validationDataLocation + "allelesForUG.vcf -I " + validationDataLocation + "pilot2_daughters.chr20.10k-11k.bam -o %s -L 20:10,000,000-10,025,000", 1,
Arrays.asList("f1ff29ac1c79c76fcb6c290b39bc3a18"));
executeTest("test MultiSample Pilot2 with alleles passed in", spec2);
}
@Test
public void testSingleSamplePilot2() {
WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
baseCommand + " -I " + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.SLX.bam -o %s -glm SNP -L 1:10,000,000-10,100,000", 1,
Arrays.asList("a7f59c32f63e8ca4c3ffe468c51fbaa2"));
executeTest("test SingleSample Pilot2", spec);
}
// --------------------------------------------------------------------------------------------------------------
//
// testing compressed output
//
// --------------------------------------------------------------------------------------------------------------
private final static String COMPRESSED_OUTPUT_MD5 = "92be4e11ee4660b67b32ae466d0651b0";
@Test
public void testCompressedOutput() {
WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
baseCommand + " -I " + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.SLX.bam -o %s -L 1:10,000,000-10,100,000", 1,
Arrays.asList("gz"), Arrays.asList(COMPRESSED_OUTPUT_MD5));
executeTest("test compressed output", spec);
}
// todo -- fixme
// @Test
// public void testCompressedOutputParallel() {
// WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
// baseCommand + " -I " + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.SLX.bam -o %s -L 1:10,000,000-10,100,000 -nt 4", 1,
// Arrays.asList("gz"), Arrays.asList(COMPRESSED_OUTPUT_MD5));
// executeTest("testCompressedOutput-nt4", spec);
// }
// --------------------------------------------------------------------------------------------------------------
//
// testing parallelization
//
// --------------------------------------------------------------------------------------------------------------
@Test
public void testParallelization() {
// Note that we need to turn off any randomization for this to work, so no downsampling and no annotations
String md5 = "f56fdf5c6a2db85031a3cece37e12a56";
WalkerTest.WalkerTestSpec spec1 = new WalkerTest.WalkerTestSpec(
baseCommand + " -dt NONE -G none -I " + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.SLX.bam -o %s -L 1:10,000,000-10,075,000", 1,
Arrays.asList(md5));
executeTest("test parallelization (single thread)", spec1);
GenomeAnalysisEngine.resetRandomGenerator();
WalkerTest.WalkerTestSpec spec2 = new WalkerTest.WalkerTestSpec(
baseCommand + " -dt NONE -G none -I " + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.SLX.bam -o %s -L 1:10,000,000-10,075,000 -nt 2", 1,
Arrays.asList(md5));
executeTest("test parallelization (2 threads)", spec2);
GenomeAnalysisEngine.resetRandomGenerator();
WalkerTest.WalkerTestSpec spec3 = new WalkerTest.WalkerTestSpec(
baseCommand + " -dt NONE -G none -I " + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.SLX.bam -o %s -L 1:10,000,000-10,075,000 -nt 4", 1,
Arrays.asList(md5));
executeTest("test parallelization (4 threads)", spec3);
}
// --------------------------------------------------------------------------------------------------------------
//
// testing parameters
//
// --------------------------------------------------------------------------------------------------------------
@Test
public void testCallingParameters() {
HashMap<String, String> e = new HashMap<String, String>();
e.put( "--min_base_quality_score 26", "e74b0f3c3977f383645e82ae76034932" );
e.put( "--min_mapping_quality_score 26", "5f08d9e052bdb04a2a5ee78db349dde9" );
e.put( "--p_nonref_model GRID_SEARCH", "2f1350f76a571d28cd06e59ea6dffe4b" );
for ( Map.Entry<String, String> entry : e.entrySet() ) {
WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
baseCommand + " -I " + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.SLX.bam -o %s -L 1:10,000,000-10,010,000 " + entry.getKey(), 1,
Arrays.asList(entry.getValue()));
executeTest(String.format("test calling parameter[%s]", entry.getKey()), spec);
}
}
@Test
public void testOutputParameter() {
HashMap<String, String> e = new HashMap<String, String>();
e.put( "-sites_only", "63b76c4d26edf8cbb5bd91dafc81fee1" );
e.put( "--output_mode EMIT_ALL_CONFIDENT_SITES", "5bf0268945d953377ea3a811b20ff1bc" );
e.put( "--output_mode EMIT_ALL_SITES", "a1730ea5ae5e1aa57d85d9d2372facc8" );
for ( Map.Entry<String, String> entry : e.entrySet() ) {
WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
baseCommand + " -I " + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.SLX.bam -o %s -L 1:10,000,000-10,010,000 " + entry.getKey(), 1,
Arrays.asList(entry.getValue()));
executeTest(String.format("testParameter[%s]", entry.getKey()), spec);
}
}
@Test
public void testConfidence() {
WalkerTest.WalkerTestSpec spec1 = new WalkerTest.WalkerTestSpec(
baseCommand + " -I " + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.SLX.bam -o %s -L 1:10,000,000-10,010,000 -stand_call_conf 10 ", 1,
Arrays.asList("5f08d9e052bdb04a2a5ee78db349dde9"));
executeTest("test confidence 1", spec1);
WalkerTest.WalkerTestSpec spec2 = new WalkerTest.WalkerTestSpec(
baseCommand + " -I " + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.SLX.bam -o %s -L 1:10,000,000-10,010,000 -stand_emit_conf 10 ", 1,
Arrays.asList("0d0bbfd08d1ce35ec1c007ba0f8dfe37"));
executeTest("test confidence 2", spec2);
}
// --------------------------------------------------------------------------------------------------------------
//
// testing heterozygosity
//
// --------------------------------------------------------------------------------------------------------------
@Test
public void testHeterozyosity() {
HashMap<Double, String> e = new HashMap<Double, String>();
e.put( 0.01, "9ed7893a36b27d5e63b6ee021918a4dd" );
e.put( 1.0 / 1850, "533bd796d2345a00536bf3164c4f75e1" );
for ( Map.Entry<Double, String> entry : e.entrySet() ) {
WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
baseCommand + " -I " + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.SLX.bam -o %s -L 1:10,000,000-10,100,000 --heterozygosity " + entry.getKey(), 1,
Arrays.asList(entry.getValue()));
executeTest(String.format("test heterozyosity[%s]", entry.getKey()), spec);
}
}
// --------------------------------------------------------------------------------------------------------------
//
// testing calls with SLX, 454, and SOLID data
//
// --------------------------------------------------------------------------------------------------------------
@Test
public void testMultiTechnologies() {
WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
baseCommand +
" -I " + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.allTechs.bam" +
" -o %s" +
" -L 1:10,000,000-10,100,000",
1,
Arrays.asList("1cdc0a1a40495cd17461280a1a37d429"));
executeTest(String.format("test multiple technologies"), spec);
}
// --------------------------------------------------------------------------------------------------------------
//
// testing calls with BAQ
//
// --------------------------------------------------------------------------------------------------------------
@Test
public void testCallingWithBAQ() {
WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
baseCommand +
" -I " + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.allTechs.bam" +
" -o %s" +
" -L 1:10,000,000-10,100,000" +
" -baq CALCULATE_AS_NECESSARY",
1,
Arrays.asList("940b42d14378e41d45e5e25a9b5aaebc"));
executeTest(String.format("test calling with BAQ"), spec);
}
// --------------------------------------------------------------------------------------------------------------
//
// testing indel caller
//
// --------------------------------------------------------------------------------------------------------------
// Basic indel testing with SLX data
@Test
public void testSimpleIndels() {
WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
baseCommand +
" -I " + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.SLX.bam" +
" -o %s" +
" -glm INDEL" +
" -L 1:10,000,000-10,500,000",
1,
Arrays.asList("d4c15c60ffefe754d83e1164e78f2b6a"));
executeTest(String.format("test indel caller in SLX"), spec);
}
// Basic indel testing with SLX data
@Test
public void testIndelsWithLowMinAlleleCnt() {
WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
baseCommand +
" -I " + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.SLX.bam" +
" -o %s" +
" -glm INDEL -minIndelCnt 1" +
" -L 1:10,000,000-10,100,000",
1,
Arrays.asList("599220ba0cc5d8a32e4952fca85fd080"));
executeTest(String.format("test indel caller in SLX witn low min allele count"), spec);
}
@Test
public void testMultiTechnologyIndels() {
WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
baseCommand +
" -I " + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.allTechs.bam" +
" -o %s" +
" -glm INDEL" +
" -L 1:10,000,000-10,500,000",
1,
Arrays.asList("4c8c2ac4e024f70779465fb14c5d8c8a"));
executeTest(String.format("test indel calling, multiple technologies"), spec);
}
// todo - feature not yet fully working with indels
//@Test
public void testWithIndelAllelesPassedIn() {
WalkerTest.WalkerTestSpec spec1 = new WalkerTest.WalkerTestSpec(
baseCommand + " --genotyping_mode GENOTYPE_GIVEN_ALLELES -B:alleles,vcf " + validationDataLocation + "indelAllelesForUG.vcf -I " + validationDataLocation +
"pilot2_daughters.chr20.10k-11k.bam -o %s -L 20:10,000,000-10,100,000 -glm INDEL", 1,
Arrays.asList("e95c545b8ae06f0721f260125cfbe1f0"));
executeTest("test MultiSample Pilot2 indels with alleles passed in", spec1);
WalkerTest.WalkerTestSpec spec2 = new WalkerTest.WalkerTestSpec(
baseCommand + " --output_mode EMIT_ALL_SITES --genotyping_mode GENOTYPE_GIVEN_ALLELES -B:alleles,vcf "
+ validationDataLocation + "indelAllelesForUG.vcf -I " + validationDataLocation +
"pilot2_daughters.chr20.10k-11k.bam -o %s -L 20:10,000,000-10,100,000 -glm INDEL", 1,
Arrays.asList("6c96d76b9bc3aade0c768d7c657ae210"));
executeTest("test MultiSample Pilot2 indels with alleles passed in", spec2);
}
}
| java/test/org/broadinstitute/sting/gatk/walkers/genotyper/UnifiedGenotyperIntegrationTest.java | package org.broadinstitute.sting.gatk.walkers.genotyper;
import org.broadinstitute.sting.WalkerTest;
import org.broadinstitute.sting.gatk.GenomeAnalysisEngine;
import org.testng.annotations.Test;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
// ********************************************************************************** //
// Note that this class also serves as an integration test for the VariantAnnotator! //
// ********************************************************************************** //
public class UnifiedGenotyperIntegrationTest extends WalkerTest {
private final static String baseCommand = "-T UnifiedGenotyper -R " + b36KGReference + " -NO_HEADER";
// --------------------------------------------------------------------------------------------------------------
//
// testing normal calling
//
// --------------------------------------------------------------------------------------------------------------
@Test
public void testMultiSamplePilot1() {
WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
baseCommand + " -I " + validationDataLocation + "low_coverage_CEU.chr1.10k-11k.bam -o %s -L 1:10,022,000-10,025,000", 1,
Arrays.asList("9895541f0395ddb9977abb7d8274831e"));
executeTest("test MultiSample Pilot1", spec);
}
@Test
public void testMultiSamplePilot2AndRecallingWithAlleles() {
String md5 = "2a8461e846a437ddcac9f1be185d0a4b";
WalkerTest.WalkerTestSpec spec1 = new WalkerTest.WalkerTestSpec(
baseCommand + " -I " + validationDataLocation + "pilot2_daughters.chr20.10k-11k.bam -o %s -L 20:10,000,000-10,050,000", 1,
Arrays.asList(md5));
List<File> result = executeTest("test MultiSample Pilot2", spec1).getFirst();
GenomeAnalysisEngine.resetRandomGenerator();
WalkerTest.WalkerTestSpec spec2 = new WalkerTest.WalkerTestSpec(
baseCommand + " --genotyping_mode GENOTYPE_GIVEN_ALLELES -B:alleles,vcf " + result.get(0).getAbsolutePath() + " -I " + validationDataLocation + "pilot2_daughters.chr20.10k-11k.bam -o %s -L 20:10,000,000-10,050,000", 1,
Arrays.asList(md5));
executeTest("test MultiSample Pilot2 with alleles passed in", spec2);
}
@Test
public void testWithAllelesPassedIn() {
WalkerTest.WalkerTestSpec spec1 = new WalkerTest.WalkerTestSpec(
baseCommand + " --genotyping_mode GENOTYPE_GIVEN_ALLELES -B:alleles,vcf " + validationDataLocation + "allelesForUG.vcf -I " + validationDataLocation + "pilot2_daughters.chr20.10k-11k.bam -o %s -L 20:10,000,000-10,025,000", 1,
Arrays.asList("bcb02e2a969edfbd290b9ec22f1a5884"));
executeTest("test MultiSample Pilot2 with alleles passed in", spec1);
WalkerTest.WalkerTestSpec spec2 = new WalkerTest.WalkerTestSpec(
baseCommand + " --output_mode EMIT_ALL_SITES --genotyping_mode GENOTYPE_GIVEN_ALLELES -B:alleles,vcf " + validationDataLocation + "allelesForUG.vcf -I " + validationDataLocation + "pilot2_daughters.chr20.10k-11k.bam -o %s -L 20:10,000,000-10,025,000", 1,
Arrays.asList("f1ff29ac1c79c76fcb6c290b39bc3a18"));
executeTest("test MultiSample Pilot2 with alleles passed in", spec2);
}
@Test
public void testSingleSamplePilot2() {
WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
baseCommand + " -I " + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.SLX.bam -o %s -glm SNP -L 1:10,000,000-10,100,000", 1,
Arrays.asList("a7f59c32f63e8ca4c3ffe468c51fbaa2"));
executeTest("test SingleSample Pilot2", spec);
}
// --------------------------------------------------------------------------------------------------------------
//
// testing compressed output
//
// --------------------------------------------------------------------------------------------------------------
private final static String COMPRESSED_OUTPUT_MD5 = "92be4e11ee4660b67b32ae466d0651b0";
@Test
public void testCompressedOutput() {
WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
baseCommand + " -I " + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.SLX.bam -o %s -L 1:10,000,000-10,100,000", 1,
Arrays.asList("gz"), Arrays.asList(COMPRESSED_OUTPUT_MD5));
executeTest("test compressed output", spec);
}
// todo -- fixme
// @Test
// public void testCompressedOutputParallel() {
// WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
// baseCommand + " -I " + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.SLX.bam -o %s -L 1:10,000,000-10,100,000 -nt 4", 1,
// Arrays.asList("gz"), Arrays.asList(COMPRESSED_OUTPUT_MD5));
// executeTest("testCompressedOutput-nt4", spec);
// }
// --------------------------------------------------------------------------------------------------------------
//
// testing parallelization
//
// --------------------------------------------------------------------------------------------------------------
@Test (enabled = false)
public void testParallelization() {
String md5 = "7e51ad5e76b8440cbf26373df83a8f41";
WalkerTest.WalkerTestSpec spec1 = new WalkerTest.WalkerTestSpec(
baseCommand + " -I " + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.SLX.bam -o %s -L 1:10,000,000-10,075,000", 1,
Arrays.asList(md5));
executeTest("test parallelization (single thread)", spec1);
GenomeAnalysisEngine.resetRandomGenerator();
WalkerTest.WalkerTestSpec spec2 = new WalkerTest.WalkerTestSpec(
baseCommand + " -I " + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.SLX.bam -o %s -L 1:10,000,000-10,075,000 -nt 2", 1,
Arrays.asList(md5));
executeTest("test parallelization (2 threads)", spec2);
GenomeAnalysisEngine.resetRandomGenerator();
WalkerTest.WalkerTestSpec spec3 = new WalkerTest.WalkerTestSpec(
baseCommand + " -I " + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.SLX.bam -o %s -L 1:10,000,000-10,075,000 -nt 4", 1,
Arrays.asList(md5));
executeTest("test parallelization (4 threads)", spec3);
}
// --------------------------------------------------------------------------------------------------------------
//
// testing parameters
//
// --------------------------------------------------------------------------------------------------------------
@Test
public void testCallingParameters() {
HashMap<String, String> e = new HashMap<String, String>();
e.put( "--min_base_quality_score 26", "e74b0f3c3977f383645e82ae76034932" );
e.put( "--min_mapping_quality_score 26", "5f08d9e052bdb04a2a5ee78db349dde9" );
e.put( "--p_nonref_model GRID_SEARCH", "2f1350f76a571d28cd06e59ea6dffe4b" );
for ( Map.Entry<String, String> entry : e.entrySet() ) {
WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
baseCommand + " -I " + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.SLX.bam -o %s -L 1:10,000,000-10,010,000 " + entry.getKey(), 1,
Arrays.asList(entry.getValue()));
executeTest(String.format("test calling parameter[%s]", entry.getKey()), spec);
}
}
@Test
public void testOutputParameter() {
HashMap<String, String> e = new HashMap<String, String>();
e.put( "-sites_only", "63b76c4d26edf8cbb5bd91dafc81fee1" );
e.put( "--output_mode EMIT_ALL_CONFIDENT_SITES", "5bf0268945d953377ea3a811b20ff1bc" );
e.put( "--output_mode EMIT_ALL_SITES", "a1730ea5ae5e1aa57d85d9d2372facc8" );
for ( Map.Entry<String, String> entry : e.entrySet() ) {
WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
baseCommand + " -I " + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.SLX.bam -o %s -L 1:10,000,000-10,010,000 " + entry.getKey(), 1,
Arrays.asList(entry.getValue()));
executeTest(String.format("testParameter[%s]", entry.getKey()), spec);
}
}
@Test
public void testConfidence() {
WalkerTest.WalkerTestSpec spec1 = new WalkerTest.WalkerTestSpec(
baseCommand + " -I " + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.SLX.bam -o %s -L 1:10,000,000-10,010,000 -stand_call_conf 10 ", 1,
Arrays.asList("5f08d9e052bdb04a2a5ee78db349dde9"));
executeTest("test confidence 1", spec1);
WalkerTest.WalkerTestSpec spec2 = new WalkerTest.WalkerTestSpec(
baseCommand + " -I " + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.SLX.bam -o %s -L 1:10,000,000-10,010,000 -stand_emit_conf 10 ", 1,
Arrays.asList("0d0bbfd08d1ce35ec1c007ba0f8dfe37"));
executeTest("test confidence 2", spec2);
}
// --------------------------------------------------------------------------------------------------------------
//
// testing heterozygosity
//
// --------------------------------------------------------------------------------------------------------------
@Test
public void testHeterozyosity() {
HashMap<Double, String> e = new HashMap<Double, String>();
e.put( 0.01, "9ed7893a36b27d5e63b6ee021918a4dd" );
e.put( 1.0 / 1850, "533bd796d2345a00536bf3164c4f75e1" );
for ( Map.Entry<Double, String> entry : e.entrySet() ) {
WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
baseCommand + " -I " + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.SLX.bam -o %s -L 1:10,000,000-10,100,000 --heterozygosity " + entry.getKey(), 1,
Arrays.asList(entry.getValue()));
executeTest(String.format("test heterozyosity[%s]", entry.getKey()), spec);
}
}
// --------------------------------------------------------------------------------------------------------------
//
// testing calls with SLX, 454, and SOLID data
//
// --------------------------------------------------------------------------------------------------------------
@Test
public void testMultiTechnologies() {
WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
baseCommand +
" -I " + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.allTechs.bam" +
" -o %s" +
" -L 1:10,000,000-10,100,000",
1,
Arrays.asList("1cdc0a1a40495cd17461280a1a37d429"));
executeTest(String.format("test multiple technologies"), spec);
}
// --------------------------------------------------------------------------------------------------------------
//
// testing calls with BAQ
//
// --------------------------------------------------------------------------------------------------------------
@Test
public void testCallingWithBAQ() {
WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
baseCommand +
" -I " + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.allTechs.bam" +
" -o %s" +
" -L 1:10,000,000-10,100,000" +
" -baq CALCULATE_AS_NECESSARY",
1,
Arrays.asList("940b42d14378e41d45e5e25a9b5aaebc"));
executeTest(String.format("test calling with BAQ"), spec);
}
// --------------------------------------------------------------------------------------------------------------
//
// testing indel caller
//
// --------------------------------------------------------------------------------------------------------------
// Basic indel testing with SLX data
@Test
public void testSimpleIndels() {
WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
baseCommand +
" -I " + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.SLX.bam" +
" -o %s" +
" -glm INDEL" +
" -L 1:10,000,000-10,500,000",
1,
Arrays.asList("d4c15c60ffefe754d83e1164e78f2b6a"));
executeTest(String.format("test indel caller in SLX"), spec);
}
// Basic indel testing with SLX data
@Test
public void testIndelsWithLowMinAlleleCnt() {
WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
baseCommand +
" -I " + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.SLX.bam" +
" -o %s" +
" -glm INDEL -minIndelCnt 1" +
" -L 1:10,000,000-10,100,000",
1,
Arrays.asList("599220ba0cc5d8a32e4952fca85fd080"));
executeTest(String.format("test indel caller in SLX witn low min allele count"), spec);
}
@Test
public void testMultiTechnologyIndels() {
WalkerTest.WalkerTestSpec spec = new WalkerTest.WalkerTestSpec(
baseCommand +
" -I " + validationDataLocation + "NA12878.1kg.p2.chr1_10mb_11_mb.allTechs.bam" +
" -o %s" +
" -glm INDEL" +
" -L 1:10,000,000-10,500,000",
1,
Arrays.asList("4c8c2ac4e024f70779465fb14c5d8c8a"));
executeTest(String.format("test indel calling, multiple technologies"), spec);
}
// Indel parallelization
//@Test
// todo - test fails because for some reason when including -nt we get "PASS" instead of . in filter fields
public void testIndelParallelization() {
String md5 = "599220ba0cc5d8a32e4952fca85fd080";
WalkerTest.WalkerTestSpec spec1 = new WalkerTest.WalkerTestSpec(
baseCommand + " -I " + validationDataLocation +
"NA12878.1kg.p2.chr1_10mb_11_mb.SLX.bam -glm INDEL -o %s -L 1:10,000,000-10,100,000", 1,
Arrays.asList(md5));
executeTest("test indel caller parallelization (single thread)", spec1);
WalkerTest.WalkerTestSpec spec2 = new WalkerTest.WalkerTestSpec(
baseCommand + " -I " + validationDataLocation +
"NA12878.1kg.p2.chr1_10mb_11_mb.SLX.bam -glm INDEL -o %s -L 1:10,000,000-10,100,000 -nt 2", 1,
Arrays.asList(md5));
executeTest("test indel caller parallelization (2 threads)", spec2);
WalkerTest.WalkerTestSpec spec3 = new WalkerTest.WalkerTestSpec(
baseCommand + " -I " + validationDataLocation +
"NA12878.1kg.p2.chr1_10mb_11_mb.SLX.bam -glm INDEL -o %s -L 1:10,000,000-10,100,000 -nt 4", 1,
Arrays.asList(md5));
executeTest("test indel caller parallelization (4 threads)", spec3);
}
// todo - feature not yet fully working with indels
//@Test
public void testWithIndelAllelesPassedIn() {
WalkerTest.WalkerTestSpec spec1 = new WalkerTest.WalkerTestSpec(
baseCommand + " --genotyping_mode GENOTYPE_GIVEN_ALLELES -B:alleles,vcf " + validationDataLocation + "indelAllelesForUG.vcf -I " + validationDataLocation +
"pilot2_daughters.chr20.10k-11k.bam -o %s -L 20:10,000,000-10,100,000 -glm INDEL", 1,
Arrays.asList("e95c545b8ae06f0721f260125cfbe1f0"));
executeTest("test MultiSample Pilot2 indels with alleles passed in", spec1);
WalkerTest.WalkerTestSpec spec2 = new WalkerTest.WalkerTestSpec(
baseCommand + " --output_mode EMIT_ALL_SITES --genotyping_mode GENOTYPE_GIVEN_ALLELES -B:alleles,vcf "
+ validationDataLocation + "indelAllelesForUG.vcf -I " + validationDataLocation +
"pilot2_daughters.chr20.10k-11k.bam -o %s -L 20:10,000,000-10,100,000 -glm INDEL", 1,
Arrays.asList("6c96d76b9bc3aade0c768d7c657ae210"));
executeTest("test MultiSample Pilot2 indels with alleles passed in", spec2);
}
}
| Re-enabling multi-threaded integration tests. To make this work, downsampling and annotations are disabled for this test so that we don't have randomization issues for it based on which shards get executed first.
git-svn-id: 4561c0a8f080806b19201efb9525134c00b76d40@5597 348d0f76-0448-11de-a6fe-93d51630548a
| java/test/org/broadinstitute/sting/gatk/walkers/genotyper/UnifiedGenotyperIntegrationTest.java | Re-enabling multi-threaded integration tests. To make this work, downsampling and annotations are disabled for this test so that we don't have randomization issues for it based on which shards get executed first. |
|
Java | mit | 25c1334d0e08a40c8d3c62e3374b31b2048903ab | 0 | oblador/react-native-keychain,oblador/react-native-keychain,oblador/react-native-keychain,oblador/react-native-keychain,oblador/react-native-keychain,oblador/react-native-keychain | package com.oblador.keychain;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.security.KeyPairGeneratorSpec;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;
import android.support.annotation.NonNull;
import android.util.Base64;
import android.util.Log;
import com.facebook.android.crypto.keychain.AndroidConceal;
import com.facebook.android.crypto.keychain.SharedPrefsBackedKeyChain;
import com.facebook.crypto.Crypto;
import com.facebook.crypto.CryptoConfig;
import com.facebook.crypto.Entity;
import com.facebook.crypto.keychain.KeyChain;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import com.oblador.keychain.exceptions.CryptoFailedException;
import com.oblador.keychain.exceptions.EmptyParameterException;
import com.oblador.keychain.exceptions.KeyStoreAccessException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Calendar;
import java.util.Date;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.security.auth.x500.X500Principal;
public class KeychainModule extends ReactContextBaseJavaModule {
public static final String E_EMPTY_PARAMETERS = "E_EMPTY_PARAMETERS";
public static final String E_CRYPTO_FAILED = "E_CRYPTO_FAILED";
public static final String E_UNSUPPORTED_KEYSTORE = "E_UNSUPPORTED_KEYSTORE";
public static final String E_KEYSTORE_ACCESS_ERROR = "E_KEYSTORE_ACCESS_ERROR";
public static final String KEYCHAIN_MODULE = "RNKeychainManager";
public static final String KEYCHAIN_DATA = "RN_KEYCHAIN";
public static final String EMPTY_STRING = "";
public static final String DEFAULT_ALIAS = "RN_KEYCHAIN_DEFAULT_ALIAS";
public static final int YEARS_TO_LAST = 15;
public static final String LEGACY_DELIMITER = ":";
public static final String DELIMITER = "_";
public static final String KEYSTORE_TYPE = "AndroidKeyStore";
public static final String RSA_ALGORITHM = "RSA/ECB/PKCS1Padding";
private final Crypto crypto;
private final SharedPreferences prefs;
private class ResultSet {
final String service;
final byte[] decryptedUsername;
final byte[] decryptedPassword;
public ResultSet(String service, byte[] decryptedUsername, byte[] decryptedPassword) {
this.service = service;
this.decryptedUsername = decryptedUsername;
this.decryptedPassword = decryptedPassword;
}
}
@Override
public String getName() {
return KEYCHAIN_MODULE;
}
public KeychainModule(ReactApplicationContext reactContext) {
super(reactContext);
KeyChain keyChain = new SharedPrefsBackedKeyChain(getReactApplicationContext(), CryptoConfig.KEY_256);
crypto = AndroidConceal.get().createDefaultCrypto(keyChain);
prefs = this.getReactApplicationContext().getSharedPreferences(KEYCHAIN_DATA, Context.MODE_PRIVATE);
}
@ReactMethod
public void setGenericPasswordForOptions(String service, String username, String password, Promise promise) {
try {
setGenericPasswordForOptions(service, username, password);
// Clean legacy values (if any)
resetGenericPasswordForOptionsLegacy(service);
promise.resolve("KeychainModule saved the data");
} catch (EmptyParameterException e) {
Log.e(KEYCHAIN_MODULE, e.getMessage());
promise.reject(E_EMPTY_PARAMETERS, e);
} catch (CryptoFailedException e) {
Log.e(KEYCHAIN_MODULE, e.getMessage());
promise.reject(E_CRYPTO_FAILED, e);
} catch (KeyStoreException e) {
Log.e(KEYCHAIN_MODULE, e.getMessage());
promise.reject(E_UNSUPPORTED_KEYSTORE, e);
} catch (KeyStoreAccessException e) {
Log.e(KEYCHAIN_MODULE, e.getMessage());
promise.reject(E_KEYSTORE_ACCESS_ERROR, e);
}
}
private void setGenericPasswordForOptions(String service, String username, String password) throws EmptyParameterException, CryptoFailedException, KeyStoreException, KeyStoreAccessException {
if (username == null || username.isEmpty() || password == null || password.isEmpty()) {
throw new EmptyParameterException("you passed empty or null username/password");
}
service = service == null ? DEFAULT_ALIAS : service;
KeyStore keyStore = getKeyStoreAndLoad();
try {
if (!keyStore.containsAlias(service)) {
AlgorithmParameterSpec spec;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
spec = new KeyGenParameterSpec.Builder(
service,
KeyProperties.PURPOSE_DECRYPT | KeyProperties.PURPOSE_ENCRYPT)
.setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
.setRandomizedEncryptionRequired(true)
//.setUserAuthenticationRequired(true) // Will throw InvalidAlgorithmParameterException if there is no fingerprint enrolled on the device
.setKeySize(2048)
.build();
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Calendar cal = Calendar.getInstance();
Date start = cal.getTime();
cal.add(Calendar.YEAR, YEARS_TO_LAST);
Date end = cal.getTime();
spec = new KeyPairGeneratorSpec.Builder(this.getReactApplicationContext())
.setAlias(service)
.setSubject(new X500Principal("CN=domain.com, O=security"))
.setSerialNumber(BigInteger.ONE)
.setStartDate(start)
.setEndDate(end)
.setKeySize(2048)
.build();
} else {
throw new CryptoFailedException("Unsupported Android SDK " + Build.VERSION.SDK_INT);
}
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", KEYSTORE_TYPE);
generator.initialize(spec);
generator.generateKeyPair();
}
PublicKey publicKey = keyStore.getCertificate(service).getPublicKey();
String encryptedUsername = encryptString(publicKey, service, username);
String encryptedPassword = encryptString(publicKey, service, password);
SharedPreferences.Editor prefsEditor = prefs.edit();
prefsEditor.putString(service + DELIMITER + "u", encryptedUsername);
prefsEditor.putString(service + DELIMITER + "p", encryptedPassword);
prefsEditor.apply();
Log.d(KEYCHAIN_MODULE, "saved the data");
} catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | NoSuchProviderException e) {
throw new CryptoFailedException("Could not encrypt data for service " + service, e);
}
}
private String encryptString(PublicKey publicKey, String service, String value) throws CryptoFailedException {
try {
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher);
cipherOutputStream.write(value.getBytes("UTF-8"));
cipherOutputStream.close();
byte[] encryptedBytes = outputStream.toByteArray();
return Base64.encodeToString(encryptedBytes, Base64.DEFAULT);
} catch (Exception e) {
throw new CryptoFailedException("Could not encrypt value for service " + service, e);
}
}
@ReactMethod
public void getGenericPasswordForOptions(String service, Promise promise) {
String originalService = service;
service = service == null ? DEFAULT_ALIAS : service;
try {
byte[] recuser = getBytesFromPrefs(service, DELIMITER + "u");
byte[] recpass = getBytesFromPrefs(service, DELIMITER + "p");
if (recuser == null || recpass == null) {
// Check if the values are stored using the LEGACY_DELIMITER and thus encrypted using FaceBook's Conceal
ResultSet resultSet = getGenericPasswordForOptionsUsingConceal(originalService);
if (resultSet != null) {
// Store the values using the new delimiter and the KeyStore
setGenericPasswordForOptions(
originalService,
new String(resultSet.decryptedUsername, Charset.forName("UTF-8")),
new String(resultSet.decryptedUsername, Charset.forName("UTF-8")));
// Remove the legacy value(s)
resetGenericPasswordForOptionsLegacy(originalService);
recuser = resultSet.decryptedUsername;
recpass = resultSet.decryptedPassword;
} else {
Log.e(KEYCHAIN_MODULE, "no keychain entry found for service: " + service);
promise.resolve(false);
return;
}
}
KeyStore keyStore = getKeyStoreAndLoad();
PrivateKey privateKey = (PrivateKey) keyStore.getKey(service, null);
byte[] decryptedUsername = decryptBytes(privateKey, recuser);
byte[] decryptedPassword = decryptBytes(privateKey, recpass);
WritableMap credentials = Arguments.createMap();
credentials.putString("service", service);
credentials.putString("username", new String(decryptedUsername, Charset.forName("UTF-8")));
credentials.putString("password", new String(decryptedPassword, Charset.forName("UTF-8")));
promise.resolve(credentials);
} catch (KeyStoreException e) {
Log.e(KEYCHAIN_MODULE, e.getMessage());
promise.reject(E_UNSUPPORTED_KEYSTORE, e);
} catch (KeyStoreAccessException e) {
Log.e(KEYCHAIN_MODULE, e.getMessage());
promise.reject(E_KEYSTORE_ACCESS_ERROR, e);
} catch (UnrecoverableKeyException | NoSuchAlgorithmException | CryptoFailedException e) {
Log.e(KEYCHAIN_MODULE, e.getMessage());
promise.reject(E_CRYPTO_FAILED, e);
} catch (EmptyParameterException e) {
Log.e(KEYCHAIN_MODULE, e.getMessage());
promise.reject(E_EMPTY_PARAMETERS, e);
}
}
private byte[] decryptBytes(PrivateKey privateKey, byte[] bytes) throws CryptoFailedException {
try {
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
CipherInputStream cipherInputStream = new CipherInputStream(
new ByteArrayInputStream(bytes), cipher);
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
while (true) {
int n = cipherInputStream.read(buffer, 0, buffer.length);
if (n <= 0) {
break;
}
output.write(buffer, 0, n);
}
return output.toByteArray();
} catch (Exception e) {
throw new CryptoFailedException("Could not decrypt bytes", e);
}
}
private ResultSet getGenericPasswordForOptionsUsingConceal(String service) throws CryptoFailedException {
if (!crypto.isAvailable()) {
throw new CryptoFailedException("Crypto is missing");
}
service = service == null ? EMPTY_STRING : service;
byte[] recuser = getBytesFromPrefs(service, LEGACY_DELIMITER + "u");
byte[] recpass = getBytesFromPrefs(service, LEGACY_DELIMITER + "p");
if (recuser == null || recpass == null) {
return null;
}
Entity userentity = Entity.create(KEYCHAIN_DATA + ":" + service + "user");
Entity pwentity = Entity.create(KEYCHAIN_DATA + ":" + service + "pass");
try {
byte[] decryptedUsername = crypto.decrypt(recuser, userentity);
byte[] decryptedPassword = crypto.decrypt(recpass, pwentity);
return new ResultSet(service, decryptedUsername, decryptedPassword);
} catch (Exception e) {
throw new CryptoFailedException("Decryption failed for service " + service, e);
}
}
private byte[] getBytesFromPrefs(String service, String prefix) {
String key = service + prefix;
String value = prefs.getString(service + prefix, null);
if (value != null) {
return Base64.decode(value, Base64.DEFAULT);
}
return null;
}
@ReactMethod
public void resetGenericPasswordForOptions(String service, Promise promise) {
try {
resetGenericPasswordForOptions(service);
promise.resolve(true);
} catch (KeyStoreException e) {
Log.e(KEYCHAIN_MODULE, e.getMessage());
promise.reject(E_UNSUPPORTED_KEYSTORE, e);
} catch (KeyStoreAccessException e) {
Log.e(KEYCHAIN_MODULE, e.getMessage());
promise.reject(E_KEYSTORE_ACCESS_ERROR, e);
}
}
private void resetGenericPasswordForOptions(String service) throws KeyStoreException, KeyStoreAccessException {
service = service == null ? DEFAULT_ALIAS : service;
KeyStore keyStore = getKeyStoreAndLoad();
if (keyStore.containsAlias(service)) {
keyStore.deleteEntry(service);
}
SharedPreferences.Editor prefsEditor = prefs.edit();
if (prefs.contains(service + DELIMITER + "u")) {
prefsEditor.remove(service + DELIMITER + "u");
prefsEditor.remove(service + DELIMITER + "p");
prefsEditor.apply();
}
}
private void resetGenericPasswordForOptionsLegacy(String service) throws KeyStoreException, KeyStoreAccessException {
service = service == null ? EMPTY_STRING : service;
SharedPreferences.Editor prefsEditor = prefs.edit();
if (prefs.contains(service + LEGACY_DELIMITER + "u")) {
prefsEditor.remove(service + LEGACY_DELIMITER + "u");
prefsEditor.remove(service + LEGACY_DELIMITER + "p");
prefsEditor.apply();
}
}
@ReactMethod
public void setInternetCredentialsForServer(@NonNull String server, String username, String password, ReadableMap unusedOptions, Promise promise) {
setGenericPasswordForOptions(server, username, password, promise);
}
@ReactMethod
public void getInternetCredentialsForServer(@NonNull String server, ReadableMap unusedOptions, Promise promise) {
getGenericPasswordForOptions(server, promise);
}
@ReactMethod
public void resetInternetCredentialsForServer(@NonNull String server, ReadableMap unusedOptions, Promise promise) {
resetGenericPasswordForOptions(server, promise);
}
private KeyStore getKeyStore() throws KeyStoreException {
return KeyStore.getInstance(KEYSTORE_TYPE);
}
private KeyStore getKeyStoreAndLoad() throws KeyStoreException, KeyStoreAccessException {
try {
KeyStore keyStore = getKeyStore();
keyStore.load(null);
return keyStore;
} catch (NoSuchAlgorithmException | CertificateException | IOException e) {
throw new KeyStoreAccessException("Could not access KeyStore", e);
}
}
} | android/src/main/java/com/oblador/keychain/KeychainModule.java | package com.oblador.keychain;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.security.KeyPairGeneratorSpec;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;
import android.support.annotation.NonNull;
import android.util.Base64;
import android.util.Log;
import com.facebook.android.crypto.keychain.AndroidConceal;
import com.facebook.android.crypto.keychain.SharedPrefsBackedKeyChain;
import com.facebook.crypto.Crypto;
import com.facebook.crypto.CryptoConfig;
import com.facebook.crypto.Entity;
import com.facebook.crypto.keychain.KeyChain;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import com.oblador.keychain.exceptions.CryptoFailedException;
import com.oblador.keychain.exceptions.EmptyParameterException;
import com.oblador.keychain.exceptions.KeyStoreAccessException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Calendar;
import java.util.Date;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.security.auth.x500.X500Principal;
public class KeychainModule extends ReactContextBaseJavaModule {
public static final String E_EMPTY_PARAMETERS = "E_EMPTY_PARAMETERS";
public static final String E_CRYPTO_FAILED = "E_CRYPTO_FAILED";
public static final String E_UNSUPPORTED_KEYSTORE = "E_UNSUPPORTED_KEYSTORE";
public static final String E_KEYSTORE_ACCESS_ERROR = "E_KEYSTORE_ACCESS_ERROR";
public static final String KEYCHAIN_MODULE = "RNKeychainManager";
public static final String KEYCHAIN_DATA = "RN_KEYCHAIN";
public static final String DEFAULT_ALIAS = "RN_KEYCHAIN_DEFAULT_ALIAS";
public static final int YEARS_TO_LAST = 15;
public static final String LEGACY_DELIMITER = ":";
public static final String DELIMITER = "_";
public static final String KEYSTORE_TYPE = "AndroidKeyStore";
public static final String RSA_ALGORITHM = "RSA/ECB/PKCS1Padding";
private final Crypto crypto;
private final SharedPreferences prefs;
private class ResultSet {
final String service;
final byte[] decryptedUsername;
final byte[] decryptedPassword;
public ResultSet(String service, byte[] decryptedUsername, byte[] decryptedPassword) {
this.service = service;
this.decryptedUsername = decryptedUsername;
this.decryptedPassword = decryptedPassword;
}
}
@Override
public String getName() {
return KEYCHAIN_MODULE;
}
public KeychainModule(ReactApplicationContext reactContext) {
super(reactContext);
KeyChain keyChain = new SharedPrefsBackedKeyChain(getReactApplicationContext(), CryptoConfig.KEY_256);
crypto = AndroidConceal.get().createDefaultCrypto(keyChain);
prefs = this.getReactApplicationContext().getSharedPreferences(KEYCHAIN_DATA, Context.MODE_PRIVATE);
}
@ReactMethod
public void setGenericPasswordForOptions(String service, String username, String password, Promise promise) {
try {
setGenericPasswordForOptions(service, username, password);
// Clean legacy values (if any)
resetGenericPasswordForOptionsLegacy(service);
promise.resolve("KeychainModule saved the data");
} catch (EmptyParameterException e) {
Log.e(KEYCHAIN_MODULE, e.getMessage());
promise.reject(E_EMPTY_PARAMETERS, e);
} catch (CryptoFailedException e) {
Log.e(KEYCHAIN_MODULE, e.getMessage());
promise.reject(E_CRYPTO_FAILED, e);
} catch (KeyStoreException e) {
Log.e(KEYCHAIN_MODULE, e.getMessage());
promise.reject(E_UNSUPPORTED_KEYSTORE, e);
} catch (KeyStoreAccessException e) {
Log.e(KEYCHAIN_MODULE, e.getMessage());
promise.reject(E_KEYSTORE_ACCESS_ERROR, e);
}
}
private void setGenericPasswordForOptions(String service, String username, String password) throws EmptyParameterException, CryptoFailedException, KeyStoreException, KeyStoreAccessException {
if (username == null || username.isEmpty() || password == null || password.isEmpty()) {
throw new EmptyParameterException("you passed empty or null username/password");
}
service = service == null ? DEFAULT_ALIAS : service;
KeyStore keyStore = getKeyStoreAndLoad();
try {
if (!keyStore.containsAlias(service)) {
AlgorithmParameterSpec spec;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
spec = new KeyGenParameterSpec.Builder(
service,
KeyProperties.PURPOSE_DECRYPT | KeyProperties.PURPOSE_ENCRYPT)
.setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
.setRandomizedEncryptionRequired(true)
//.setUserAuthenticationRequired(true) // Will throw InvalidAlgorithmParameterException if there is no fingerprint enrolled on the device
.setKeySize(2048)
.build();
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Calendar cal = Calendar.getInstance();
Date start = cal.getTime();
cal.add(Calendar.YEAR, YEARS_TO_LAST);
Date end = cal.getTime();
spec = new KeyPairGeneratorSpec.Builder(this.getReactApplicationContext())
.setAlias(service)
.setSubject(new X500Principal("CN=domain.com, O=security"))
.setSerialNumber(BigInteger.ONE)
.setStartDate(start)
.setEndDate(end)
.setKeySize(2048)
.build();
} else {
throw new CryptoFailedException("Unsupported Android SDK " + Build.VERSION.SDK_INT);
}
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", KEYSTORE_TYPE);
generator.initialize(spec);
generator.generateKeyPair();
}
PublicKey publicKey = keyStore.getCertificate(service).getPublicKey();
String encryptedUsername = encryptString(publicKey, service, username);
String encryptedPassword = encryptString(publicKey, service, password);
SharedPreferences.Editor prefsEditor = prefs.edit();
prefsEditor.putString(service + DELIMITER + "u", encryptedUsername);
prefsEditor.putString(service + DELIMITER + "p", encryptedPassword);
prefsEditor.apply();
Log.d(KEYCHAIN_MODULE, "saved the data");
} catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | NoSuchProviderException e) {
throw new CryptoFailedException("Could not encrypt data for service " + service, e);
}
}
private String encryptString(PublicKey publicKey, String service, String value) throws CryptoFailedException {
try {
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher);
cipherOutputStream.write(value.getBytes("UTF-8"));
cipherOutputStream.close();
byte[] encryptedBytes = outputStream.toByteArray();
return Base64.encodeToString(encryptedBytes, Base64.DEFAULT);
} catch (Exception e) {
throw new CryptoFailedException("Could not encrypt value for service " + service, e);
}
}
@ReactMethod
public void getGenericPasswordForOptions(String service, Promise promise) {
service = service == null ? DEFAULT_ALIAS : service;
try {
byte[] recuser = getBytesFromPrefs(service, DELIMITER + "u");
byte[] recpass = getBytesFromPrefs(service, DELIMITER + "p");
if (recuser == null || recpass == null) {
// Check if the values are stored using the LEGACY_DELIMITER and thus encrypted using FaceBook's Conceal
ResultSet resultSet = getGenericPasswordForOptionsUsingConceal(service);
if (resultSet != null) {
// Store the values using the new delimiter and the KeyStore
setGenericPasswordForOptions(
resultSet.service,
new String(resultSet.decryptedUsername, Charset.forName("UTF-8")),
new String(resultSet.decryptedUsername, Charset.forName("UTF-8")));
// Remove the legacy value(s)
resetGenericPasswordForOptionsLegacy(service);
recuser = resultSet.decryptedUsername;
recpass = resultSet.decryptedPassword;
} else {
Log.e(KEYCHAIN_MODULE, "no keychain entry found for service: " + service);
promise.resolve(false);
return;
}
}
KeyStore keyStore = getKeyStoreAndLoad();
PrivateKey privateKey = (PrivateKey) keyStore.getKey(service, null);
byte[] decryptedUsername = decryptBytes(privateKey, recuser);
byte[] decryptedPassword = decryptBytes(privateKey, recpass);
WritableMap credentials = Arguments.createMap();
credentials.putString("service", service);
credentials.putString("username", new String(decryptedUsername, Charset.forName("UTF-8")));
credentials.putString("password", new String(decryptedPassword, Charset.forName("UTF-8")));
promise.resolve(credentials);
} catch (KeyStoreException e) {
Log.e(KEYCHAIN_MODULE, e.getMessage());
promise.reject(E_UNSUPPORTED_KEYSTORE, e);
} catch (KeyStoreAccessException e) {
Log.e(KEYCHAIN_MODULE, e.getMessage());
promise.reject(E_KEYSTORE_ACCESS_ERROR, e);
} catch (UnrecoverableKeyException | NoSuchAlgorithmException | CryptoFailedException e) {
Log.e(KEYCHAIN_MODULE, e.getMessage());
promise.reject(E_CRYPTO_FAILED, e);
} catch (EmptyParameterException e) {
Log.e(KEYCHAIN_MODULE, e.getMessage());
promise.reject(E_EMPTY_PARAMETERS, e);
}
}
private byte[] decryptBytes(PrivateKey privateKey, byte[] bytes) throws CryptoFailedException {
try {
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
CipherInputStream cipherInputStream = new CipherInputStream(
new ByteArrayInputStream(bytes), cipher);
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
while (true) {
int n = cipherInputStream.read(buffer, 0, buffer.length);
if (n <= 0) {
break;
}
output.write(buffer, 0, n);
}
return output.toByteArray();
} catch (Exception e) {
throw new CryptoFailedException("Could not decrypt bytes", e);
}
}
private ResultSet getGenericPasswordForOptionsUsingConceal(String service) throws CryptoFailedException {
if (!crypto.isAvailable()) {
throw new CryptoFailedException("Crypto is missing");
}
service = service == null ? DEFAULT_ALIAS : service;
byte[] recuser = getBytesFromPrefs(service, LEGACY_DELIMITER + "u");
byte[] recpass = getBytesFromPrefs(service, LEGACY_DELIMITER + "p");
if (recuser == null || recpass == null) {
return null;
}
Entity userentity = Entity.create(KEYCHAIN_DATA + ":" + service + "user");
Entity pwentity = Entity.create(KEYCHAIN_DATA + ":" + service + "pass");
try {
byte[] decryptedUsername = crypto.decrypt(recuser, userentity);
byte[] decryptedPassword = crypto.decrypt(recpass, pwentity);
return new ResultSet(service, decryptedUsername, decryptedPassword);
} catch (Exception e) {
throw new CryptoFailedException("Decryption failed for service " + service, e);
}
}
private byte[] getBytesFromPrefs(String service, String prefix) {
String key = service + prefix;
String value = prefs.getString(service + prefix, null);
if (value != null) {
return Base64.decode(value, Base64.DEFAULT);
}
return null;
}
@ReactMethod
public void resetGenericPasswordForOptions(String service, Promise promise) {
try {
resetGenericPasswordForOptions(service);
promise.resolve(true);
} catch (KeyStoreException e) {
Log.e(KEYCHAIN_MODULE, e.getMessage());
promise.reject(E_UNSUPPORTED_KEYSTORE, e);
} catch (KeyStoreAccessException e) {
Log.e(KEYCHAIN_MODULE, e.getMessage());
promise.reject(E_KEYSTORE_ACCESS_ERROR, e);
}
}
private void resetGenericPasswordForOptions(String service) throws KeyStoreException, KeyStoreAccessException {
service = service == null ? DEFAULT_ALIAS : service;
KeyStore keyStore = getKeyStoreAndLoad();
if (keyStore.containsAlias(service)) {
keyStore.deleteEntry(service);
}
SharedPreferences.Editor prefsEditor = prefs.edit();
if (prefs.contains(service + DELIMITER + "u")) {
prefsEditor.remove(service + DELIMITER + "u");
prefsEditor.remove(service + DELIMITER + "p");
prefsEditor.apply();
}
}
private void resetGenericPasswordForOptionsLegacy(String service) throws KeyStoreException, KeyStoreAccessException {
service = service == null ? DEFAULT_ALIAS : service;
SharedPreferences.Editor prefsEditor = prefs.edit();
if (prefs.contains(service + LEGACY_DELIMITER + "u")) {
prefsEditor.remove(service + LEGACY_DELIMITER + "u");
prefsEditor.remove(service + LEGACY_DELIMITER + "p");
prefsEditor.apply();
}
}
@ReactMethod
public void setInternetCredentialsForServer(@NonNull String server, String username, String password, ReadableMap unusedOptions, Promise promise) {
setGenericPasswordForOptions(server, username, password, promise);
}
@ReactMethod
public void getInternetCredentialsForServer(@NonNull String server, ReadableMap unusedOptions, Promise promise) {
getGenericPasswordForOptions(server, promise);
}
@ReactMethod
public void resetInternetCredentialsForServer(@NonNull String server, ReadableMap unusedOptions, Promise promise) {
resetGenericPasswordForOptions(server, promise);
}
private KeyStore getKeyStore() throws KeyStoreException {
return KeyStore.getInstance(KEYSTORE_TYPE);
}
private KeyStore getKeyStoreAndLoad() throws KeyStoreException, KeyStoreAccessException {
try {
KeyStore keyStore = getKeyStore();
keyStore.load(null);
return keyStore;
} catch (NoSuchAlgorithmException | CertificateException | IOException e) {
throw new KeyStoreAccessException("Could not access KeyStore", e);
}
}
} | Fixing issue where legacy values stored with a NULL service would not be migrated.
Signed-off-by: Pelle Stenild Coltau <[email protected]>
| android/src/main/java/com/oblador/keychain/KeychainModule.java | Fixing issue where legacy values stored with a NULL service would not be migrated. |
|
Java | mit | 20e2728fd6711da9fe2d9080f4209101a2eff0ea | 0 | digibib/ls.ext,digibib/ls.ext,digibib/ls.ext,digibib/ls.ext | package no.deichman.services.resources;
import java.net.URI;
import java.net.URISyntaxException;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.OPTIONS;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import com.hp.hpl.jena.rdf.model.Model;
import no.deichman.services.kohaadapter.KohaAdapter;
import no.deichman.services.repository.Repository;
import no.deichman.services.service.Service;
import no.deichman.services.service.ServiceDefault;
import no.deichman.services.uridefaults.BaseURI;
import no.deichman.services.uridefaults.BaseURIDefault;
import no.deichman.services.utils.CORSProvider;
import no.deichman.services.utils.JSONLD;
import no.deichman.services.utils.MimeType;
@Path("/publication")
public class PublicationResource {
private static final String MIME_JSONLD = MimeType.JSONLD;
private static final String ENCODING_UTF8 = "; charset=utf-8";
private final Service service;
private BaseURI baseURI;
private JSONLD jsonld;
private CORSProvider cors;
public PublicationResource() {
super();
baseURI = new BaseURIDefault();
jsonld = new JSONLD(baseURI);
service = new ServiceDefault(baseURI);
cors = new CORSProvider();
}
public PublicationResource(KohaAdapter kohaAdapter, Repository repository, BaseURI b) {
super();
ServiceDefault serviceDefault = new ServiceDefault(b);
serviceDefault.setKohaAdapter(kohaAdapter);
serviceDefault.setRepository(repository);
service = serviceDefault;
baseURI = b;
jsonld = new JSONLD(b);
cors = new CORSProvider();
}
@POST
@Consumes(MIME_JSONLD)
public Response createPublication(String publication) throws URISyntaxException {
String workId = service.createPublication(publication);
URI location = new URI(workId);
return Response.created(location)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "POST")
.header("Access-Control-Expose-Headers", "Location")
.allow("OPTIONS")
.build();
}
@GET
@Path("/{publicationId: [a-zA-Z0-9_]+}")
@Produces(MIME_JSONLD + ENCODING_UTF8)
public Response getPublicationJSON(@PathParam("publicationId") String publicationId) {
Model model = service.retrievePublicationById(publicationId);
if (model.isEmpty()) {
throw new NotFoundException();
}
return Response.ok().entity(jsonld.getJson(model))
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET")
.allow("OPTIONS")
.build();
}
@DELETE
@Path("/{publicationId: [a-zA-Z0-9_]+}")
public Response deletePublication(@PathParam("publicationId") String publicationId) {
Model model = service.retrievePublicationById(publicationId);
if (model.isEmpty()) {
throw new NotFoundException();
}
service.deletePublication(model);
return Response.noContent().header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET")
.allow("OPTIONS")
.build();
}
@OPTIONS
public Response corsPublicationBase(@HeaderParam("Access-Control-Request-Headers") String reqHeader) {
return cors.makeCORSResponse(Response.ok(), reqHeader);
}
@OPTIONS
@Path("/{publicationId: [a-zA-Z0-9_]+}")
public Response corsPublicationId(@HeaderParam("Access-Control-Request-Headers") String reqHeader) {
return cors.makeCORSResponse(Response.ok(), reqHeader);
}
}
| redef/services/src/main/java/no/deichman/services/resources/PublicationResource.java | package no.deichman.services.resources;
import java.net.URI;
import java.net.URISyntaxException;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.OPTIONS;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import com.hp.hpl.jena.rdf.model.Model;
import no.deichman.services.kohaadapter.KohaAdapter;
import no.deichman.services.repository.Repository;
import no.deichman.services.service.Service;
import no.deichman.services.service.ServiceDefault;
import no.deichman.services.uridefaults.BaseURI;
import no.deichman.services.uridefaults.BaseURIDefault;
import no.deichman.services.utils.CORSProvider;
import no.deichman.services.utils.JSONLD;
import no.deichman.services.utils.MimeType;
@Path("/publication")
public class PublicationResource {
private static final String MIME_JSONLD = MimeType.JSONLD;
private static final String ENCODING_UTF8 = "; charset=utf-8";
private final Service service;
private BaseURI baseURI;
private JSONLD jsonld;
private CORSProvider cors;
public PublicationResource() {
super();
baseURI = new BaseURIDefault();
jsonld = new JSONLD(baseURI);
service = new ServiceDefault(baseURI);
cors = new CORSProvider();
}
public PublicationResource(KohaAdapter kohaAdapter, Repository repository, BaseURI b) {
super();
ServiceDefault serviceDefault = new ServiceDefault(b);
serviceDefault.setKohaAdapter(kohaAdapter);
serviceDefault.setRepository(repository);
service = serviceDefault;
baseURI = b;
jsonld = new JSONLD(b);
cors = new CORSProvider();
}
@POST
@Consumes(MIME_JSONLD)
public Response createPublication(String publication) throws URISyntaxException {
String workId = service.createPublication(publication);
URI location = new URI(workId);
return Response.created(location)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "POST")
.header("Access-Control-Expose-Headers", "Location")
.allow("OPTIONS")
.build();
}
@GET
@Path("/{publicationId: [a-zA-Z0-9_]+}")
@Produces(MIME_JSONLD + ENCODING_UTF8)
public Response getPublicationJSON(@PathParam("publicationId") String publicationId) {
Model model = service.retrievePublicationById(publicationId);
if (model.isEmpty()) {
throw new NotFoundException();
}
return Response.ok().entity(jsonld.getJson(model))
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET")
.allow("OPTIONS")
.build();
}
@DELETE
@Path("/{publicationId: [a-zA-Z0-9_]+}")
public Response deletePublication(@PathParam("publicationId") String publicationId) {
Model model = service.retrievePublicationById(publicationId);
if (model.isEmpty()) {
throw new NotFoundException();
}
service.deletePublication(model);
return Response.noContent().header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET")
.allow("OPTIONS")
.build();
}
@OPTIONS
public Response corsPublicationBase(String reqHeader) {
Response response = cors.makeCORSResponse(Response.ok(), reqHeader);
return response;
}
@OPTIONS
@Path("/{publicationId: [a-zA-Z0-9_]+}")
public Response corsPublicationId(@HeaderParam("Access-Control-Request-Headers") String reqHeader) {
return cors.makeCORSResponse(Response.ok(), reqHeader);
}
}
| Include missing @HeaderParam
| redef/services/src/main/java/no/deichman/services/resources/PublicationResource.java | Include missing @HeaderParam |
|
Java | mit | a58ad74042be8353d7a537ac047adfb15f1c2a63 | 0 | LenKagamine/aMEba | import java.awt.*;
import javax.imageio.ImageIO;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
public abstract class Organism extends MapObject{
protected double speed,angle;
protected int health;
protected DNA dna;
protected int species;
private long start;
public Organism(Map map,double x,double y,int species){
super(map,x,y);
this.species = species;
try{
if (species == 0)
img = ImageIO.read(getClass().getResourceAsStream("buggy.png"));
else if (species == 1)
img = ImageIO.read(getClass().getResourceAsStream("gooey.png"));
else if (species == 2)
img = ImageIO.read(getClass().getResourceAsStream("aqua.png"));
else if (species == 3)
img = ImageIO.read(getClass().getResourceAsStream("biter.png"));
else if (species == 4)
img = ImageIO.read(getClass().getResourceAsStream("diatom.png"));
else if (species == 8)
img = ImageIO.read(getClass().getResourceAsStream("triangle.png"));
} catch(Exception e){
e.printStackTrace();
}
width = img.getWidth();
height = img.getHeight();
boxwidth = width/2;
boxheight = height/2;
speed = Math.random()*3+2;
angle = Math.random()*360;
start = System.currentTimeMillis();
}
public void update(){
long elapsed = System.currentTimeMillis();
if(elapsed-start>1000){
start = System.currentTimeMillis();
health -= dna.getHunger();
}
}
public void draw(Graphics g){
mapx = map.getX();
mapy = map.getY();
g.setColor(Color.black);
g.drawRect((int)(x-mapx-width/2),(int)(y-mapy-height/2),width,height);
g.setColor(Color.red);
g.drawRect((int)(x-mapx-boxwidth/2),(int)(y-mapy-boxheight/2),boxwidth,boxheight);
AffineTransform tx = AffineTransform.getRotateInstance(angle, width/2, height/2);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
g.drawImage(op.filter(img,null),(int)(x-mapx-width/2),(int)(y-mapy-height/2),null);
g.setColor(Color.white);
g.setFont(new Font("Tahoma", Font.BOLD, 20));
g.drawString((int)(dna.getStat(7))+"",(int)(x-mapx-width/2),(int)(y-mapy+height/2));
}
public void hit(int dmg){
health = Math.max(health-dmg,0);
}
public int getSpecies(){
return species;
}
public boolean isDead(){
return health<=0;
}
public DNA getDNA(){
return dna;
}
public void consume(DNA dna2){
if (species == 8)
dna.playerDebuff(dna2);
dna.add(dna2);
this.health += dna2.getHealth()/2;
if(this.health >= dna.getHealth()) this.health = dna.getHealth();
this.speed = this.dna.getSpeed();
}
public void consume(Berry berry){
health += berry.recoverHealth();
if(this.health >= dna.getHealth()) this.health = dna.getHealth();
}
}
| Organism.java | import java.awt.*;
import javax.imageio.ImageIO;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
public abstract class Organism extends MapObject{
protected double speed,angle;
protected int health;
protected DNA dna;
protected int species;
private long start;
public Organism(Map map,double x,double y,int species){
super(map,x,y);
this.species = species;
try{
if (species == 0)
img = ImageIO.read(getClass().getResourceAsStream("buggy.png"));
else if (species == 1)
img = ImageIO.read(getClass().getResourceAsStream("gooey.png"));
else if (species == 2)
img = ImageIO.read(getClass().getResourceAsStream("aqua.png"));
else if (species == 3)
img = ImageIO.read(getClass().getResourceAsStream("biter.png"));
else if (species == 4)
img = ImageIO.read(getClass().getResourceAsStream("diatom.png"));
else if (species == 8)
img = ImageIO.read(getClass().getResourceAsStream("triangle.png"));
} catch(Exception e){
e.printStackTrace();
}
width = img.getWidth();
height = img.getHeight();
boxwidth = width/2;
boxheight = height/2;
speed = Math.random()*3+2;
angle = Math.random()*360;
start = System.currentTimeMillis();
}
public void update(){
long elapsed = System.currentTimeMillis();
if(elapsed-start>1000){
start = System.currentTimeMillis();
health -= dna.getHunger();
}
}
public void draw(Graphics g){
mapx = map.getX();
mapy = map.getY();
g.setColor(Color.black);
g.drawRect((int)(x-mapx-width/2),(int)(y-mapy-height/2),width,height);
g.setColor(Color.red);
g.drawRect((int)(x-mapx-boxwidth/2),(int)(y-mapy-boxheight/2),boxwidth,boxheight);
AffineTransform tx = AffineTransform.getRotateInstance(angle, width/2, height/2);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
g.drawImage(op.filter(img,null),(int)(x-mapx-width/2),(int)(y-mapy-height/2),null);
}
public void hit(int dmg){
health = Math.max(health-dmg,0);
}
public int getSpecies(){
return species;
}
public boolean isDead(){
return health<=0;
}
public DNA getDNA(){
return dna;
}
public void consume(DNA dna2){
dna.add(dna2);
this.health += dna2.getHealth()/2;
if(this.health >= dna.getHealth()) this.health = dna.getHealth();
this.speed = this.dna.getSpeed();
}
public void consume(Berry berry){
health += berry.recoverHealth();
if(this.health >= dna.getHealth()) this.health = dna.getHealth();
}
}
| Player debuff and shows level | Organism.java | Player debuff and shows level |
|
Java | mit | b3a80a3e02139eaa8992e8593dfb778cd7bfc892 | 0 | mitallast/netty-queue,mitallast/netty-queue,mitallast/netty-queue,mitallast/netty-queue,mitallast/netty-queue | package org.mitallast.queue.raft.log;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import org.junit.Assert;
import org.junit.Test;
import org.mitallast.queue.common.BaseTest;
import org.mitallast.queue.common.stream.StreamInput;
import org.mitallast.queue.common.stream.StreamOutput;
import org.mitallast.queue.common.stream.Streamable;
import org.mitallast.queue.raft.Term;
import org.mitallast.queue.raft.cluster.StableClusterConfiguration;
import org.mitallast.queue.raft.protocol.LogEntry;
import org.mitallast.queue.raft.protocol.RaftSnapshot;
import org.mitallast.queue.raft.protocol.RaftSnapshotMetadata;
import java.io.IOException;
import java.util.Optional;
public abstract class ReplicatedLogTest extends BaseTest {
protected final Term term0 = new Term(0);
protected final Term term1 = new Term(1);
protected final Term term = term1;
protected final LogEntry entry1 = new LogEntry(new AppendWord("word"), term, 1);
protected final LogEntry entry2 = new LogEntry(new AppendWord("word"), term, 2);
protected final LogEntry entry3 = new LogEntry(new AppendWord("word"), term, 3);
protected final StableClusterConfiguration clusterConf = new StableClusterConfiguration(0, ImmutableSet.of());
protected final RaftSnapshot snapshot1 = new RaftSnapshot(new RaftSnapshotMetadata(term, 1, clusterConf), null);
protected final RaftSnapshot snapshot2 = new RaftSnapshot(new RaftSnapshotMetadata(term, 2, clusterConf), null);
protected final RaftSnapshot snapshot3 = new RaftSnapshot(new RaftSnapshotMetadata(term, 3, clusterConf), null);
protected final LogEntry snapshotEntry1 = new LogEntry(snapshot1, term, 1);
protected final LogEntry snapshotEntry2 = new LogEntry(snapshot2, term, 2);
protected final LogEntry snapshotEntry3 = new LogEntry(snapshot3, term, 3);
protected abstract ReplicatedLog log() throws Exception;
@Test
public void testAddFirstEntry() throws Exception {
Assert.assertEquals(ImmutableList.of(entry1), log().append(entry1).entries());
}
@Test
public void testAddSecondEntry() throws Exception {
Assert.assertEquals(ImmutableList.of(entry1, entry2), log().append(entry1).append(entry2).entries());
}
@Test
public void testMatchNextEntry() throws Exception {
Assert.assertEquals(ImmutableList.of(entry1, entry3), log().append(entry1).append(entry3).entries());
}
@Test
public void testReturn1NextIndexIfEmpty() throws Exception {
Assert.assertEquals(1, log().nextIndex());
}
@Test
public void testReturn2NextIndexIfContainsEntry1() throws Exception {
Assert.assertEquals(2, log().append(entry1).nextIndex());
}
@Test
public void testReturn3NextIndexIfContainsEntry2() throws Exception {
Assert.assertEquals(3, log().append(entry1).append(entry2).nextIndex());
}
@Test
public void testReturn4NextIndexIfContainsEntry3() throws Exception {
Assert.assertEquals(4, log().append(entry1).append(entry2).append(entry3).nextIndex());
}
@Test
public void testPrevIndex0IfEmpty() throws Exception {
Assert.assertEquals(0, log().prevIndex());
}
@Test
public void testPrevIndex0IfContainsEntry1() throws Exception {
Assert.assertEquals(0, log().append(entry1).prevIndex());
}
@Test
public void testPrevIndex1IfContainsEntry2() throws Exception {
Assert.assertEquals(1, log().append(entry1).append(entry2).prevIndex());
}
@Test
public void testPrevIndex2IfContainsEntry3() throws Exception {
Assert.assertEquals(2, log().append(entry1).append(entry2).append(entry3).prevIndex());
}
@Test
public void testNextEntriesLowerBound0() throws Exception {
Assert.assertEquals(ImmutableList.of(entry1, entry2, entry3), log().append(entry1).append(entry2).append(entry3).entriesBatchFrom(1));
}
@Test
public void testNextEntriesLowerBound1() throws Exception {
Assert.assertEquals(ImmutableList.of(entry2, entry3), log().append(entry1).append(entry2).append(entry3).entriesBatchFrom(2));
}
@Test
public void testNextEntriesLowerBound2() throws Exception {
Assert.assertEquals(ImmutableList.of(entry3), log().append(entry1).append(entry2).append(entry3).entriesBatchFrom(3));
}
@Test
public void testNextEntriesLowerBound3() throws Exception {
Assert.assertEquals(ImmutableList.of(), log().append(entry1).append(entry2).append(entry3).entriesBatchFrom(4));
}
@Test
public void testContainsMatchingEntry0IfEmpty() throws Exception {
Assert.assertTrue(log().containsMatchingEntry(term0, 0));
}
@Test
public void testContainsMatchingEntry1IfEmpty() throws Exception {
Assert.assertFalse(log().containsMatchingEntry(term0, 1));
}
@Test
public void testContainsMatchingEntry3IfNotEmpty() throws Exception {
Assert.assertTrue(log().append(entry1).append(entry2).append(entry3).containsMatchingEntry(term, 3));
}
@Test
public void testContainsMatchingEntry2IfNotEmpty() throws Exception {
Assert.assertTrue(log().append(entry1).append(entry2).append(entry3).containsMatchingEntry(term, 2));
}
@Test
public void testContainsMatchingEntry1IfNotEmpty() throws Exception {
Assert.assertTrue(log().append(entry1).append(entry2).append(entry3).containsMatchingEntry(term, 1));
}
@Test
public void testBetween1and1empty() throws Exception {
Assert.assertEquals(ImmutableList.of(entry1), log().append(entry1).append(entry2).append(entry3).slice(1, 1));
}
@Test
public void testBetween1and2entry2() throws Exception {
Assert.assertEquals(ImmutableList.of(entry1, entry2), log().append(entry1).append(entry2).append(entry3).slice(1, 2));
}
@Test
public void testBetween1and3entry3() throws Exception {
Assert.assertEquals(ImmutableList.of(entry1, entry2, entry3), log().append(entry1).append(entry2).append(entry3).slice(1, 3));
}
@Test
public void testCommitIndexIfEmpty() throws Exception {
Assert.assertEquals(0, log().committedIndex());
}
@Test
public void testNotContainsEntry1ifEmpty() throws Exception {
Assert.assertFalse(log().containsEntryAt(1));
}
@Test
public void testContainsEntry1ifEntry1() throws Exception {
Assert.assertTrue(log().append(entry1).containsEntryAt(1));
}
@Test
public void testCompactLog() throws Exception {
ReplicatedLog compacted = log().append(entry1).append(entry2).append(entry3).compactedWith(snapshot3);
Assert.assertEquals(ImmutableList.of(snapshotEntry3), compacted.entries());
Assert.assertTrue(compacted.hasSnapshot());
Assert.assertEquals(snapshot3, compacted.snapshot());
}
@Test
public void testContainsMatchingEntryAfterCompaction1() throws Exception {
ReplicatedLog compacted = log().append(entry1).compactedWith(snapshot1);
Assert.assertTrue(compacted.containsMatchingEntry(term, 1));
}
@Test
public void testContainsMatchingEntryAfterCompaction2() throws Exception {
ReplicatedLog compacted = log().append(entry1).append(entry2).compactedWith(snapshot2);
Assert.assertTrue(compacted.containsMatchingEntry(term, 2));
}
@Test
public void testContainsMatchingEntryAfterCompaction3() throws Exception {
ReplicatedLog compacted = log().append(entry1).append(entry2).append(entry3).compactedWith(snapshot3);
Assert.assertTrue(compacted.containsMatchingEntry(term, 3));
}
@Test
public void testContainsEntry1AfterCompaction1() throws Exception {
ReplicatedLog compacted = log().append(entry1).append(entry2).append(entry3).compactedWith(snapshot1);
Assert.assertEquals(ImmutableList.of(snapshotEntry1, entry2, entry3), compacted.entries());
Assert.assertTrue(compacted.containsEntryAt(1));
Assert.assertTrue(compacted.containsEntryAt(2));
Assert.assertTrue(compacted.containsEntryAt(3));
}
@Test
public void testContainsEntry1AfterCompaction2() throws Exception {
ReplicatedLog compacted = log().append(entry1).append(entry2).append(entry3).compactedWith(snapshot2);
Assert.assertEquals(ImmutableList.of(snapshotEntry2, entry3), compacted.entries());
Assert.assertFalse(compacted.containsEntryAt(1));
Assert.assertTrue(compacted.containsEntryAt(2));
Assert.assertTrue(compacted.containsEntryAt(3));
}
@Test
public void testContainsEntry1AfterCompaction3() throws Exception {
ReplicatedLog compacted = log().append(entry1).append(entry2).append(entry3).compactedWith(snapshot3);
Assert.assertEquals(ImmutableList.of(snapshotEntry3), compacted.entries());
Assert.assertFalse(compacted.containsEntryAt(1));
Assert.assertFalse(compacted.containsEntryAt(2));
Assert.assertTrue(compacted.containsEntryAt(3));
}
@Test
public void testLastTermAfterCompaction1() throws Exception {
ReplicatedLog compacted = log().append(entry1).compactedWith(snapshot1);
Assert.assertEquals(Optional.of(term), compacted.lastTerm());
}
@Test
public void testLastTermAfterCompaction2() throws Exception {
ReplicatedLog compacted = log().append(entry1).append(entry2).compactedWith(snapshot1);
Assert.assertEquals(Optional.of(term), compacted.lastTerm());
}
@Test
public void testLastTermAfterCompaction3() throws Exception {
ReplicatedLog compacted = log().append(entry1).append(entry2).append(entry3).compactedWith(snapshot1);
Assert.assertEquals(Optional.of(term), compacted.lastTerm());
}
@Test
public void testLastIndexAfterCompaction1() throws Exception {
ReplicatedLog compacted = log().append(entry1).compactedWith(snapshot1);
Assert.assertEquals(1, compacted.lastIndex());
}
@Test
public void testLastIndexAfterCompaction2() throws Exception {
ReplicatedLog compacted = log().append(entry1).append(entry2).compactedWith(snapshot2);
Assert.assertEquals(2, compacted.lastIndex());
}
@Test
public void testLastIndexAfterCompaction3() throws Exception {
ReplicatedLog compacted = log().append(entry1).append(entry2).append(entry3).compactedWith(snapshot3);
Assert.assertEquals(3, compacted.lastIndex());
}
@Test
public void testEntriesBatchFrom1AfterCompaction1() throws Exception {
ReplicatedLog compacted = log().append(entry1).append(entry2).append(entry3).compactedWith(snapshot1);
Assert.assertEquals(ImmutableList.of(snapshotEntry1, entry2, entry3), compacted.entriesBatchFrom(1));
}
@Test
public void testEntriesBatchFrom1AfterCompaction2() throws Exception {
ReplicatedLog compacted = log().append(entry1).append(entry2).append(entry3).compactedWith(snapshot1);
Assert.assertEquals(ImmutableList.of(entry2, entry3), compacted.entriesBatchFrom(2));
}
@Test
public void testEntriesBatchFrom1AfterCompaction3() throws Exception {
ReplicatedLog compacted = log().append(entry1).append(entry2).append(entry3).compactedWith(snapshot1);
Assert.assertEquals(ImmutableList.of(entry3), compacted.entriesBatchFrom(3));
}
public class AppendWord implements Streamable {
private final String word;
public AppendWord(StreamInput stream) throws IOException {
word = stream.readText();
}
public AppendWord(String word) {
this.word = word;
}
@Override
public void writeTo(StreamOutput stream) throws IOException {
stream.writeText(word);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AppendWord that = (AppendWord) o;
return word.equals(that.word);
}
@Override
public int hashCode() {
return word.hashCode();
}
}
}
| src/test/java/org/mitallast/queue/raft/log/ReplicatedLogTest.java | package org.mitallast.queue.raft.log;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import org.junit.Assert;
import org.junit.Test;
import org.mitallast.queue.common.BaseTest;
import org.mitallast.queue.common.stream.StreamInput;
import org.mitallast.queue.common.stream.StreamOutput;
import org.mitallast.queue.common.stream.Streamable;
import org.mitallast.queue.raft.Term;
import org.mitallast.queue.raft.cluster.StableClusterConfiguration;
import org.mitallast.queue.raft.protocol.LogEntry;
import org.mitallast.queue.raft.protocol.RaftSnapshot;
import org.mitallast.queue.raft.protocol.RaftSnapshotMetadata;
import java.io.IOException;
import java.util.Optional;
public abstract class ReplicatedLogTest extends BaseTest {
protected final Term term0 = new Term(0);
protected final Term term1 = new Term(1);
protected final Term term = term1;
protected final LogEntry entry1 = new LogEntry(new AppendWord("word"), term, 1);
protected final LogEntry entry2 = new LogEntry(new AppendWord("word"), term, 2);
protected final LogEntry entry3 = new LogEntry(new AppendWord("word"), term, 3);
protected final StableClusterConfiguration clusterConf = new StableClusterConfiguration(0, ImmutableSet.of());
protected final RaftSnapshot snapshot1 = new RaftSnapshot(new RaftSnapshotMetadata(term, 1, clusterConf), null);
protected final RaftSnapshot snapshot2 = new RaftSnapshot(new RaftSnapshotMetadata(term, 2, clusterConf), null);
protected final RaftSnapshot snapshot3 = new RaftSnapshot(new RaftSnapshotMetadata(term, 3, clusterConf), null);
protected final LogEntry snapshotEntry1 = new LogEntry(snapshot1, term, 1);
protected final LogEntry snapshotEntry2 = new LogEntry(snapshot2, term, 2);
protected final LogEntry snapshotEntry3 = new LogEntry(snapshot3, term, 3);
protected abstract ReplicatedLog log() throws Exception;
@Test
public void testAddFirstEntry() throws Exception {
Assert.assertEquals(ImmutableList.of(entry1), log().append(entry1).entries());
}
@Test
public void testAddSecondEntry() throws Exception {
Assert.assertEquals(ImmutableList.of(entry1, entry2), log().append(entry1).append(entry2).entries());
}
@Test
public void testMatchNextEntry() throws Exception {
Assert.assertEquals(ImmutableList.of(entry1, entry3), log().append(entry1).append(entry3).entries());
}
@Test
public void testReturn1NextIndexIfEmpty() throws Exception {
Assert.assertEquals(1, log().nextIndex());
}
@Test
public void testReturn2NextIndexIfContainsEntry1() throws Exception {
Assert.assertEquals(2, log().append(entry1).nextIndex());
}
@Test
public void testReturn3NextIndexIfContainsEntry2() throws Exception {
Assert.assertEquals(3, log().append(entry1).append(entry2).nextIndex());
}
@Test
public void testReturn4NextIndexIfContainsEntry3() throws Exception {
Assert.assertEquals(4, log().append(entry1).append(entry2).append(entry3).nextIndex());
}
@Test
public void testPrevIndex0IfEmpty() throws Exception {
Assert.assertEquals(0, log().prevIndex());
}
@Test
public void testPrevIndex0IfContainsEntry1() throws Exception {
Assert.assertEquals(0, log().append(entry1).prevIndex());
}
@Test
public void testPrevIndex1IfContainsEntry2() throws Exception {
Assert.assertEquals(1, log().append(entry1).append(entry2).prevIndex());
}
@Test
public void testPrevIndex2IfContainsEntry3() throws Exception {
Assert.assertEquals(2, log().append(entry1).append(entry2).append(entry3).prevIndex());
}
@Test
public void testNextEntriesLowerBound0() throws Exception {
Assert.assertEquals(ImmutableList.of(entry1, entry2, entry3), log().append(entry1).append(entry2).append(entry3).entriesBatchFrom(1));
}
@Test
public void testNextEntriesLowerBound1() throws Exception {
Assert.assertEquals(ImmutableList.of(entry2, entry3), log().append(entry1).append(entry2).append(entry3).entriesBatchFrom(2));
}
@Test
public void testNextEntriesLowerBound2() throws Exception {
Assert.assertEquals(ImmutableList.of(entry3), log().append(entry1).append(entry2).append(entry3).entriesBatchFrom(3));
}
@Test
public void testNextEntriesLowerBound3() throws Exception {
Assert.assertEquals(ImmutableList.of(), log().append(entry1).append(entry2).append(entry3).entriesBatchFrom(4));
}
@Test
public void testContrainsMatchingEntry0IfEmpty() throws Exception {
Assert.assertTrue(log().containsMatchingEntry(term0, 0));
}
@Test
public void testContrainsMatchingEntry1IfEmpty() throws Exception {
Assert.assertFalse(log().containsMatchingEntry(term0, 1));
}
@Test
public void testContrainsMatchingEntry3IfNotEmpty() throws Exception {
Assert.assertTrue(log().append(entry1).append(entry2).append(entry3).containsMatchingEntry(term, 3));
}
@Test
public void testContrainsMatchingEntry2IfNotEmpty() throws Exception {
Assert.assertTrue(log().append(entry1).append(entry2).append(entry3).containsMatchingEntry(term, 2));
}
@Test
public void testContrainsMatchingEntry1IfNotEmpty() throws Exception {
Assert.assertTrue(log().append(entry1).append(entry2).append(entry3).containsMatchingEntry(term, 1));
}
@Test
public void testBetween1and1empty() throws Exception {
Assert.assertEquals(ImmutableList.of(entry1), log().append(entry1).append(entry2).append(entry3).slice(1, 1));
}
@Test
public void testBetween1and2entry2() throws Exception {
Assert.assertEquals(ImmutableList.of(entry1, entry2), log().append(entry1).append(entry2).append(entry3).slice(1, 2));
}
@Test
public void testBetween1and3entry3() throws Exception {
Assert.assertEquals(ImmutableList.of(entry1, entry2, entry3), log().append(entry1).append(entry2).append(entry3).slice(1, 3));
}
@Test
public void testCommitIndexIfEmpty() throws Exception {
Assert.assertEquals(0, log().committedIndex());
}
@Test
public void testNotContainsEntry1ifEmpty() throws Exception {
Assert.assertFalse(log().containsEntryAt(1));
}
@Test
public void testContainsEntry1ifEntry1() throws Exception {
Assert.assertTrue(log().append(entry1).containsEntryAt(1));
}
@Test
public void testCompactLog() throws Exception {
ReplicatedLog compacted = log().append(entry1).append(entry2).append(entry3).compactedWith(snapshot3);
Assert.assertEquals(ImmutableList.of(snapshotEntry3), compacted.entries());
Assert.assertTrue(compacted.hasSnapshot());
Assert.assertEquals(snapshot3, compacted.snapshot());
}
@Test
public void testContainsMatchingEntryAfterCompaction1() throws Exception {
ReplicatedLog compacted = log().append(entry1).compactedWith(snapshot1);
Assert.assertTrue(compacted.containsMatchingEntry(term, 1));
}
@Test
public void testContainsMatchingEntryAfterCompaction2() throws Exception {
ReplicatedLog compacted = log().append(entry1).append(entry2).compactedWith(snapshot2);
Assert.assertTrue(compacted.containsMatchingEntry(term, 2));
}
@Test
public void testContainsMatchingEntryAfterCompaction3() throws Exception {
ReplicatedLog compacted = log().append(entry1).append(entry2).append(entry3).compactedWith(snapshot3);
Assert.assertTrue(compacted.containsMatchingEntry(term, 3));
}
@Test
public void testContainsEntry1AfterCompaction1() throws Exception {
ReplicatedLog compacted = log().append(entry1).append(entry2).append(entry3).compactedWith(snapshot1);
Assert.assertEquals(ImmutableList.of(snapshotEntry1, entry2, entry3), compacted.entries());
Assert.assertTrue(compacted.containsEntryAt(1));
Assert.assertTrue(compacted.containsEntryAt(2));
Assert.assertTrue(compacted.containsEntryAt(3));
}
@Test
public void testContainsEntry1AfterCompaction2() throws Exception {
ReplicatedLog compacted = log().append(entry1).append(entry2).append(entry3).compactedWith(snapshot2);
Assert.assertEquals(ImmutableList.of(snapshotEntry2, entry3), compacted.entries());
Assert.assertFalse(compacted.containsEntryAt(1));
Assert.assertTrue(compacted.containsEntryAt(2));
Assert.assertTrue(compacted.containsEntryAt(3));
}
@Test
public void testContainsEntry1AfterCompaction3() throws Exception {
ReplicatedLog compacted = log().append(entry1).append(entry2).append(entry3).compactedWith(snapshot3);
Assert.assertEquals(ImmutableList.of(snapshotEntry3), compacted.entries());
Assert.assertFalse(compacted.containsEntryAt(1));
Assert.assertFalse(compacted.containsEntryAt(2));
Assert.assertTrue(compacted.containsEntryAt(3));
}
@Test
public void testLastTermAfterCompaction1() throws Exception {
ReplicatedLog compacted = log().append(entry1).compactedWith(snapshot1);
Assert.assertEquals(Optional.of(term), compacted.lastTerm());
}
@Test
public void testLastTermAfterCompaction2() throws Exception {
ReplicatedLog compacted = log().append(entry1).append(entry2).compactedWith(snapshot1);
Assert.assertEquals(Optional.of(term), compacted.lastTerm());
}
@Test
public void testLastTermAfterCompaction3() throws Exception {
ReplicatedLog compacted = log().append(entry1).append(entry2).append(entry3).compactedWith(snapshot1);
Assert.assertEquals(Optional.of(term), compacted.lastTerm());
}
@Test
public void testLastIndexAfterCompaction1() throws Exception {
ReplicatedLog compacted = log().append(entry1).compactedWith(snapshot1);
Assert.assertEquals(1, compacted.lastIndex());
}
@Test
public void testLastIndexAfterCompaction2() throws Exception {
ReplicatedLog compacted = log().append(entry1).append(entry2).compactedWith(snapshot2);
Assert.assertEquals(2, compacted.lastIndex());
}
@Test
public void testLastIndexAfterCompaction3() throws Exception {
ReplicatedLog compacted = log().append(entry1).append(entry2).append(entry3).compactedWith(snapshot3);
Assert.assertEquals(3, compacted.lastIndex());
}
@Test
public void testEntriesBatchFrom1AfterCompaction1() throws Exception {
ReplicatedLog compacted = log().append(entry1).append(entry2).append(entry3).compactedWith(snapshot1);
Assert.assertEquals(ImmutableList.of(snapshotEntry1, entry2, entry3), compacted.entriesBatchFrom(1));
}
@Test
public void testEntriesBatchFrom1AfterCompaction2() throws Exception {
ReplicatedLog compacted = log().append(entry1).append(entry2).append(entry3).compactedWith(snapshot1);
Assert.assertEquals(ImmutableList.of(entry2, entry3), compacted.entriesBatchFrom(2));
}
@Test
public void testEntriesBatchFrom1AfterCompaction3() throws Exception {
ReplicatedLog compacted = log().append(entry1).append(entry2).append(entry3).compactedWith(snapshot1);
Assert.assertEquals(ImmutableList.of(entry3), compacted.entriesBatchFrom(3));
}
public class AppendWord implements Streamable {
private final String word;
public AppendWord(StreamInput stream) throws IOException {
word = stream.readText();
}
public AppendWord(String word) {
this.word = word;
}
@Override
public void writeTo(StreamOutput stream) throws IOException {
stream.writeText(word);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AppendWord that = (AppendWord) o;
return word.equals(that.word);
}
@Override
public int hashCode() {
return word.hashCode();
}
}
}
| raft2:
- fix naming in test
| src/test/java/org/mitallast/queue/raft/log/ReplicatedLogTest.java | raft2: - fix naming in test |
|
Java | epl-1.0 | 12866ef2c40c69a6974d46f4d08cf7a6a8966d0a | 0 | rayyang2000/goclipse,johnjaylward/goclipse,happyspace/goclipse,johannesMatevosyan/goclipse,fredyw/goclipse,aschran/goclipse,gchm2010/goclipse,GoClipse/goclipse,johnjaylward/goclipse,akutz/goclipse,fredyw/goclipse,bnrghvn/goclipse,gchm2010/goclipse,gchm2010/goclipse,happyspace/goclipse,johannesMatevosyan/goclipse,rayyang2000/goclipse,happyspace/goclipse,bnrghvn/goclipse,fredyw/goclipse,aschran/goclipse,johnjaylward/goclipse,bnrghvn/goclipse,johannesMatevosyan/goclipse,GoClipse/goclipse,rayyang2000/goclipse,akutz/goclipse,GoClipse/goclipse,aschran/goclipse,akutz/goclipse | /*******************************************************************************
* Copyright (c) 2015, 2015 Bruno Medeiros and other Contributors.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Bruno Medeiros - initial API and implementation
*******************************************************************************/
package melnorme.lang.ide.ui.text;
import static melnorme.utilbox.core.Assert.AssertNamespace.assertUnreachable;
import static melnorme.utilbox.core.CoreUtil.array;
import static melnorme.utilbox.core.CoreUtil.tryCast;
import java.util.Map;
import melnorme.lang.ide.ui.CodeFormatterConstants;
import melnorme.lang.ide.ui.CodeFormatterConstants.IndentMode;
import melnorme.lang.ide.ui.EditorSettings_Actual;
import melnorme.lang.ide.ui.LangUIPlugin;
import melnorme.lang.ide.ui.LangUIPlugin_Actual;
import melnorme.lang.ide.ui.editor.AbstractLangEditor;
import melnorme.lang.ide.ui.editor.LangSourceViewer;
import melnorme.lang.ide.ui.editor.ProjectionViewerExt;
import melnorme.lang.ide.ui.editor.hover.BestMatchHover;
import melnorme.lang.ide.ui.editor.structure.AbstractLangStructureEditor;
import melnorme.lang.ide.ui.editor.structure.LangOutlineInformationControl.OutlineInformationControlCreator;
import melnorme.lang.ide.ui.editor.structure.StructureElementInformationProvider;
import melnorme.lang.ide.ui.editor.text.LangReconciler;
import melnorme.lang.ide.ui.text.completion.CompletionProposalsGrouping;
import melnorme.lang.ide.ui.text.completion.ContentAssistantExt;
import melnorme.lang.ide.ui.text.completion.LangContentAssistProcessor;
import melnorme.lang.ide.ui.text.completion.LangContentAssistProcessor.ContentAssistCategoriesBuilder;
import melnorme.lang.ide.ui.text.util.AutoEditUtils;
import melnorme.utilbox.collections.Indexable;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.AbstractInformationControlManager;
import org.eclipse.jface.text.DefaultInformationControl;
import org.eclipse.jface.text.IAutoEditStrategy;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IInformationControl;
import org.eclipse.jface.text.IInformationControlCreator;
import org.eclipse.jface.text.ITextHover;
import org.eclipse.jface.text.ITextViewerExtension2;
import org.eclipse.jface.text.contentassist.ContentAssistant;
import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
import org.eclipse.jface.text.contentassist.IContentAssistant;
import org.eclipse.jface.text.information.IInformationPresenter;
import org.eclipse.jface.text.information.IInformationProvider;
import org.eclipse.jface.text.information.InformationPresenter;
import org.eclipse.jface.text.reconciler.AbstractReconciler;
import org.eclipse.jface.text.reconciler.IReconciler;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.IAnnotationHover;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.texteditor.ITextEditor;
import _org.eclipse.cdt.ui.text.IColorManager;
import _org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy;
import _org.eclipse.jdt.internal.ui.text.HTMLAnnotationHover;
public abstract class AbstractLangSourceViewerConfiguration extends SimpleLangSourceViewerConfiguration {
protected final AbstractLangStructureEditor editor;
public AbstractLangSourceViewerConfiguration(IPreferenceStore preferenceStore, IColorManager colorManager,
AbstractLangStructureEditor editor) {
super(preferenceStore, colorManager);
this.editor = editor;
}
public AbstractLangStructureEditor getEditor() {
return editor;
}
public AbstractLangEditor getEditor_asLang() {
return tryCast(editor, AbstractLangEditor.class);
}
/* ----------------- Hovers ----------------- */
@Override
public final ITextHover getTextHover(ISourceViewer sourceViewer, String contentType) {
return getTextHover(sourceViewer, contentType, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK);
}
@Override
public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType, int stateMask) {
return new BestMatchHover(getEditor());
}
@Override
public IAnnotationHover getAnnotationHover(ISourceViewer sourceViewer) {
return new HTMLAnnotationHover(false) {
@Override
protected boolean isIncluded(Annotation annotation) {
return isShowInVerticalRuler(annotation);
}
};
}
@Override
public IAnnotationHover getOverviewRulerAnnotationHover(ISourceViewer sourceViewer) {
return new HTMLAnnotationHover(true) {
@Override
protected boolean isIncluded(Annotation annotation) {
return isShowInOverviewRuler(annotation);
}
};
}
@Override
public IInformationPresenter getInformationPresenter(ISourceViewer sourceViewer) {
InformationPresenter presenter = new InformationPresenter(getInformationPresenterControlCreator(sourceViewer));
presenter.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
// Register information providers
for (String contentType : getConfiguredContentTypes(sourceViewer)) {
presenter.setInformationProvider(getInformationProvider(contentType), contentType);
}
presenter.setSizeConstraints(100, 12, false, true);
return presenter;
}
protected abstract IInformationProvider getInformationProvider(String contentType);
protected IInformationControlCreator getInformationPresenterControlCreator(
@SuppressWarnings("unused") ISourceViewer sourceViewer) {
return new IInformationControlCreator() {
@Override
public IInformationControl createInformationControl(Shell parent) {
return new DefaultInformationControl(parent, true);
}
};
}
/* ----------------- Navigation operations ----------------- */
@Override
protected Map<String, ITextEditor> getHyperlinkDetectorTargets(ISourceViewer sourceViewer) {
Map<String, ITextEditor> targets = super.getHyperlinkDetectorTargets(sourceViewer);
targets.put(EditorSettings_Actual.EDITOR_CODE_TARGET, editor);
return targets;
}
public void installOutlinePresenter(final LangSourceViewer sourceViewer) {
final InformationPresenter presenter =
new InformationPresenter(getOutlinePresenterControlCreator(sourceViewer));
presenter.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
presenter.setAnchor(AbstractInformationControlManager.ANCHOR_GLOBAL);
IInformationProvider provider = new StructureElementInformationProvider(getEditor());
for(String contentType : getConfiguredContentTypes(sourceViewer)) {
presenter.setInformationProvider(provider, contentType);
}
presenter.setSizeConstraints(50, 20, true, false);
presenter.install(sourceViewer);
sourceViewer.setOutlinePresenter(presenter);
}
protected IInformationControlCreator getOutlinePresenterControlCreator(
@SuppressWarnings("unused") ISourceViewer sourceViewer) {
return new OutlineInformationControlCreator(this);
}
/* ----------------- Modification operations ----------------- */
@Override
public String[] getDefaultPrefixes(ISourceViewer sourceViewer, String contentType) {
return new String[] { getToggleCommentPrefix(), "" };
}
protected abstract String getToggleCommentPrefix();
@Override
public IAutoEditStrategy[] getAutoEditStrategies(ISourceViewer sourceViewer, String contentType) {
if(IDocument.DEFAULT_CONTENT_TYPE.equals(contentType)) {
return array(LangUIPlugin_Actual.createAutoEditStrategy(sourceViewer, contentType));
} else {
return super.getAutoEditStrategies(sourceViewer, contentType);
}
}
@Override
public String[] getIndentPrefixes(ISourceViewer sourceViewer, String contentType) {
IndentMode indentMode = CodeFormatterConstants.IndentMode.fromPrefStore();
int spaceIndentationSize = CodeFormatterConstants.FORMATTER_INDENTATION_SPACES_SIZE.get();
String spaceIndent = AutoEditUtils.getNSpaces(spaceIndentationSize);
switch (indentMode) {
case TAB: return array("\t", spaceIndent); // return getIndentPrefixesForTab(spaceIndent);
case SPACES: return array(spaceIndent, "\t"); // return getIndentPrefixesForSpaces(spaceIndent);
}
throw assertUnreachable();
}
@Override
protected void updateIndentationSettings(SourceViewer sourceViewer, String property) {
super.updateIndentationSettings(sourceViewer, property);
if(
CodeFormatterConstants.FORMATTER_INDENTATION_SPACES_SIZE.keyEquals(property) ||
CodeFormatterConstants.FORMATTER_INDENT_MODE.keyEquals(property)) {
for(String contentType : getConfiguredContentTypes(sourceViewer)) {
String[] prefixes= getIndentPrefixes(sourceViewer, contentType);
sourceViewer.setIndentPrefixes(prefixes, contentType);
}
}
}
/* ----------------- Content Assist ----------------- */
@Override
public ContentAssistant getContentAssistant(ISourceViewer sourceViewer) {
AbstractLangEditor editor = getEditor_asLang();
if(editor != null) {
ContentAssistantExt assistant = createContentAssitant();
assistant.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
assistant.setRestoreCompletionProposalSize(LangUIPlugin.getDialogSettings("completion_proposal_size"));
assistant.setInformationControlCreator(
getInformationControl_ContentAsssist(getAdditionalInfoAffordanceString()));
assistant.setContextInformationPopupOrientation(IContentAssistant.CONTEXT_INFO_ABOVE);
assistant.enableColoredLabels(true);
configureContentAssistantProcessors(assistant);
// Note: configuration must come after processors are created
assistant.configure(fPreferenceStore, editor.getSourceViewer_());
return assistant;
}
return null;
}
protected ContentAssistantExt createContentAssitant() {
return new ContentAssistantExt(getPreferenceStore());
}
protected void configureContentAssistantProcessors(ContentAssistant assistant) {
Indexable<CompletionProposalsGrouping> categories = getContentAssistCategoriesProvider().getCategories();
IContentAssistProcessor cap = createContentAssistProcessor(assistant, categories);
assistant.setContentAssistProcessor(cap, IDocument.DEFAULT_CONTENT_TYPE);
}
protected LangContentAssistProcessor createContentAssistProcessor(ContentAssistant assistant,
Indexable<CompletionProposalsGrouping> categories) {
return new LangContentAssistProcessor(assistant, getEditor(), categories);
}
protected abstract ContentAssistCategoriesBuilder getContentAssistCategoriesProvider();
/* ----------------- reconciler ----------------- */
@Override
public IReconciler getReconciler(ISourceViewer sourceViewer) {
ITextEditor editor = getEditor();
if(editor != null && editor.isEditable()) {
AbstractReconciler reconciler = doCreateReconciler(editor);
reconciler.setIsAllowedToModifyDocument(false);
reconciler.setDelay(500); // Can't use zero
return reconciler;
}
return null;
}
protected LangReconciler doCreateReconciler(ITextEditor editor) {
CompositeReconcilingStrategy strategy = getReconciler_createCompositeStrategy(editor);
return new LangReconciler(strategy, false, editor);
}
@SuppressWarnings("unused")
protected CompositeReconcilingStrategy getReconciler_createCompositeStrategy(ITextEditor editor) {
return new CompositeReconcilingStrategy();
}
/* ----------------- ----------------- */
@Override
public void configureViewer(ProjectionViewerExt sourceViewer) {
super.configureViewer(sourceViewer);
if(sourceViewer instanceof LangSourceViewer) {
LangSourceViewer langSourceViewer = (LangSourceViewer) sourceViewer;
installOutlinePresenter(langSourceViewer);
}
}
} | plugin_ide.ui/src-lang/melnorme/lang/ide/ui/text/AbstractLangSourceViewerConfiguration.java | /*******************************************************************************
* Copyright (c) 2015, 2015 Bruno Medeiros and other Contributors.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Bruno Medeiros - initial API and implementation
*******************************************************************************/
package melnorme.lang.ide.ui.text;
import static melnorme.utilbox.core.Assert.AssertNamespace.assertUnreachable;
import static melnorme.utilbox.core.CoreUtil.array;
import static melnorme.utilbox.core.CoreUtil.tryCast;
import java.util.Map;
import melnorme.lang.ide.ui.CodeFormatterConstants;
import melnorme.lang.ide.ui.CodeFormatterConstants.IndentMode;
import melnorme.lang.ide.ui.EditorSettings_Actual;
import melnorme.lang.ide.ui.LangUIPlugin;
import melnorme.lang.ide.ui.LangUIPlugin_Actual;
import melnorme.lang.ide.ui.editor.AbstractLangEditor;
import melnorme.lang.ide.ui.editor.LangSourceViewer;
import melnorme.lang.ide.ui.editor.ProjectionViewerExt;
import melnorme.lang.ide.ui.editor.hover.BestMatchHover;
import melnorme.lang.ide.ui.editor.structure.AbstractLangStructureEditor;
import melnorme.lang.ide.ui.editor.structure.LangOutlineInformationControl.OutlineInformationControlCreator;
import melnorme.lang.ide.ui.editor.structure.StructureElementInformationProvider;
import melnorme.lang.ide.ui.editor.text.LangReconciler;
import melnorme.lang.ide.ui.text.completion.CompletionProposalsGrouping;
import melnorme.lang.ide.ui.text.completion.ContentAssistantExt;
import melnorme.lang.ide.ui.text.completion.LangContentAssistProcessor;
import melnorme.lang.ide.ui.text.completion.LangContentAssistProcessor.ContentAssistCategoriesBuilder;
import melnorme.lang.ide.ui.text.util.AutoEditUtils;
import melnorme.utilbox.collections.Indexable;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.AbstractInformationControlManager;
import org.eclipse.jface.text.DefaultInformationControl;
import org.eclipse.jface.text.IAutoEditStrategy;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IInformationControl;
import org.eclipse.jface.text.IInformationControlCreator;
import org.eclipse.jface.text.ITextHover;
import org.eclipse.jface.text.ITextViewerExtension2;
import org.eclipse.jface.text.contentassist.ContentAssistant;
import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
import org.eclipse.jface.text.contentassist.IContentAssistant;
import org.eclipse.jface.text.information.IInformationPresenter;
import org.eclipse.jface.text.information.IInformationProvider;
import org.eclipse.jface.text.information.InformationPresenter;
import org.eclipse.jface.text.reconciler.AbstractReconciler;
import org.eclipse.jface.text.reconciler.IReconciler;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.IAnnotationHover;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.texteditor.ITextEditor;
import _org.eclipse.cdt.ui.text.IColorManager;
import _org.eclipse.jdt.internal.ui.text.CompositeReconcilingStrategy;
import _org.eclipse.jdt.internal.ui.text.HTMLAnnotationHover;
public abstract class AbstractLangSourceViewerConfiguration extends SimpleLangSourceViewerConfiguration {
protected final AbstractLangStructureEditor editor;
public AbstractLangSourceViewerConfiguration(IPreferenceStore preferenceStore, IColorManager colorManager,
AbstractLangStructureEditor editor) {
super(preferenceStore, colorManager);
this.editor = editor;
}
public AbstractLangStructureEditor getEditor() {
return editor;
}
public AbstractLangEditor getEditor_asLang() {
return tryCast(editor, AbstractLangEditor.class);
}
/* ----------------- Hovers ----------------- */
@Override
public final ITextHover getTextHover(ISourceViewer sourceViewer, String contentType) {
return getTextHover(sourceViewer, contentType, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK);
}
@Override
public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType, int stateMask) {
if(contentType.equals(IDocument.DEFAULT_CONTENT_TYPE)) {
return new BestMatchHover(getEditor());
}
return null;
}
@Override
public IAnnotationHover getAnnotationHover(ISourceViewer sourceViewer) {
return new HTMLAnnotationHover(false) {
@Override
protected boolean isIncluded(Annotation annotation) {
return isShowInVerticalRuler(annotation);
}
};
}
@Override
public IAnnotationHover getOverviewRulerAnnotationHover(ISourceViewer sourceViewer) {
return new HTMLAnnotationHover(true) {
@Override
protected boolean isIncluded(Annotation annotation) {
return isShowInOverviewRuler(annotation);
}
};
}
@Override
public IInformationPresenter getInformationPresenter(ISourceViewer sourceViewer) {
InformationPresenter presenter = new InformationPresenter(getInformationPresenterControlCreator(sourceViewer));
presenter.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
// Register information providers
for (String contentType : getConfiguredContentTypes(sourceViewer)) {
presenter.setInformationProvider(getInformationProvider(contentType), contentType);
}
presenter.setSizeConstraints(100, 12, false, true);
return presenter;
}
protected abstract IInformationProvider getInformationProvider(String contentType);
protected IInformationControlCreator getInformationPresenterControlCreator(
@SuppressWarnings("unused") ISourceViewer sourceViewer) {
return new IInformationControlCreator() {
@Override
public IInformationControl createInformationControl(Shell parent) {
return new DefaultInformationControl(parent, true);
}
};
}
/* ----------------- Navigation operations ----------------- */
@Override
protected Map<String, ITextEditor> getHyperlinkDetectorTargets(ISourceViewer sourceViewer) {
Map<String, ITextEditor> targets = super.getHyperlinkDetectorTargets(sourceViewer);
targets.put(EditorSettings_Actual.EDITOR_CODE_TARGET, editor);
return targets;
}
public void installOutlinePresenter(final LangSourceViewer sourceViewer) {
final InformationPresenter presenter =
new InformationPresenter(getOutlinePresenterControlCreator(sourceViewer));
presenter.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
presenter.setAnchor(AbstractInformationControlManager.ANCHOR_GLOBAL);
IInformationProvider provider = new StructureElementInformationProvider(getEditor());
for(String contentType : getConfiguredContentTypes(sourceViewer)) {
presenter.setInformationProvider(provider, contentType);
}
presenter.setSizeConstraints(50, 20, true, false);
presenter.install(sourceViewer);
sourceViewer.setOutlinePresenter(presenter);
}
protected IInformationControlCreator getOutlinePresenterControlCreator(
@SuppressWarnings("unused") ISourceViewer sourceViewer) {
return new OutlineInformationControlCreator(this);
}
/* ----------------- Modification operations ----------------- */
@Override
public String[] getDefaultPrefixes(ISourceViewer sourceViewer, String contentType) {
return new String[] { getToggleCommentPrefix(), "" };
}
protected abstract String getToggleCommentPrefix();
@Override
public IAutoEditStrategy[] getAutoEditStrategies(ISourceViewer sourceViewer, String contentType) {
if(IDocument.DEFAULT_CONTENT_TYPE.equals(contentType)) {
return array(LangUIPlugin_Actual.createAutoEditStrategy(sourceViewer, contentType));
} else {
return super.getAutoEditStrategies(sourceViewer, contentType);
}
}
@Override
public String[] getIndentPrefixes(ISourceViewer sourceViewer, String contentType) {
IndentMode indentMode = CodeFormatterConstants.IndentMode.fromPrefStore();
int spaceIndentationSize = CodeFormatterConstants.FORMATTER_INDENTATION_SPACES_SIZE.get();
String spaceIndent = AutoEditUtils.getNSpaces(spaceIndentationSize);
switch (indentMode) {
case TAB: return array("\t", spaceIndent); // return getIndentPrefixesForTab(spaceIndent);
case SPACES: return array(spaceIndent, "\t"); // return getIndentPrefixesForSpaces(spaceIndent);
}
throw assertUnreachable();
}
@Override
protected void updateIndentationSettings(SourceViewer sourceViewer, String property) {
super.updateIndentationSettings(sourceViewer, property);
if(
CodeFormatterConstants.FORMATTER_INDENTATION_SPACES_SIZE.keyEquals(property) ||
CodeFormatterConstants.FORMATTER_INDENT_MODE.keyEquals(property)) {
for(String contentType : getConfiguredContentTypes(sourceViewer)) {
String[] prefixes= getIndentPrefixes(sourceViewer, contentType);
sourceViewer.setIndentPrefixes(prefixes, contentType);
}
}
}
/* ----------------- Content Assist ----------------- */
@Override
public ContentAssistant getContentAssistant(ISourceViewer sourceViewer) {
AbstractLangEditor editor = getEditor_asLang();
if(editor != null) {
ContentAssistantExt assistant = createContentAssitant();
assistant.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
assistant.setRestoreCompletionProposalSize(LangUIPlugin.getDialogSettings("completion_proposal_size"));
assistant.setInformationControlCreator(
getInformationControl_ContentAsssist(getAdditionalInfoAffordanceString()));
assistant.setContextInformationPopupOrientation(IContentAssistant.CONTEXT_INFO_ABOVE);
assistant.enableColoredLabels(true);
configureContentAssistantProcessors(assistant);
// Note: configuration must come after processors are created
assistant.configure(fPreferenceStore, editor.getSourceViewer_());
return assistant;
}
return null;
}
protected ContentAssistantExt createContentAssitant() {
return new ContentAssistantExt(getPreferenceStore());
}
protected void configureContentAssistantProcessors(ContentAssistant assistant) {
Indexable<CompletionProposalsGrouping> categories = getContentAssistCategoriesProvider().getCategories();
IContentAssistProcessor cap = createContentAssistProcessor(assistant, categories);
assistant.setContentAssistProcessor(cap, IDocument.DEFAULT_CONTENT_TYPE);
}
protected LangContentAssistProcessor createContentAssistProcessor(ContentAssistant assistant,
Indexable<CompletionProposalsGrouping> categories) {
return new LangContentAssistProcessor(assistant, getEditor(), categories);
}
protected abstract ContentAssistCategoriesBuilder getContentAssistCategoriesProvider();
/* ----------------- reconciler ----------------- */
@Override
public IReconciler getReconciler(ISourceViewer sourceViewer) {
ITextEditor editor = getEditor();
if(editor != null && editor.isEditable()) {
AbstractReconciler reconciler = doCreateReconciler(editor);
reconciler.setIsAllowedToModifyDocument(false);
reconciler.setDelay(500); // Can't use zero
return reconciler;
}
return null;
}
protected LangReconciler doCreateReconciler(ITextEditor editor) {
CompositeReconcilingStrategy strategy = getReconciler_createCompositeStrategy(editor);
return new LangReconciler(strategy, false, editor);
}
@SuppressWarnings("unused")
protected CompositeReconcilingStrategy getReconciler_createCompositeStrategy(ITextEditor editor) {
return new CompositeReconcilingStrategy();
}
/* ----------------- ----------------- */
@Override
public void configureViewer(ProjectionViewerExt sourceViewer) {
super.configureViewer(sourceViewer);
if(sourceViewer instanceof LangSourceViewer) {
LangSourceViewer langSourceViewer = (LangSourceViewer) sourceViewer;
installOutlinePresenter(langSourceViewer);
}
}
} | LANG: fix text hover not showing on other content types. | plugin_ide.ui/src-lang/melnorme/lang/ide/ui/text/AbstractLangSourceViewerConfiguration.java | LANG: fix text hover not showing on other content types. |
|
Java | epl-1.0 | 2a1163121d6e49dea024f753272c08c62299e970 | 0 | ELTE-Soft/xUML-RT-Executor | package hu.eltesoft.modelexecution.runtime;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingDeque;
import hu.eltesoft.modelexecution.runtime.base.ClassWithState;
import hu.eltesoft.modelexecution.runtime.base.Event;
import hu.eltesoft.modelexecution.runtime.external.ExternalEntityException;
import hu.eltesoft.modelexecution.runtime.external.ExternalEntityRegistry;
import hu.eltesoft.modelexecution.runtime.log.Logger;
import hu.eltesoft.modelexecution.runtime.log.NoLogger;
import hu.eltesoft.modelexecution.runtime.trace.InvalidTraceException;
import hu.eltesoft.modelexecution.runtime.trace.NoTraceReader;
import hu.eltesoft.modelexecution.runtime.trace.NoTracer;
import hu.eltesoft.modelexecution.runtime.trace.TargetedEvent;
import hu.eltesoft.modelexecution.runtime.trace.TraceReader;
import hu.eltesoft.modelexecution.runtime.trace.TraceReader.EventSource;
import hu.eltesoft.modelexecution.runtime.validation.ValidationError;
import hu.eltesoft.modelexecution.runtime.trace.Tracer;
/**
* Executes the model using logging and tracing. Receives the name of the class
* and the name of a static function to execute.
*/
public final class BaseRuntime implements AutoCloseable {
private static final String LOGGER_ID = "hu.eltesoft.modelexecution.runtime.baseRuntime";
public static final String RUNTIME_LOGGER_ID = LOGGER_ID + ".Runtime";
public static final String STATES_LOGGER_ID = LOGGER_ID + ".StateMachine.States";
public static final String TRANSITIONS_LOGGER_ID = LOGGER_ID + ".StateMachine.Transitions";
public static final String MESSAGES_LOGGER_ID = LOGGER_ID + ".Events.Messages";
private LinkedBlockingDeque<TargetedEvent> queue = new LinkedBlockingDeque<>();
private Tracer traceWriter = new NoTracer();
private TraceReader traceReader = new NoTraceReader();
private Logger logger = new NoLogger();
private RuntimeControllerServer controller;
private static java.util.logging.Logger errorLogger = java.util.logging.Logger.getLogger(RUNTIME_LOGGER_ID); // $NON-NLS-1$
private final ExternalEntityRegistry externalEntities;
private ClassLoader classLoader = BaseRuntime.class.getClassLoader();
private final CountDownLatch executionReady = new CountDownLatch(1);
private boolean controlledStart = false;
/**
* If has to set the class loader it must be done before the runtime is
* used.
*/
public void setClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
private static BaseRuntime INSTANCE = null;
public static BaseRuntime getInstance() {
if (INSTANCE == null) {
INSTANCE = new BaseRuntime();
}
return INSTANCE;
}
private BaseRuntime() {
externalEntities = new ExternalEntityRegistry(classLoader);
}
/**
* Switches the runtime to a controlled mode. In controlled mode, the
* runtime can be managed with control messages throught the control stream.
* This method may be called multiple times, in this case, the runtime
* responds to messages on all control streams.
*/
public void addControlStreams(InputStream controlStream, OutputStream eventStream) {
controller = new RuntimeControllerServer(controlStream, eventStream, this);
controller.startListening();
}
public void start() {
executionReady.countDown();
}
/**
* Stops the execution of the runtime after the logs have been written out.
*/
public void terminate() {
try {
// explicitly call close
close();
} catch (Exception e) {
logError("Cannot close the runtime", e);
}
System.exit(1);
}
public void addEventToQueue(ClassWithState target, Event event) {
TargetedEvent targetedEvent = new TargetedEvent(target, event);
queue.addLast(targetedEvent);
logger.messageQueued(target, event);
}
public void addExternalEventToQueue(ClassWithState target, Event event) {
TargetedEvent targetedEvent = TargetedEvent.createOutsideEvent(target, event);
queue.addLast(targetedEvent);
logger.messageQueued(target, event);
}
public void setTraceWriter(Tracer traceWriter) {
this.traceWriter = traceWriter;
}
public void setTraceReader(TraceReader traceReader) {
this.traceReader = traceReader;
}
public void setLogger(Logger logger) {
this.logger = logger;
}
/**
* Runs the system. This can be an entry point of the runtime.
*/
public TerminationResult run(String className, String mainName) throws Exception {
try {
logInfo("Preparing system for execution");
prepare(className, mainName);
if (!InstanceRegistry.getInstanceRegistry().isEmpty()) {
if (controlledStart) {
executionReady.await();
}
logInfo("Starting execution");
do {
// events read from trace will not be written to trace
if (queue.isEmpty() && traceReader.hasEvent()) {
traceReader.dispatchEvent(logger);
} else {
// if queue is empty, take blocks
TargetedEvent currQueueEvent = queue.take();
if (traceReader.dispatchEvent(currQueueEvent, logger) == EventSource.Trace) {
// put back the event to the original position
queue.addFirst(currQueueEvent);
} else {
traceWriter.traceEvent(currQueueEvent);
}
}
} while (!InstanceRegistry.getInstanceRegistry().isEmpty());
}
logInfo("Execution terminated successfully");
return TerminationResult.SUCCESSFUL_TERMINATION;
} catch (InvalidTraceException e) {
logError("The trace file is not consistent with the current model.", e);
return TerminationResult.INVALID_TRACEFILE;
} catch (ExternalEntityException e) {
logError("Invalid external entity.", e);
return TerminationResult.INVALID_EXTERNAL_ENTITY;
} catch (Exception e) {
logError("An internal error happened", e);
return TerminationResult.INTERNAL_ERROR;
} finally {
if (controller != null) {
controller.stopListening();
}
}
}
/**
* Runs the selected static main method.
*/
private void prepare(String className, String mainName)
throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
java.lang.Class<?> classClass = classLoader.loadClass(className);
Method main = classClass.getMethod(mainName);
main.invoke(null);
}
public void logEnterState(String state) {
logger.enterState(state);
}
public void logExitState(String state) {
logger.exitState(state);
}
public void logTransition(String eventName, String messageName, String source, String target) {
logger.transition(eventName, messageName, source, target);
}
public static void logInfo(String message) {
errorLogger.log(java.util.logging.Level.INFO, message);
}
public static void validationError(ValidationError validationError) {
errorLogger.log(java.util.logging.Level.SEVERE, validationError.getMessage());
}
public static void logError(String message) {
errorLogger.log(java.util.logging.Level.SEVERE, message);
}
public static void logError(String message, Throwable cause) {
errorLogger.log(java.util.logging.Level.SEVERE, message);
errorLogger.log(java.util.logging.Level.INFO, "", cause);
}
public static void logError(Throwable cause) {
errorLogger.log(java.util.logging.Level.SEVERE, "Unexpected exception", //$NON-NLS-1$
cause);
}
@Override
public void close() throws Exception {
logger.close();
traceWriter.close();
traceReader.close();
INSTANCE = null;
}
public <Impl> Impl getExternalEntity(Class<? super Impl> entityClass) {
return externalEntities.getInstance(entityClass);
}
public void setControlledStart(boolean controlledStart) {
this.controlledStart = controlledStart;
}
}
| plugins/hu.eltesoft.modelexecution.runtime/src/hu/eltesoft/modelexecution/runtime/BaseRuntime.java | package hu.eltesoft.modelexecution.runtime;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingDeque;
import hu.eltesoft.modelexecution.runtime.base.ClassWithState;
import hu.eltesoft.modelexecution.runtime.base.Event;
import hu.eltesoft.modelexecution.runtime.external.ExternalEntityException;
import hu.eltesoft.modelexecution.runtime.external.ExternalEntityRegistry;
import hu.eltesoft.modelexecution.runtime.log.Logger;
import hu.eltesoft.modelexecution.runtime.log.NoLogger;
import hu.eltesoft.modelexecution.runtime.trace.InvalidTraceException;
import hu.eltesoft.modelexecution.runtime.trace.NoTraceReader;
import hu.eltesoft.modelexecution.runtime.trace.NoTracer;
import hu.eltesoft.modelexecution.runtime.trace.TargetedEvent;
import hu.eltesoft.modelexecution.runtime.trace.TraceReader;
import hu.eltesoft.modelexecution.runtime.trace.TraceReader.EventSource;
import hu.eltesoft.modelexecution.runtime.validation.ValidationError;
import hu.eltesoft.modelexecution.runtime.trace.Tracer;
/**
* Executes the model using logging and tracing. Receives the name of the class
* and the name of a static function to execute.
*/
public final class BaseRuntime implements AutoCloseable {
private static final String LOGGER_ID = "hu.eltesoft.modelexecution.runtime.baseRuntime.";
public static final String RUNTIME_LOGGER_ID = LOGGER_ID + "Runtime";
public static final String STATES_LOGGER_ID = LOGGER_ID + "StateMachine.States";
public static final String TRANSITIONS_LOGGER_ID = LOGGER_ID + "StateMachine.Transitions";
public static final String MESSAGES_LOGGER_ID = LOGGER_ID + "Events.Messages";
private LinkedBlockingDeque<TargetedEvent> queue = new LinkedBlockingDeque<>();
private Tracer traceWriter = new NoTracer();
private TraceReader traceReader = new NoTraceReader();
private Logger logger = new NoLogger();
private RuntimeControllerServer controller;
private static java.util.logging.Logger errorLogger = java.util.logging.Logger.getLogger(LOGGER_ID); // $NON-NLS-1$
private final ExternalEntityRegistry externalEntities;
private ClassLoader classLoader = BaseRuntime.class.getClassLoader();
private final CountDownLatch executionReady = new CountDownLatch(1);
private boolean controlledStart = false;
/**
* If has to set the class loader it must be done before the runtime is
* used.
*/
public void setClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
private static BaseRuntime INSTANCE = null;
public static BaseRuntime getInstance() {
if (INSTANCE == null) {
INSTANCE = new BaseRuntime();
}
return INSTANCE;
}
private BaseRuntime() {
externalEntities = new ExternalEntityRegistry(classLoader);
}
/**
* Switches the runtime to a controlled mode. In controlled mode, the
* runtime can be managed with control messages throught the control stream.
* This method may be called multiple times, in this case, the runtime
* responds to messages on all control streams.
*/
public void addControlStreams(InputStream controlStream, OutputStream eventStream) {
controller = new RuntimeControllerServer(controlStream, eventStream, this);
controller.startListening();
}
public void start() {
executionReady.countDown();
}
/**
* Stops the execution of the runtime after the logs have been written out.
*/
public void terminate() {
try {
// explicitly call close
close();
} catch (Exception e) {
logError("Cannot close the runtime", e);
}
System.exit(1);
}
public void addEventToQueue(ClassWithState target, Event event) {
TargetedEvent targetedEvent = new TargetedEvent(target, event);
queue.addLast(targetedEvent);
logger.messageQueued(target, event);
}
public void addExternalEventToQueue(ClassWithState target, Event event) {
TargetedEvent targetedEvent = TargetedEvent.createOutsideEvent(target, event);
queue.addLast(targetedEvent);
logger.messageQueued(target, event);
}
public void setTraceWriter(Tracer traceWriter) {
this.traceWriter = traceWriter;
}
public void setTraceReader(TraceReader traceReader) {
this.traceReader = traceReader;
}
public void setLogger(Logger logger) {
this.logger = logger;
}
/**
* Runs the system. This can be an entry point of the runtime.
*/
public TerminationResult run(String className, String mainName) throws Exception {
try {
logInfo("Preparing system for execution");
prepare(className, mainName);
if (!InstanceRegistry.getInstanceRegistry().isEmpty()) {
if (controlledStart) {
executionReady.await();
}
logInfo("Starting execution");
do {
// events read from trace will not be written to trace
if (queue.isEmpty() && traceReader.hasEvent()) {
traceReader.dispatchEvent(logger);
} else {
// if queue is empty, take blocks
TargetedEvent currQueueEvent = queue.take();
if (traceReader.dispatchEvent(currQueueEvent, logger) == EventSource.Trace) {
// put back the event to the original position
queue.addFirst(currQueueEvent);
} else {
traceWriter.traceEvent(currQueueEvent);
}
}
} while (!InstanceRegistry.getInstanceRegistry().isEmpty());
}
logInfo("Execution terminated successfully");
return TerminationResult.SUCCESSFUL_TERMINATION;
} catch (InvalidTraceException e) {
logError("The trace file is not consistent with the current model.", e);
return TerminationResult.INVALID_TRACEFILE;
} catch (ExternalEntityException e) {
logError("Invalid external entity.", e);
return TerminationResult.INVALID_EXTERNAL_ENTITY;
} catch (Exception e) {
logError("An internal error happened", e);
return TerminationResult.INTERNAL_ERROR;
} finally {
if (controller != null) {
controller.stopListening();
}
}
}
/**
* Runs the selected static main method.
*/
private void prepare(String className, String mainName)
throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
java.lang.Class<?> classClass = classLoader.loadClass(className);
Method main = classClass.getMethod(mainName);
main.invoke(null);
}
public void logEnterState(String state) {
logger.enterState(state);
}
public void logExitState(String state) {
logger.exitState(state);
}
public void logTransition(String eventName, String messageName, String source, String target) {
logger.transition(eventName, messageName, source, target);
}
public static void logInfo(String message) {
errorLogger.log(java.util.logging.Level.INFO, message);
}
public static void validationError(ValidationError validationError) {
errorLogger.log(java.util.logging.Level.SEVERE, validationError.getMessage());
}
public static void logError(String message) {
errorLogger.log(java.util.logging.Level.SEVERE, message);
}
public static void logError(String message, Throwable cause) {
errorLogger.log(java.util.logging.Level.SEVERE, message);
errorLogger.log(java.util.logging.Level.INFO, "", cause);
}
public static void logError(Throwable cause) {
errorLogger.log(java.util.logging.Level.SEVERE, "Unexpected exception", //$NON-NLS-1$
cause);
}
@Override
public void close() throws Exception {
logger.close();
traceWriter.close();
traceReader.close();
INSTANCE = null;
}
public <Impl> Impl getExternalEntity(Class<? super Impl> entityClass) {
return externalEntities.getInstance(entityClass);
}
public void setControlledStart(boolean controlledStart) {
this.controlledStart = controlledStart;
}
}
| correction of logging ids
| plugins/hu.eltesoft.modelexecution.runtime/src/hu/eltesoft/modelexecution/runtime/BaseRuntime.java | correction of logging ids |
|
Java | mpl-2.0 | 4b0ec8b09296d1d50cf597e2c30b274ae0bc6d61 | 0 | begetan/syncthing-android,jmintb/syncthing-android,wweich/syncthing-android,wweich/syncthing-android,jmintb/syncthing-android,Nutomic/syncthing-android,flipreverse/syncthing-android,syncthing/syncthing-android,syncthing/syncthing-android,syncthing/syncthing-android,begetan/syncthing-android,flipreverse/syncthing-android,Nutomic/syncthing-android | package com.nutomic.syncthingandroid.http;
import android.annotation.SuppressLint;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.util.Pair;
import com.google.common.base.Charsets;
import com.google.common.io.ByteSource;
import com.nutomic.syncthingandroid.syncthing.RestApi;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.SignatureException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public abstract class RestTask<Params, Progress> extends
AsyncTask<Params, Progress, Pair<Boolean, String>> {
private static final String TAG = "RestTask";
/**
* The name of the HTTP header used for the syncthing API key.
*/
private static final String HEADER_API_KEY = "X-API-Key";
public interface OnSuccessListener {
public void onSuccess(String result);
}
private final URL mUrl;
protected final String mPath;
private final String mHttpsCertPath;
private final String mApiKey;
private final OnSuccessListener mListener;
public RestTask(URL url, String path, String httpsCertPath, String apiKey,
OnSuccessListener listener) {
mUrl = url;
mPath = path;
mHttpsCertPath = httpsCertPath;
mApiKey = apiKey;
mListener = listener;
}
protected HttpsURLConnection openConnection(String... params) throws IOException {
Uri.Builder uriBuilder = Uri.parse(mUrl.toString())
.buildUpon()
.path(mPath);
for (int paramCounter = 0; paramCounter + 1 < params.length; ) {
uriBuilder.appendQueryParameter(params[paramCounter++], params[paramCounter++]);
}
URL url = new URL(uriBuilder.build().toString());
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestProperty(HEADER_API_KEY, mApiKey);
connection.setHostnameVerifier((h, s) -> true);
connection.setSSLSocketFactory(getSslSocketFactory());
return connection;
}
/**
* Opens the connection, then returns success status and response string.
*/
protected Pair<Boolean, String> connect(HttpsURLConnection connection) throws IOException {
connection.connect();
Pair<Boolean, String> result;
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
int responseCode = connection.getResponseCode();
String responseMessage = connection.getResponseMessage();
Log.i(TAG, "Request to " + connection.getURL() + " failed, code: " + responseCode +
", message: " + responseMessage);
result = new Pair<>(false, streamToString(connection.getErrorStream()));
}
else {
result = new Pair<>(true, streamToString(connection.getInputStream()));
}
connection.disconnect();
return result;
}
private String streamToString(InputStream is) throws IOException {
ByteSource byteSource = new ByteSource() {
@Override
public InputStream openStream() throws IOException {
return is;
}
};
return byteSource.asCharSource(Charsets.UTF_8).read();
}
protected void onPostExecute(Pair<Boolean, String> result) {
if (mListener == null || !result.first)
return;
mListener.onSuccess(result.second);
}
private SSLSocketFactory getSslSocketFactory() {
try {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{new SyncthingTrustManager()},
new SecureRandom());
return sslContext.getSocketFactory();
} catch (NoSuchAlgorithmException | KeyManagementException e) {
Log.w(TAG, e);
return null;
}
}
/*
* TrustManager checking against the local Syncthing instance's https public key.
*
* Based on http://stackoverflow.com/questions/16719959#16759793
*/
private class SyncthingTrustManager implements X509TrustManager {
private static final String TAG = "SyncthingTrustManager";
@Override
@SuppressLint("TrustAllX509TrustManager")
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
/**
* Verifies certs against public key of the local syncthing instance
*/
@Override
public void checkServerTrusted(X509Certificate[] certs,
String authType) throws CertificateException {
InputStream is = null;
try {
is = new FileInputStream(mHttpsCertPath);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate ca = (X509Certificate) cf.generateCertificate(is);
for (X509Certificate cert : certs) {
cert.verify(ca.getPublicKey());
}
} catch (FileNotFoundException | NoSuchAlgorithmException | InvalidKeyException |
NoSuchProviderException | SignatureException e) {
throw new CertificateException("Untrusted Certificate!", e);
} finally {
try {
if (is != null)
is.close();
} catch (IOException e) {
Log.w(TAG, e);
}
}
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
}
| src/main/java/com/nutomic/syncthingandroid/http/RestTask.java | package com.nutomic.syncthingandroid.http;
import android.annotation.SuppressLint;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.util.Pair;
import com.google.common.base.Charsets;
import com.google.common.io.ByteSource;
import com.nutomic.syncthingandroid.syncthing.RestApi;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.SignatureException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public abstract class RestTask<Params, Progress> extends
AsyncTask<Params, Progress, Pair<Boolean, String>> {
private static final String TAG = "RestTask";
/**
* The name of the HTTP header used for the syncthing API key.
*/
private static final String HEADER_API_KEY = "X-API-Key";
public interface OnSuccessListener {
public void onSuccess(String result);
}
private final URL mUrl;
protected final String mPath;
private final String mHttpsCertPath;
private final String mApiKey;
private final OnSuccessListener mListener;
public RestTask(URL url, String path, String httpsCertPath, String apiKey,
OnSuccessListener listener) {
mUrl = url;
mPath = path;
mHttpsCertPath = httpsCertPath;
mApiKey = apiKey;
mListener = listener;
}
protected HttpsURLConnection openConnection(String... params) throws IOException {
Uri.Builder uriBuilder = Uri.parse(mUrl.toString())
.buildUpon()
.path(mPath);
for (int paramCounter = 0; paramCounter + 1 < params.length; ) {
uriBuilder.appendQueryParameter(params[paramCounter++], params[paramCounter++]);
}
URL url = new URL(uriBuilder.build().toString());
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestProperty(HEADER_API_KEY, mApiKey);
connection.setHostnameVerifier((h, s) -> true);
connection.setSSLSocketFactory(getSslSocketFactory());
return connection;
}
/**
* Opens the connection, then returns success status and response string.
*/
protected Pair<Boolean, String> connect(HttpsURLConnection connection) throws IOException {
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
int responseCode = connection.getResponseCode();
String responseMessage = connection.getResponseMessage();
Log.i(TAG, "Request to " + connection.getURL() + " failed, code: " + responseCode +
", message: " + responseMessage);
return new Pair<>(false, streamToString(connection.getErrorStream()));
}
return new Pair<>(true, streamToString(connection.getInputStream()));
}
private String streamToString(InputStream is) throws IOException {
ByteSource byteSource = new ByteSource() {
@Override
public InputStream openStream() throws IOException {
return is;
}
};
return byteSource.asCharSource(Charsets.UTF_8).read();
}
protected void onPostExecute(Pair<Boolean, String> result) {
if (mListener == null || !result.first)
return;
mListener.onSuccess(result.second);
}
private SSLSocketFactory getSslSocketFactory() {
try {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{new SyncthingTrustManager()},
new SecureRandom());
return sslContext.getSocketFactory();
} catch (NoSuchAlgorithmException | KeyManagementException e) {
Log.w(TAG, e);
return null;
}
}
/*
* TrustManager checking against the local Syncthing instance's https public key.
*
* Based on http://stackoverflow.com/questions/16719959#16759793
*/
private class SyncthingTrustManager implements X509TrustManager {
private static final String TAG = "SyncthingTrustManager";
@Override
@SuppressLint("TrustAllX509TrustManager")
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
/**
* Verifies certs against public key of the local syncthing instance
*/
@Override
public void checkServerTrusted(X509Certificate[] certs,
String authType) throws CertificateException {
InputStream is = null;
try {
is = new FileInputStream(mHttpsCertPath);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate ca = (X509Certificate) cf.generateCertificate(is);
for (X509Certificate cert : certs) {
cert.verify(ca.getPublicKey());
}
} catch (FileNotFoundException | NoSuchAlgorithmException | InvalidKeyException |
NoSuchProviderException | SignatureException e) {
throw new CertificateException("Untrusted Certificate!", e);
} finally {
try {
if (is != null)
is.close();
} catch (IOException e) {
Log.w(TAG, e);
}
}
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
}
| We should close URLConnections
| src/main/java/com/nutomic/syncthingandroid/http/RestTask.java | We should close URLConnections |
|
Java | lgpl-2.1 | a01cea7cb589aa1667486a6170c109fd4312a989 | 0 | kimrutherford/intermine,zebrafishmine/intermine,Arabidopsis-Information-Portal/intermine,elsiklab/intermine,tomck/intermine,tomck/intermine,drhee/toxoMine,drhee/toxoMine,justincc/intermine,tomck/intermine,justincc/intermine,tomck/intermine,justincc/intermine,JoeCarlson/intermine,joshkh/intermine,drhee/toxoMine,justincc/intermine,Arabidopsis-Information-Portal/intermine,zebrafishmine/intermine,zebrafishmine/intermine,elsiklab/intermine,JoeCarlson/intermine,elsiklab/intermine,drhee/toxoMine,zebrafishmine/intermine,zebrafishmine/intermine,joshkh/intermine,kimrutherford/intermine,kimrutherford/intermine,Arabidopsis-Information-Portal/intermine,elsiklab/intermine,elsiklab/intermine,justincc/intermine,zebrafishmine/intermine,drhee/toxoMine,elsiklab/intermine,Arabidopsis-Information-Portal/intermine,elsiklab/intermine,kimrutherford/intermine,zebrafishmine/intermine,justincc/intermine,Arabidopsis-Information-Portal/intermine,elsiklab/intermine,kimrutherford/intermine,joshkh/intermine,drhee/toxoMine,joshkh/intermine,drhee/toxoMine,justincc/intermine,tomck/intermine,joshkh/intermine,drhee/toxoMine,joshkh/intermine,joshkh/intermine,drhee/toxoMine,joshkh/intermine,kimrutherford/intermine,tomck/intermine,JoeCarlson/intermine,kimrutherford/intermine,justincc/intermine,kimrutherford/intermine,tomck/intermine,JoeCarlson/intermine,elsiklab/intermine,kimrutherford/intermine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,JoeCarlson/intermine,JoeCarlson/intermine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,Arabidopsis-Information-Portal/intermine,tomck/intermine,JoeCarlson/intermine,joshkh/intermine,Arabidopsis-Information-Portal/intermine,zebrafishmine/intermine,tomck/intermine,justincc/intermine,zebrafishmine/intermine | package org.intermine.objectstore.intermine;
/*
* Copyright (C) 2002-2007 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import java.lang.reflect.UndeclaredThrowableException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import junit.framework.Test;
import org.intermine.model.InterMineObject;
import org.intermine.model.testmodel.Address;
import org.intermine.model.testmodel.Company;
import org.intermine.model.testmodel.Department;
import org.intermine.model.testmodel.Employee;
import org.intermine.model.testmodel.Manager;
import org.intermine.model.testmodel.Types;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreAbstractImplTestCase;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.objectstore.ObjectStoreFactory;
import org.intermine.objectstore.ObjectStoreQueriesTestCase;
import org.intermine.objectstore.query.BagConstraint;
import org.intermine.objectstore.query.ClassConstraint;
import org.intermine.objectstore.query.ConstraintOp;
import org.intermine.objectstore.query.ConstraintSet;
import org.intermine.objectstore.query.ContainsConstraint;
import org.intermine.objectstore.query.ObjectStoreBag;
import org.intermine.objectstore.query.Query;
import org.intermine.objectstore.query.QueryClass;
import org.intermine.objectstore.query.QueryCloner;
import org.intermine.objectstore.query.QueryCollectionReference;
import org.intermine.objectstore.query.QueryField;
import org.intermine.objectstore.query.QueryValue;
import org.intermine.objectstore.query.Results;
import org.intermine.objectstore.query.ResultsRow;
import org.intermine.objectstore.query.SimpleConstraint;
import org.intermine.objectstore.query.SingletonResults;
import org.intermine.objectstore.query.iql.IqlQuery;
import org.intermine.sql.query.Constraint;
public class ObjectStoreInterMineImplTest extends ObjectStoreAbstractImplTestCase
{
public static void oneTimeSetUp() throws Exception {
os = (ObjectStoreInterMineImpl) ObjectStoreFactory.getObjectStore("os.unittest");
ObjectStoreAbstractImplTestCase.oneTimeSetUp();
}
public ObjectStoreInterMineImplTest(String arg) throws Exception {
super(arg);
}
public static Test suite() {
return buildSuite(ObjectStoreInterMineImplTest.class);
}
public void testLargeOffset() throws Exception {
Query q = new Query();
QueryClass qc = new QueryClass(Address.class);
q.addFrom(qc);
q.addToSelect(qc);
Query q2 = QueryCloner.cloneQuery(q);
SingletonResults r = os.executeSingleton(q);
r.setBatchSize(2);
InterMineObject o = (InterMineObject) r.get(5);
SqlGenerator.registerOffset(q2, 6, ((ObjectStoreInterMineImpl) os).getSchema(), ((ObjectStoreInterMineImpl) os).db, o.getId(), new HashMap());
SingletonResults r2 = os.executeSingleton(q2);
r2.setBatchSize(2);
Query q3 = QueryCloner.cloneQuery(q);
SqlGenerator.registerOffset(q3, 5, ((ObjectStoreInterMineImpl) os).getSchema(), ((ObjectStoreInterMineImpl) os).db, o.getId(), new HashMap());
SingletonResults r3 = os.executeSingleton(q3);
r3.setBatchSize(2);
assertEquals(r, r2);
assertTrue(!r.equals(r3));
}
public void testLargeOffset2() throws Exception {
Employee nullEmployee = new Employee();
nullEmployee.setAge(26);
nullEmployee.setName(null);
try {
storeDataWriter.store(nullEmployee);
Query q = new Query();
QueryClass qc = new QueryClass(Employee.class);
q.addFrom(qc);
q.addToSelect(qc);
q.addToOrderBy(new QueryField(qc, "name"));
Query q2 = QueryCloner.cloneQuery(q);
SingletonResults r = os.executeSingleton(q);
r.setBatchSize(2);
Employee o = (Employee) r.get(2);
SqlGenerator.registerOffset(q2, 3, ((ObjectStoreInterMineImpl) os).getSchema(), ((ObjectStoreInterMineImpl) os).db, o.getName(), new HashMap());
SingletonResults r2 = os.executeSingleton(q2);
r2.setBatchSize(2);
Query q3 = QueryCloner.cloneQuery(q);
SqlGenerator.registerOffset(q3, 2, ((ObjectStoreInterMineImpl) os).getSchema(), ((ObjectStoreInterMineImpl) os).db, o.getName(), new HashMap());
SingletonResults r3 = os.executeSingleton(q3);
r3.setBatchSize(2);
assertEquals(r, r2);
assertTrue(!r.equals(r3));
} finally {
storeDataWriter.delete(nullEmployee);
}
}
/*public void testLargeOffset3() throws Exception {
// This is to test the indexing of large offset queries, so it needs to do a performance test.
Set toDelete = new HashSet();
try {
long start = System.currentTimeMillis();
storeDataWriter.beginTransaction();
for (int i = 0; i < 10105; i++) {
Employee e = new Employee();
String name = "Fred_";
if (i < 10000) {
name += "0";
}
if (i < 1000) {
name += "0";
}
if (i < 100) {
name += "0";
}
if (i < 10) {
name += "0";
}
e.setName(name + i);
e.setAge(i + 1000000);
storeDataWriter.store(e);
toDelete.add(e);
}
for (int i = 10105; i < 10205; i++) {
Employee e = new Employee();
e.setAge(i + 1000000);
storeDataWriter.store(e);
toDelete.add(e);
}
storeDataWriter.commitTransaction();
Connection c = null;
try {
c = ((ObjectStoreWriterInterMineImpl) storeDataWriter).getConnection();
c.createStatement().execute("ANALYSE");
} finally {
if (c != null) {
((ObjectStoreWriterInterMineImpl) storeDataWriter).releaseConnection(c);
}
}
long now = System.currentTimeMillis();
System.out.println("Took " + (now - start) + "ms to insert data");
start = now;
Query q = new Query();
QueryClass qc = new QueryClass(Employee.class);
QueryField f = new QueryField(qc, "name");
q.addFrom(qc);
q.addToSelect(f);
q.setDistinct(false);
SingletonResults r = os.executeSingleton(q);
r.setBatchSize(10);
assertEquals("Fred_00000", r.get(6));
now = System.currentTimeMillis();
System.out.println("Took " + (now - start) + "ms to find first row");
long timeA = now - start;
start = now;
assertEquals("Fred_10015", r.get(10021));
now = System.currentTimeMillis();
System.out.println("Took " + (now - start) + "ms to find row 10015");
long timeB = now - start;
start = now;
assertEquals("Fred_10035", r.get(10041));
now = System.currentTimeMillis();
System.out.println("Took " + (now - start) + "ms to find row 10035");
long timeC = now - start;
start = now;
assertNull(r.get(10141));
now = System.currentTimeMillis();
System.out.println("Took " + (now - start) + "ms to find row 10135");
long timeD = now - start;
q = QueryCloner.cloneQuery(q);
((ObjectStoreInterMineImpl) os).precompute(q);
r = os.executeSingleton(q);
r.setBatchSize(10);
now = System.currentTimeMillis();
System.out.println("Took " + (now - start) + "ms to precompute results");
start = now;
assertEquals("Fred_00000", r.get(6));
now = System.currentTimeMillis();
System.out.println("Took " + (now - start) + "ms to find first precomputed row");
long timePA = now - start;
start = now;
assertEquals("Fred_10015", r.get(10021));
now = System.currentTimeMillis();
System.out.println("Took " + (now - start) + "ms to find precomputed row 10015");
long timePB = now - start;
start = now;
assertEquals("Fred_10035", r.get(10041));
now = System.currentTimeMillis();
System.out.println("Took " + (now - start) + "ms to find precomputed row 10035");
long timePC = now - start;
start = now;
assertNull(r.get(10141));
now = System.currentTimeMillis();
System.out.println("Took " + (now - start) + "ms to find precomputed row 10135");
long timePD = now - start;
assertTrue("Row 6 found in " + timeA + "ms", timeA < 30);
assertTrue("Row 10015 found in " + timeB + "ms", timeB > 30);
assertTrue("Row 10035 found in " + timeC + "ms", timeC < 22);
assertTrue("Row 10135 found in " + timeD + "ms", timeD < 15);
assertTrue("Precomputed row 6 found in " + timePA + "ms", timePA < 30);
assertTrue("Precomputed row 10015 found in " + timePB + "ms", timePB > 30);
//TODO: This should pass - it's Postgres being thick.
//assertTrue("Precomputed row 10035 found in " + timePC + "ms", timePC < 15);
assertTrue("Precomputed row 10135 found in " + timePD + "ms", timePD < 15);
} finally {
if (storeDataWriter.isInTransaction()) {
storeDataWriter.abortTransaction();
}
long start = System.currentTimeMillis();
storeDataWriter.beginTransaction();
Iterator iter = toDelete.iterator();
while (iter.hasNext()) {
Employee e = (Employee) iter.next();
storeDataWriter.delete(e);
}
storeDataWriter.commitTransaction();
long now = System.currentTimeMillis();
System.out.println("Took " + (now - start) + "ms to remove data");
start = now;
Connection c = null;
try {
c = ((ObjectStoreWriterInterMineImpl) storeDataWriter).getConnection();
c.createStatement().execute("VACUUM FULL ANALYSE");
} finally {
if (c != null) {
((ObjectStoreWriterInterMineImpl) storeDataWriter).releaseConnection(c);
}
}
now = System.currentTimeMillis();
System.out.println("Took " + (now - start) + "ms to VACUUM FULL ANALYSE");
}
}*/
public void testPrecompute() throws Exception {
Query q = new Query();
QueryClass qc1 = new QueryClass(Department.class);
QueryClass qc2 = new QueryClass(Employee.class);
q.addFrom(qc1);
q.addFrom(qc2);
q.addToSelect(qc1);
q.addToSelect(qc2);
QueryField f1 = new QueryField(qc1, "name");
QueryField f2 = new QueryField(qc2, "name");
q.addToSelect(f1);
q.addToSelect(f2);
q.setConstraint(new ContainsConstraint(new QueryCollectionReference(qc1, "employees"), ConstraintOp.CONTAINS, qc2));
q.setDistinct(false);
Set indexes = new LinkedHashSet();
indexes.add(qc1);
indexes.add(f1);
indexes.add(f2);
String tableName = ((ObjectStoreInterMineImpl) os).precompute(q, indexes, "test");
Connection con = null;
Map indexMap = new HashMap();
try {
con = ((ObjectStoreInterMineImpl) os).getConnection();
Statement s = con.createStatement();
ResultSet r = s.executeQuery("SELECT * FROM pg_indexes WHERE tablename = '" + tableName + "'");
while (r.next()) {
indexMap.put(r.getString("indexname"), r.getString("indexdef"));
}
} finally {
if (con != null) {
((ObjectStoreInterMineImpl) os).releaseConnection(con);
}
}
Map expectedIndexMap = new HashMap();
expectedIndexMap.put("index" + tableName + "_field_orderby_field", "CREATE INDEX index" + tableName + "_field_orderby_field ON " + tableName + " USING btree (orderby_field)");
expectedIndexMap.put("index" + tableName + "_field_a1_id__lower_a3____lower_a4__", "CREATE INDEX index" + tableName + "_field_a1_id__lower_a3____lower_a4__ ON " + tableName + " USING btree (a1_id, lower(a3_), lower(a4_))");
expectedIndexMap.put("index" + tableName + "_field_lower_a3__", "CREATE INDEX index" + tableName + "_field_lower_a3__ ON " + tableName + " USING btree (lower(a3_))");
expectedIndexMap.put("index" + tableName + "_field_lower_a3___nulls", "CREATE INDEX index" + tableName + "_field_lower_a3___nulls ON " + tableName + " USING btree (((lower(a3_) IS NULL)))");
expectedIndexMap.put("index" + tableName + "_field_lower_a4__", "CREATE INDEX index" + tableName + "_field_lower_a4__ ON " + tableName + " USING btree (lower(a4_))");
expectedIndexMap.put("index" + tableName + "_field_lower_a4___nulls", "CREATE INDEX index" + tableName + "_field_lower_a4___nulls ON " + tableName + " USING btree (((lower(a4_) IS NULL)))");
assertEquals(expectedIndexMap, indexMap);
}
public void testGoFaster() throws Exception {
Query q = new IqlQuery("SELECT Company, Department FROM Company, Department WHERE Department.company CONTAINS Company", "org.intermine.model.testmodel").toQuery();
try {
((ObjectStoreInterMineImpl) os).goFaster(q);
Results r = os.execute(q);
r.get(0);
assertEquals(3, r.size());
} finally {
((ObjectStoreInterMineImpl) os).releaseGoFaster(q);
}
}
public void testPrecomputeWithNullsInOrder() throws Exception {
Types t1 = new Types();
t1.setIntObjType(null);
t1.setLongObjType(new Long(234212354));
t1.setName("fred");
storeDataWriter.store(t1);
Types t2 = new Types();
t2.setIntObjType(new Integer(278652));
t2.setLongObjType(null);
t2.setName("fred");
storeDataWriter.store(t2);
Query q = new Query();
QueryClass qc = new QueryClass(Types.class);
QueryField into = new QueryField(qc, "intObjType");
QueryField longo = new QueryField(qc, "longObjType");
q.addFrom(qc);
q.addToSelect(into);
q.addToSelect(longo);
q.addToSelect(qc);
q.setDistinct(false);
((ObjectStoreInterMineImpl) os).precompute(q, "test");
Results r = os.execute(q);
r.setBatchSize(1);
SqlGenerator.registerOffset(q, 1, ((ObjectStoreInterMineImpl) os).getSchema(), ((ObjectStoreInterMineImpl) os).db, new Integer(100000), new HashMap());
ResultsRow row = (ResultsRow) r.get(1);
InterMineObject o = (InterMineObject) row.get(2);
assertEquals("Expected " + t2.toString() + " but got " + o.toString(), t2.getId(), o.getId());
row = (ResultsRow) r.get(2);
o = (InterMineObject) row.get(2);
assertEquals("Expected " + t1.toString() + " but got " + o.toString(), t1.getId(), o.getId());
q.setConstraint(new SimpleConstraint(into, ConstraintOp.GREATER_THAN, new QueryValue(new Integer(100000))));
q = QueryCloner.cloneQuery(q);
r = os.execute(q);
r.setBatchSize(10);
row = (ResultsRow) r.get(0);
o = (InterMineObject) row.get(2);
assertEquals("Expected " + t2.toString() + " but got " + o.toString(), t2.getId(), o.getId());
assertEquals(1, r.size());
storeDataWriter.delete(t1);
storeDataWriter.delete(t2);
}
public void testPrecomputeWithNegatives() throws Exception {
Types t1 = new Types();
t1.setLongObjType(new Long(-765187651234L));
t1.setIntObjType(new Integer(278652));
t1.setName("Fred");
storeDataWriter.store(t1);
Query q = new Query();
QueryClass qc = new QueryClass(Types.class);
QueryField into = new QueryField(qc, "intObjType");
QueryField longo = new QueryField(qc, "longObjType");
q.addFrom(qc);
q.addToSelect(into);
q.addToSelect(longo);
q.addToSelect(qc);
q.setDistinct(false);
((ObjectStoreInterMineImpl) os).precompute(q, "test");
Results r = os.execute(q);
r.setBatchSize(1);
SqlGenerator.registerOffset(q, 1, ((ObjectStoreInterMineImpl) os).getSchema(), ((ObjectStoreInterMineImpl) os).db, new Integer(278651), new HashMap());
ResultsRow row = (ResultsRow) r.get(1);
InterMineObject o = (InterMineObject) row.get(2);
assertEquals("Expected " + t1.toString() + " but got " + o.toString(), t1.getId(), o.getId());
try {
r.get(2);
fail("Expected size to be 2");
} catch (Exception e) {
}
assertEquals(2, r.size());
storeDataWriter.delete(t1);
}
public void testCancelMethods1() throws Exception {
Object id = "flibble1";
Connection c = ((ObjectStoreInterMineImpl) os).getConnection();
try {
Statement s = c.createStatement();
((ObjectStoreInterMineImpl) os).registerRequestId(id);
((ObjectStoreInterMineImpl) os).registerStatement(s);
((ObjectStoreInterMineImpl) os).deregisterStatement(s);
((ObjectStoreInterMineImpl) os).deregisterRequestId(id);
} finally {
((ObjectStoreInterMineImpl) os).releaseConnection(c);
}
}
public void testCancelMethods2() throws Exception {
Object id = "flibble2";
Connection c = ((ObjectStoreInterMineImpl) os).getConnection();
try {
Statement s = c.createStatement();
((ObjectStoreInterMineImpl) os).registerRequestId(id);
((ObjectStoreInterMineImpl) os).registerStatement(s);
((ObjectStoreInterMineImpl) os).cancelRequest(id);
((ObjectStoreInterMineImpl) os).deregisterStatement(s);
((ObjectStoreInterMineImpl) os).deregisterRequestId(id);
} finally {
((ObjectStoreInterMineImpl) os).releaseConnection(c);
}
}
public void testCancelMethods3() throws Exception {
Object id = "flibble3";
try {
((ObjectStoreInterMineImpl) os).deregisterRequestId(id);
fail("Should have thrown exception");
} catch (ObjectStoreException e) {
assertEquals("This Thread is not registered with ID flibble3", e.getMessage());
}
}
public void testCancelMethods4() throws Exception {
Object id = "flibble4";
// this test sometimes fails even when all is OK, so run it multiple times and exit if it
// passes
for (int i = 0 ;i < 20 ; i++) {
Connection c = ((ObjectStoreInterMineImpl) os).getConnection();
try {
Statement s = c.createStatement();
((ObjectStoreInterMineImpl) os).registerRequestId(id);
((ObjectStoreInterMineImpl) os).cancelRequest(id);
((ObjectStoreInterMineImpl) os).registerStatement(s);
fail("Should have thrown exception");
} catch (ObjectStoreException e) {
assertEquals("Request id flibble4 is cancelled", e.getMessage());
} finally {
((ObjectStoreInterMineImpl) os).deregisterRequestId(id);
((ObjectStoreInterMineImpl) os).releaseConnection(c);
}
}
}
public void testCancelMethods5() throws Exception {
UndeclaredThrowableException failure = null;
// this test sometimes fails even when all is OK, so run it multiple times and exit if it
// passes
for (int i = 0 ;i < 20 ; i++) {
Object id = "flibble5";
Connection c = ((ObjectStoreInterMineImpl) os).getConnection();
Statement s = null;
try {
s = c.createStatement();
((ObjectStoreInterMineImpl) os).registerRequestId(id);
((ObjectStoreInterMineImpl) os).registerStatement(s);
((ObjectStoreInterMineImpl) os).registerStatement(s);
fail("Should have thrown exception");
} catch (ObjectStoreException e) {
assertEquals("Request id flibble5 is currently being serviced in another thread. Don't share request IDs over multiple threads!", e.getMessage());
// test passed so stop immediately
return;
} catch (UndeclaredThrowableException t) {
// test failed but might pass next time - try again
failure = t;
} finally {
if (s != null) {
((ObjectStoreInterMineImpl) os).deregisterStatement(s);
}
((ObjectStoreInterMineImpl) os).deregisterRequestId(id);
((ObjectStoreInterMineImpl) os).releaseConnection(c);
}
}
throw failure;
}
/*
public void testCancelMethods6() throws Exception {
Object id = "flibble6";
Connection c = ((ObjectStoreInterMineImpl) os).getConnection();
Statement s = null;
long start = 0;
try {
s = c.createStatement();
s.execute("CREATE TABLE test (col1 int, col2 int)");
s.execute("INSERT INTO test VALUES (1, 1)");
s.execute("INSERT INTO test VALUES (1, 2)");
s.execute("INSERT INTO test VALUES (2, 1)");
s.execute("INSERT INTO test VALUES (2, 2)");
((ObjectStoreInterMineImpl) os).registerRequestId(id);
((ObjectStoreInterMineImpl) os).registerStatement(s);
Thread delayedCancel = new Thread(new DelayedCancel(id));
delayedCancel.start();
start = System.currentTimeMillis();
s.executeQuery("SELECT * FROM test AS a, test AS b, test AS c, test AS d, test AS e, test AS f, test AS g, test AS h, test AS i, test AS j, test AS k, test AS l, test AS m WHERE a.col2 = b.col1 AND b.col2 = c.col1 AND c.col2 = d.col1 AND d.col2 = e.col1 AND e.col2 = f.col1 AND f.col2 = g.col1 AND g.col2 = h.col1 AND h.col2 = i.col1 AND i.col2 = j.col1 AND j.col2 = k.col1 AND k.col2 = l.col1 AND l.col2 = m.col1");
System.out.println("testCancelMethods6: time for query = " + (System.currentTimeMillis() - start) + " ms");
fail("Request should have been cancelled");
} catch (SQLException e) {
if (start != 0) {
System.out.println("testCancelMethods6: time for query = " + (System.currentTimeMillis() - start) + " ms");
}
String errorString = e.getMessage().replaceFirst("statement", "query");
assertEquals("ERROR: canceling query due to user request", errorString);
} finally {
if (s != null) {
try {
((ObjectStoreInterMineImpl) os).deregisterStatement(s);
} catch (ObjectStoreException e) {
e.printStackTrace(System.out);
}
}
try {
((ObjectStoreInterMineImpl) os).deregisterRequestId(id);
} catch (ObjectStoreException e) {
e.printStackTrace(System.out);
}
try {
c.createStatement().execute("DROP TABLE test");
} catch (SQLException e) {
}
((ObjectStoreInterMineImpl) os).releaseConnection(c);
}
}
*/
/*This test does not work. This is due to a failing of JDBC. The Statement.cancel() method is
* not fully Thread-safe, in that if one performs a cancel() request just before a Statement is
* used, that operation will not be cancelled. There is a race condition between the
* ObjectStore.execute() method registering the Statement and the Statement becoming
* cancellable.
public void testCancelMethods7() throws Exception {
Object id = "flibble7";
Connection c = ((ObjectStoreInterMineImpl) os).getConnection();
Statement s = null;
long start = 0;
try {
s = c.createStatement();
s.execute("CREATE TABLE test (col1 int, col2 int)");
s.execute("INSERT INTO test VALUES (1, 1)");
s.execute("INSERT INTO test VALUES (1, 2)");
s.execute("INSERT INTO test VALUES (2, 1)");
s.execute("INSERT INTO test VALUES (2, 2)");
((ObjectStoreInterMineImpl) os).registerRequestId(id);
((ObjectStoreInterMineImpl) os).registerStatement(s);
start = System.currentTimeMillis();
s.cancel();
s.executeQuery("SELECT * FROM test AS a, test AS b, test AS c, test AS d, test AS e, test AS f, test AS g, test AS h, test AS i, test AS j, test AS k, test AS l, test AS m WHERE a.col2 = b.col1 AND b.col2 = c.col1 AND c.col2 = d.col1 AND d.col2 = e.col1 AND e.col2 = f.col1 AND f.col2 = g.col1 AND g.col2 = h.col1 AND h.col2 = i.col1 AND i.col2 = j.col1 AND j.col2 = k.col1 AND k.col2 = l.col1 AND l.col2 = m.col1");
System.out.println("testCancelMethods6: time for query = " + (System.currentTimeMillis() - start) + " ms");
fail("Request should have been cancelled");
} catch (SQLException e) {
if (start != 0) {
System.out.println("testCancelMethods6: time for query = " + (System.currentTimeMillis() - start) + " ms");
}
assertEquals("ERROR: canceling query due to user request", e.getMessage());
} finally {
if (s != null) {
try {
((ObjectStoreInterMineImpl) os).deregisterStatement(s);
} catch (ObjectStoreException e) {
e.printStackTrace(System.out);
}
}
try {
((ObjectStoreInterMineImpl) os).deregisterRequestId(id);
} catch (ObjectStoreException e) {
e.printStackTrace(System.out);
}
try {
c.createStatement().execute("DROP TABLE test");
} catch (SQLException e) {
}
((ObjectStoreInterMineImpl) os).releaseConnection(c);
}
}
public void testCancel() throws Exception {
Object id = "flibble8";
Query q = new IqlQuery("SELECT a, b, c, d, e FROM Employee AS a, Employee AS b, Employee AS c, Employee AS d, Employee AS e", "org.intermine.model.testmodel").toQuery();
((ObjectStoreInterMineImpl) os).registerRequestId(id);
try {
Thread delayedCancel = new Thread(new DelayedCancel(id));
delayedCancel.start();
Results r = os.execute(q);
r.setBatchSize(10000);
r.setNoOptimise();
r.setNoExplain();
r.get(0);
fail("Operation should have been cancelled");
} catch (RuntimeException e) {
assertEquals("ObjectStore error has occured (in get)", e.getMessage());
Throwable t = e.getCause();
if (!"Request id flibble8 is cancelled".equals(t.getMessage())) {
t = t.getCause();
String errorString = t.getMessage().replaceFirst("statement", "query");
assertEquals("ERROR: canceling query due to user request",errorString);
}
} finally {
((ObjectStoreInterMineImpl) os).deregisterRequestId(id);
}
}
*/
public void testCreateTempBagTables() throws Exception {
Query q = ObjectStoreQueriesTestCase.bagConstraint();
Map bagTableNames = ((ObjectStoreInterMineImpl) os).bagConstraintTables;
bagTableNames.clear();
Connection con = null;
try {
con = ((ObjectStoreInterMineImpl) os).getConnection();
con.setAutoCommit(false);
int minBagSize = ((ObjectStoreInterMineImpl) os).minBagTableSize;
((ObjectStoreInterMineImpl) os).minBagTableSize = 1;
((ObjectStoreInterMineImpl) os).createTempBagTables(con, q);
((ObjectStoreInterMineImpl) os).minBagTableSize = minBagSize;
assertEquals("Entries: " + bagTableNames, 1, bagTableNames.size());
String tableName = (String) bagTableNames.values().iterator().next();
Set expected = new HashSet();
Iterator bagIter = ((BagConstraint) q.getConstraint()).getBag().iterator();
while (bagIter.hasNext()) {
Object thisObject = bagIter.next();
if (thisObject instanceof String) {
expected.add(thisObject);
}
}
Statement s = con.createStatement();
ResultSet r = s.executeQuery("SELECT value FROM " + tableName);
r.next();
Set resultStrings = new HashSet();
resultStrings.add(r.getString(1));
r.next();
resultStrings.add(r.getString(1));
r.next();
resultStrings.add(r.getString(1));
try {
r.next();
} catch (SQLException e) {
// expected
}
assertEquals(expected, resultStrings);
} finally {
if (con != null) {
con.commit();
con.setAutoCommit(true);
((ObjectStoreInterMineImpl) os).releaseConnection(con);
}
}
}
public void testGetUniqueInteger() throws Exception {
ObjectStoreInterMineImpl osii = (ObjectStoreInterMineImpl) os;
Connection con = osii.getConnection();
con.setAutoCommit(false);
int integer1 = osii.getUniqueInteger(con);
int integer2 = osii.getUniqueInteger(con);
assertTrue(integer2 > integer1);
con.setAutoCommit(true);
int integer3 = osii.getUniqueInteger(con);
int integer4 = osii.getUniqueInteger(con);
assertTrue(integer3 > integer2);
assertTrue(integer4 > integer3);
}
private static class DelayedCancel implements Runnable
{
private Object id;
public DelayedCancel(Object id) {
this.id = id;
}
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
try {
((ObjectStoreInterMineImpl) os).cancelRequest(id);
} catch (ObjectStoreException e) {
e.printStackTrace(System.out);
}
}
}
public void testIsPrecomputed() throws Exception {
Query q = new Query();
QueryClass qc = new QueryClass(Employee.class);
QueryField qf = new QueryField(qc,"age");
SimpleConstraint sc = new SimpleConstraint(qf,ConstraintOp.GREATER_THAN,new QueryValue(new Integer(20)));
q.addToSelect(qc);
q.addFrom(qc);
q.setConstraint(sc);
assertFalse(((ObjectStoreInterMineImpl)os).isPrecomputed(q,"template"));
((ObjectStoreInterMineImpl)os).precompute(q, "template");
assertTrue(((ObjectStoreInterMineImpl)os).isPrecomputed(q,"template"));
ObjectStoreBag osb = storeDataWriter.createObjectStoreBag();
storeDataWriter.addToBag(osb, new Integer(5));
assertTrue(((ObjectStoreInterMineImpl)os).isPrecomputed(q,"template"));
storeDataWriter.store((Employee) data.get("EmployeeA1"));
assertFalse(((ObjectStoreInterMineImpl)os).isPrecomputed(q,"template"));
}
public void testObjectStoreBag() throws Exception {
System.out.println("Starting testObjectStoreBag");
ObjectStoreBag osb = storeDataWriter.createObjectStoreBag();
ArrayList coll = new ArrayList();
coll.add(new Integer(3));
coll.add(((Employee) data.get("EmployeeA1")).getId());
coll.add(((Employee) data.get("EmployeeA2")).getId());
coll.add(new Integer(20));
coll.add(new Integer(23));
coll.add(new Integer(30));
storeDataWriter.beginTransaction();
storeDataWriter.addAllToBag(osb, coll);
Query q = new Query();
q.addToSelect(osb);
SingletonResults r = os.executeSingleton(q);
assertEquals(Collections.EMPTY_LIST, r);
q = new Query();
q.addToSelect(osb);
r = os.executeSingleton(q);
storeDataWriter.commitTransaction();
try {
r.get(0);
fail("Expected: ConcurrentModificationException");
} catch (ConcurrentModificationException e) {
}
q = new Query();
q.addToSelect(osb);
r = os.executeSingleton(q);
assertEquals(coll, r);
q = new Query();
QueryClass qc = new QueryClass(Employee.class);
q.addFrom(qc);
q.addToSelect(qc);
q.setConstraint(new BagConstraint(qc, ConstraintOp.IN, osb));
r = os.executeSingleton(q);
assertEquals(Arrays.asList(new Object[] {data.get("EmployeeA1"), data.get("EmployeeA2")}), r);
ObjectStoreBag osb2 = storeDataWriter.createObjectStoreBag();
storeDataWriter.addToBag(osb2, ((Employee) data.get("EmployeeA1")).getId());
storeDataWriter.addToBagFromQuery(osb2, q);
q = new Query();
q.addToSelect(osb2);
r = os.executeSingleton(q);
assertEquals(Arrays.asList(new Object[] {((Employee) data.get("EmployeeA1")).getId(), ((Employee) data.get("EmployeeA2")).getId()}), r);
}
public void testClosedConnectionBug() throws Exception {
Query pq = new Query();
QueryClass qc = new QueryClass(Employee.class);
pq.addFrom(qc);
pq.addToSelect(qc);
((ObjectStoreInterMineImpl) os).precompute(pq, "Whatever");
Query q = new Query();
QueryClass qc1 = new QueryClass(Manager.class);
QueryClass qc2 = new QueryClass(Manager.class);
QueryClass qc3 = new QueryClass(Manager.class);
QueryClass qc4 = new QueryClass(Manager.class);
QueryClass qc5 = new QueryClass(Manager.class);
QueryClass qc6 = new QueryClass(Manager.class);
QueryClass qc7 = new QueryClass(Manager.class);
QueryClass qc8 = new QueryClass(Manager.class);
QueryClass qc9 = new QueryClass(Manager.class);
q.addFrom(qc1);
q.addFrom(qc2);
q.addFrom(qc3);
q.addFrom(qc4);
q.addFrom(qc5);
q.addFrom(qc6);
q.addFrom(qc7);
q.addFrom(qc8);
q.addFrom(qc9);
q.addToSelect(qc1);
q.addToSelect(qc2);
q.addToSelect(qc3);
q.addToSelect(qc4);
q.addToSelect(qc5);
q.addToSelect(qc6);
q.addToSelect(qc7);
q.addToSelect(qc8);
q.addToSelect(qc9);
ConstraintSet cs = new ConstraintSet(ConstraintOp.AND);
q.setConstraint(cs);
cs.addConstraint(new SimpleConstraint(new QueryField(qc1, "id"), ConstraintOp.EQUALS, new QueryValue(new Integer(1))));
cs.addConstraint(new SimpleConstraint(new QueryField(qc1, "id"), ConstraintOp.EQUALS, new QueryValue(new Integer(2))));
cs.addConstraint(new ClassConstraint(qc1, ConstraintOp.EQUALS, qc2));
cs.addConstraint(new ClassConstraint(qc1, ConstraintOp.EQUALS, qc3));
cs.addConstraint(new ClassConstraint(qc1, ConstraintOp.EQUALS, qc4));
cs.addConstraint(new ClassConstraint(qc1, ConstraintOp.EQUALS, qc5));
cs.addConstraint(new ClassConstraint(qc1, ConstraintOp.EQUALS, qc6));
cs.addConstraint(new ClassConstraint(qc1, ConstraintOp.EQUALS, qc7));
cs.addConstraint(new ClassConstraint(qc1, ConstraintOp.EQUALS, qc8));
cs.addConstraint(new ClassConstraint(qc1, ConstraintOp.EQUALS, qc9));
assertEquals(Collections.EMPTY_LIST, os.execute(q, 0, 1000, true, true, ObjectStore.SEQUENCE_IGNORE));
}
public void testFailFast() throws Exception {
Query q1 = new Query();
ObjectStoreBag osb1 = new ObjectStoreBag(100);
q1.addToSelect(osb1);
Query q2 = new Query();
ObjectStoreBag osb2 = new ObjectStoreBag(200);
q2.addToSelect(osb2);
Query q3 = new Query();
QueryClass qc1 = new QueryClass(Employee.class);
q3.addFrom(qc1);
q3.addToSelect(qc1);
Results r1 = os.execute(q1);
Results r2 = os.execute(q2);
Results r3 = os.execute(q3);
storeDataWriter.addToBag(osb1, new Integer(1));
try {
r1.iterator().hasNext();
fail("Expected: ConcurrentModificationException");
} catch (ConcurrentModificationException e) {
}
r2.iterator().hasNext();
r3.iterator().hasNext();
r1 = os.execute(q1);
r2 = os.execute(q2);
r3 = os.execute(q3);
storeDataWriter.addToBag(osb2, new Integer(2));
r1.iterator().hasNext();
try {
r2.iterator().hasNext();
fail("Expected: ConcurrentModificationException");
} catch (ConcurrentModificationException e) {
}
r3.iterator().hasNext();
r1 = os.execute(q1);
r2 = os.execute(q2);
r3 = os.execute(q3);
storeDataWriter.store((Employee) data.get("EmployeeA1"));
r1.iterator().hasNext();
r2.iterator().hasNext();
try {
r3.iterator().hasNext();
fail("Expected: ConcurrentModificationException");
} catch (ConcurrentModificationException e) {
}
}
}
| intermine/objectstore/test/src/org/intermine/objectstore/intermine/ObjectStoreInterMineImplTest.java | package org.intermine.objectstore.intermine;
/*
* Copyright (C) 2002-2007 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import java.lang.reflect.UndeclaredThrowableException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import junit.framework.Test;
import org.intermine.model.InterMineObject;
import org.intermine.model.testmodel.Address;
import org.intermine.model.testmodel.Company;
import org.intermine.model.testmodel.Department;
import org.intermine.model.testmodel.Employee;
import org.intermine.model.testmodel.Manager;
import org.intermine.model.testmodel.Types;
import org.intermine.objectstore.ObjectStore;
import org.intermine.objectstore.ObjectStoreAbstractImplTestCase;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.objectstore.ObjectStoreFactory;
import org.intermine.objectstore.ObjectStoreQueriesTestCase;
import org.intermine.objectstore.query.BagConstraint;
import org.intermine.objectstore.query.ClassConstraint;
import org.intermine.objectstore.query.ConstraintOp;
import org.intermine.objectstore.query.ConstraintSet;
import org.intermine.objectstore.query.ContainsConstraint;
import org.intermine.objectstore.query.ObjectStoreBag;
import org.intermine.objectstore.query.Query;
import org.intermine.objectstore.query.QueryClass;
import org.intermine.objectstore.query.QueryCloner;
import org.intermine.objectstore.query.QueryCollectionReference;
import org.intermine.objectstore.query.QueryField;
import org.intermine.objectstore.query.QueryValue;
import org.intermine.objectstore.query.Results;
import org.intermine.objectstore.query.ResultsRow;
import org.intermine.objectstore.query.SimpleConstraint;
import org.intermine.objectstore.query.SingletonResults;
import org.intermine.objectstore.query.iql.IqlQuery;
import org.intermine.sql.query.Constraint;
public class ObjectStoreInterMineImplTest extends ObjectStoreAbstractImplTestCase
{
public static void oneTimeSetUp() throws Exception {
os = (ObjectStoreInterMineImpl) ObjectStoreFactory.getObjectStore("os.unittest");
ObjectStoreAbstractImplTestCase.oneTimeSetUp();
}
public ObjectStoreInterMineImplTest(String arg) throws Exception {
super(arg);
}
public static Test suite() {
return buildSuite(ObjectStoreInterMineImplTest.class);
}
public void testLargeOffset() throws Exception {
Query q = new Query();
QueryClass qc = new QueryClass(Address.class);
q.addFrom(qc);
q.addToSelect(qc);
Query q2 = QueryCloner.cloneQuery(q);
SingletonResults r = os.executeSingleton(q);
r.setBatchSize(2);
InterMineObject o = (InterMineObject) r.get(5);
SqlGenerator.registerOffset(q2, 6, ((ObjectStoreInterMineImpl) os).getSchema(), ((ObjectStoreInterMineImpl) os).db, o.getId(), new HashMap());
SingletonResults r2 = os.executeSingleton(q2);
r2.setBatchSize(2);
Query q3 = QueryCloner.cloneQuery(q);
SqlGenerator.registerOffset(q3, 5, ((ObjectStoreInterMineImpl) os).getSchema(), ((ObjectStoreInterMineImpl) os).db, o.getId(), new HashMap());
SingletonResults r3 = os.executeSingleton(q3);
r3.setBatchSize(2);
assertEquals(r, r2);
assertTrue(!r.equals(r3));
}
public void testLargeOffset2() throws Exception {
Employee nullEmployee = new Employee();
nullEmployee.setAge(26);
nullEmployee.setName(null);
try {
storeDataWriter.store(nullEmployee);
Query q = new Query();
QueryClass qc = new QueryClass(Employee.class);
q.addFrom(qc);
q.addToSelect(qc);
q.addToOrderBy(new QueryField(qc, "name"));
Query q2 = QueryCloner.cloneQuery(q);
SingletonResults r = os.executeSingleton(q);
r.setBatchSize(2);
Employee o = (Employee) r.get(2);
SqlGenerator.registerOffset(q2, 3, ((ObjectStoreInterMineImpl) os).getSchema(), ((ObjectStoreInterMineImpl) os).db, o.getName(), new HashMap());
SingletonResults r2 = os.executeSingleton(q2);
r2.setBatchSize(2);
Query q3 = QueryCloner.cloneQuery(q);
SqlGenerator.registerOffset(q3, 2, ((ObjectStoreInterMineImpl) os).getSchema(), ((ObjectStoreInterMineImpl) os).db, o.getName(), new HashMap());
SingletonResults r3 = os.executeSingleton(q3);
r3.setBatchSize(2);
assertEquals(r, r2);
assertTrue(!r.equals(r3));
} finally {
storeDataWriter.delete(nullEmployee);
}
}
/*public void testLargeOffset3() throws Exception {
// This is to test the indexing of large offset queries, so it needs to do a performance test.
Set toDelete = new HashSet();
try {
long start = System.currentTimeMillis();
storeDataWriter.beginTransaction();
for (int i = 0; i < 10105; i++) {
Employee e = new Employee();
String name = "Fred_";
if (i < 10000) {
name += "0";
}
if (i < 1000) {
name += "0";
}
if (i < 100) {
name += "0";
}
if (i < 10) {
name += "0";
}
e.setName(name + i);
e.setAge(i + 1000000);
storeDataWriter.store(e);
toDelete.add(e);
}
for (int i = 10105; i < 10205; i++) {
Employee e = new Employee();
e.setAge(i + 1000000);
storeDataWriter.store(e);
toDelete.add(e);
}
storeDataWriter.commitTransaction();
Connection c = null;
try {
c = ((ObjectStoreWriterInterMineImpl) storeDataWriter).getConnection();
c.createStatement().execute("ANALYSE");
} finally {
if (c != null) {
((ObjectStoreWriterInterMineImpl) storeDataWriter).releaseConnection(c);
}
}
long now = System.currentTimeMillis();
System.out.println("Took " + (now - start) + "ms to insert data");
start = now;
Query q = new Query();
QueryClass qc = new QueryClass(Employee.class);
QueryField f = new QueryField(qc, "name");
q.addFrom(qc);
q.addToSelect(f);
q.setDistinct(false);
SingletonResults r = os.executeSingleton(q);
r.setBatchSize(10);
assertEquals("Fred_00000", r.get(6));
now = System.currentTimeMillis();
System.out.println("Took " + (now - start) + "ms to find first row");
long timeA = now - start;
start = now;
assertEquals("Fred_10015", r.get(10021));
now = System.currentTimeMillis();
System.out.println("Took " + (now - start) + "ms to find row 10015");
long timeB = now - start;
start = now;
assertEquals("Fred_10035", r.get(10041));
now = System.currentTimeMillis();
System.out.println("Took " + (now - start) + "ms to find row 10035");
long timeC = now - start;
start = now;
assertNull(r.get(10141));
now = System.currentTimeMillis();
System.out.println("Took " + (now - start) + "ms to find row 10135");
long timeD = now - start;
q = QueryCloner.cloneQuery(q);
((ObjectStoreInterMineImpl) os).precompute(q);
r = os.executeSingleton(q);
r.setBatchSize(10);
now = System.currentTimeMillis();
System.out.println("Took " + (now - start) + "ms to precompute results");
start = now;
assertEquals("Fred_00000", r.get(6));
now = System.currentTimeMillis();
System.out.println("Took " + (now - start) + "ms to find first precomputed row");
long timePA = now - start;
start = now;
assertEquals("Fred_10015", r.get(10021));
now = System.currentTimeMillis();
System.out.println("Took " + (now - start) + "ms to find precomputed row 10015");
long timePB = now - start;
start = now;
assertEquals("Fred_10035", r.get(10041));
now = System.currentTimeMillis();
System.out.println("Took " + (now - start) + "ms to find precomputed row 10035");
long timePC = now - start;
start = now;
assertNull(r.get(10141));
now = System.currentTimeMillis();
System.out.println("Took " + (now - start) + "ms to find precomputed row 10135");
long timePD = now - start;
assertTrue("Row 6 found in " + timeA + "ms", timeA < 30);
assertTrue("Row 10015 found in " + timeB + "ms", timeB > 30);
assertTrue("Row 10035 found in " + timeC + "ms", timeC < 22);
assertTrue("Row 10135 found in " + timeD + "ms", timeD < 15);
assertTrue("Precomputed row 6 found in " + timePA + "ms", timePA < 30);
assertTrue("Precomputed row 10015 found in " + timePB + "ms", timePB > 30);
//TODO: This should pass - it's Postgres being thick.
//assertTrue("Precomputed row 10035 found in " + timePC + "ms", timePC < 15);
assertTrue("Precomputed row 10135 found in " + timePD + "ms", timePD < 15);
} finally {
if (storeDataWriter.isInTransaction()) {
storeDataWriter.abortTransaction();
}
long start = System.currentTimeMillis();
storeDataWriter.beginTransaction();
Iterator iter = toDelete.iterator();
while (iter.hasNext()) {
Employee e = (Employee) iter.next();
storeDataWriter.delete(e);
}
storeDataWriter.commitTransaction();
long now = System.currentTimeMillis();
System.out.println("Took " + (now - start) + "ms to remove data");
start = now;
Connection c = null;
try {
c = ((ObjectStoreWriterInterMineImpl) storeDataWriter).getConnection();
c.createStatement().execute("VACUUM FULL ANALYSE");
} finally {
if (c != null) {
((ObjectStoreWriterInterMineImpl) storeDataWriter).releaseConnection(c);
}
}
now = System.currentTimeMillis();
System.out.println("Took " + (now - start) + "ms to VACUUM FULL ANALYSE");
}
}*/
public void testPrecompute() throws Exception {
Query q = new Query();
QueryClass qc1 = new QueryClass(Department.class);
QueryClass qc2 = new QueryClass(Employee.class);
q.addFrom(qc1);
q.addFrom(qc2);
q.addToSelect(qc1);
q.addToSelect(qc2);
QueryField f1 = new QueryField(qc1, "name");
QueryField f2 = new QueryField(qc2, "name");
q.addToSelect(f1);
q.addToSelect(f2);
q.setConstraint(new ContainsConstraint(new QueryCollectionReference(qc1, "employees"), ConstraintOp.CONTAINS, qc2));
q.setDistinct(false);
Set indexes = new LinkedHashSet();
indexes.add(qc1);
indexes.add(f1);
indexes.add(f2);
String tableName = ((ObjectStoreInterMineImpl) os).precompute(q, indexes, "test");
Connection con = null;
Map indexMap = new HashMap();
try {
con = ((ObjectStoreInterMineImpl) os).getConnection();
Statement s = con.createStatement();
ResultSet r = s.executeQuery("SELECT * FROM pg_indexes WHERE tablename = '" + tableName + "'");
while (r.next()) {
indexMap.put(r.getString("indexname"), r.getString("indexdef"));
}
} finally {
if (con != null) {
((ObjectStoreInterMineImpl) os).releaseConnection(con);
}
}
Map expectedIndexMap = new HashMap();
expectedIndexMap.put("index" + tableName + "_field_orderby_field", "CREATE INDEX index" + tableName + "_field_orderby_field ON " + tableName + " USING btree (orderby_field)");
expectedIndexMap.put("index" + tableName + "_field_a1_id__lower_a3____lower_a4__", "CREATE INDEX index" + tableName + "_field_a1_id__lower_a3____lower_a4__ ON " + tableName + " USING btree (a1_id, lower(a3_), lower(a4_))");
expectedIndexMap.put("index" + tableName + "_field_lower_a3__", "CREATE INDEX index" + tableName + "_field_lower_a3__ ON " + tableName + " USING btree (lower(a3_))");
expectedIndexMap.put("index" + tableName + "_field_lower_a3___nulls", "CREATE INDEX index" + tableName + "_field_lower_a3___nulls ON " + tableName + " USING btree (((lower(a3_) IS NULL)))");
expectedIndexMap.put("index" + tableName + "_field_lower_a4__", "CREATE INDEX index" + tableName + "_field_lower_a4__ ON " + tableName + " USING btree (lower(a4_))");
expectedIndexMap.put("index" + tableName + "_field_lower_a4___nulls", "CREATE INDEX index" + tableName + "_field_lower_a4___nulls ON " + tableName + " USING btree (((lower(a4_) IS NULL)))");
assertEquals(expectedIndexMap, indexMap);
}
public void testGoFaster() throws Exception {
Query q = new IqlQuery("SELECT Company, Department FROM Company, Department WHERE Department.company CONTAINS Company", "org.intermine.model.testmodel").toQuery();
try {
((ObjectStoreInterMineImpl) os).goFaster(q);
Results r = os.execute(q);
r.get(0);
assertEquals(3, r.size());
} finally {
((ObjectStoreInterMineImpl) os).releaseGoFaster(q);
}
}
public void testPrecomputeWithNullsInOrder() throws Exception {
Types t1 = new Types();
t1.setIntObjType(null);
t1.setLongObjType(new Long(234212354));
t1.setName("fred");
storeDataWriter.store(t1);
Types t2 = new Types();
t2.setIntObjType(new Integer(278652));
t2.setLongObjType(null);
t2.setName("fred");
storeDataWriter.store(t2);
Query q = new Query();
QueryClass qc = new QueryClass(Types.class);
QueryField into = new QueryField(qc, "intObjType");
QueryField longo = new QueryField(qc, "longObjType");
q.addFrom(qc);
q.addToSelect(into);
q.addToSelect(longo);
q.addToSelect(qc);
q.setDistinct(false);
((ObjectStoreInterMineImpl) os).precompute(q, "test");
Results r = os.execute(q);
r.setBatchSize(1);
SqlGenerator.registerOffset(q, 1, ((ObjectStoreInterMineImpl) os).getSchema(), ((ObjectStoreInterMineImpl) os).db, new Integer(100000), new HashMap());
ResultsRow row = (ResultsRow) r.get(1);
InterMineObject o = (InterMineObject) row.get(2);
assertEquals("Expected " + t2.toString() + " but got " + o.toString(), t2.getId(), o.getId());
row = (ResultsRow) r.get(2);
o = (InterMineObject) row.get(2);
assertEquals("Expected " + t1.toString() + " but got " + o.toString(), t1.getId(), o.getId());
q.setConstraint(new SimpleConstraint(into, ConstraintOp.GREATER_THAN, new QueryValue(new Integer(100000))));
q = QueryCloner.cloneQuery(q);
r = os.execute(q);
r.setBatchSize(10);
row = (ResultsRow) r.get(0);
o = (InterMineObject) row.get(2);
assertEquals("Expected " + t2.toString() + " but got " + o.toString(), t2.getId(), o.getId());
assertEquals(1, r.size());
storeDataWriter.delete(t1);
storeDataWriter.delete(t2);
}
public void testPrecomputeWithNegatives() throws Exception {
Types t1 = new Types();
t1.setLongObjType(new Long(-765187651234L));
t1.setIntObjType(new Integer(278652));
t1.setName("Fred");
storeDataWriter.store(t1);
Query q = new Query();
QueryClass qc = new QueryClass(Types.class);
QueryField into = new QueryField(qc, "intObjType");
QueryField longo = new QueryField(qc, "longObjType");
q.addFrom(qc);
q.addToSelect(into);
q.addToSelect(longo);
q.addToSelect(qc);
q.setDistinct(false);
((ObjectStoreInterMineImpl) os).precompute(q, "test");
Results r = os.execute(q);
r.setBatchSize(1);
SqlGenerator.registerOffset(q, 1, ((ObjectStoreInterMineImpl) os).getSchema(), ((ObjectStoreInterMineImpl) os).db, new Integer(278651), new HashMap());
ResultsRow row = (ResultsRow) r.get(1);
InterMineObject o = (InterMineObject) row.get(2);
assertEquals("Expected " + t1.toString() + " but got " + o.toString(), t1.getId(), o.getId());
try {
r.get(2);
fail("Expected size to be 2");
} catch (Exception e) {
}
assertEquals(2, r.size());
storeDataWriter.delete(t1);
}
public void testCancelMethods1() throws Exception {
Object id = "flibble1";
Connection c = ((ObjectStoreInterMineImpl) os).getConnection();
try {
Statement s = c.createStatement();
((ObjectStoreInterMineImpl) os).registerRequestId(id);
((ObjectStoreInterMineImpl) os).registerStatement(s);
((ObjectStoreInterMineImpl) os).deregisterStatement(s);
((ObjectStoreInterMineImpl) os).deregisterRequestId(id);
} finally {
((ObjectStoreInterMineImpl) os).releaseConnection(c);
}
}
public void testCancelMethods2() throws Exception {
Object id = "flibble2";
Connection c = ((ObjectStoreInterMineImpl) os).getConnection();
try {
Statement s = c.createStatement();
((ObjectStoreInterMineImpl) os).registerRequestId(id);
((ObjectStoreInterMineImpl) os).registerStatement(s);
((ObjectStoreInterMineImpl) os).cancelRequest(id);
((ObjectStoreInterMineImpl) os).deregisterStatement(s);
((ObjectStoreInterMineImpl) os).deregisterRequestId(id);
} finally {
((ObjectStoreInterMineImpl) os).releaseConnection(c);
}
}
public void testCancelMethods3() throws Exception {
Object id = "flibble3";
try {
((ObjectStoreInterMineImpl) os).deregisterRequestId(id);
fail("Should have thrown exception");
} catch (ObjectStoreException e) {
assertEquals("This Thread is not registered with ID flibble3", e.getMessage());
}
}
public void testCancelMethods4() throws Exception {
Object id = "flibble4";
Connection c = ((ObjectStoreInterMineImpl) os).getConnection();
try {
Statement s = c.createStatement();
((ObjectStoreInterMineImpl) os).registerRequestId(id);
((ObjectStoreInterMineImpl) os).cancelRequest(id);
((ObjectStoreInterMineImpl) os).registerStatement(s);
fail("Should have thrown exception");
} catch (ObjectStoreException e) {
assertEquals("Request id flibble4 is cancelled", e.getMessage());
} finally {
((ObjectStoreInterMineImpl) os).deregisterRequestId(id);
((ObjectStoreInterMineImpl) os).releaseConnection(c);
}
}
public void testCancelMethods5() throws Exception {
UndeclaredThrowableException failure = null;
// this test sometimes fails even when all is OK, so run it multiple times and exit if it
// passes
for (int i = 0 ;i < 20 ; i++) {
Object id = "flibble5";
Connection c = ((ObjectStoreInterMineImpl) os).getConnection();
Statement s = null;
try {
s = c.createStatement();
((ObjectStoreInterMineImpl) os).registerRequestId(id);
((ObjectStoreInterMineImpl) os).registerStatement(s);
((ObjectStoreInterMineImpl) os).registerStatement(s);
fail("Should have thrown exception");
} catch (ObjectStoreException e) {
assertEquals("Request id flibble5 is currently being serviced in another thread. Don't share request IDs over multiple threads!", e.getMessage());
// test passed so stop immediately
return;
} catch (UndeclaredThrowableException t) {
// test failed but might pass next time - try again
failure = t;
} finally {
if (s != null) {
((ObjectStoreInterMineImpl) os).deregisterStatement(s);
}
((ObjectStoreInterMineImpl) os).deregisterRequestId(id);
((ObjectStoreInterMineImpl) os).releaseConnection(c);
}
}
throw failure;
}
/*
public void testCancelMethods6() throws Exception {
Object id = "flibble6";
Connection c = ((ObjectStoreInterMineImpl) os).getConnection();
Statement s = null;
long start = 0;
try {
s = c.createStatement();
s.execute("CREATE TABLE test (col1 int, col2 int)");
s.execute("INSERT INTO test VALUES (1, 1)");
s.execute("INSERT INTO test VALUES (1, 2)");
s.execute("INSERT INTO test VALUES (2, 1)");
s.execute("INSERT INTO test VALUES (2, 2)");
((ObjectStoreInterMineImpl) os).registerRequestId(id);
((ObjectStoreInterMineImpl) os).registerStatement(s);
Thread delayedCancel = new Thread(new DelayedCancel(id));
delayedCancel.start();
start = System.currentTimeMillis();
s.executeQuery("SELECT * FROM test AS a, test AS b, test AS c, test AS d, test AS e, test AS f, test AS g, test AS h, test AS i, test AS j, test AS k, test AS l, test AS m WHERE a.col2 = b.col1 AND b.col2 = c.col1 AND c.col2 = d.col1 AND d.col2 = e.col1 AND e.col2 = f.col1 AND f.col2 = g.col1 AND g.col2 = h.col1 AND h.col2 = i.col1 AND i.col2 = j.col1 AND j.col2 = k.col1 AND k.col2 = l.col1 AND l.col2 = m.col1");
System.out.println("testCancelMethods6: time for query = " + (System.currentTimeMillis() - start) + " ms");
fail("Request should have been cancelled");
} catch (SQLException e) {
if (start != 0) {
System.out.println("testCancelMethods6: time for query = " + (System.currentTimeMillis() - start) + " ms");
}
String errorString = e.getMessage().replaceFirst("statement", "query");
assertEquals("ERROR: canceling query due to user request", errorString);
} finally {
if (s != null) {
try {
((ObjectStoreInterMineImpl) os).deregisterStatement(s);
} catch (ObjectStoreException e) {
e.printStackTrace(System.out);
}
}
try {
((ObjectStoreInterMineImpl) os).deregisterRequestId(id);
} catch (ObjectStoreException e) {
e.printStackTrace(System.out);
}
try {
c.createStatement().execute("DROP TABLE test");
} catch (SQLException e) {
}
((ObjectStoreInterMineImpl) os).releaseConnection(c);
}
}
*/
/*This test does not work. This is due to a failing of JDBC. The Statement.cancel() method is
* not fully Thread-safe, in that if one performs a cancel() request just before a Statement is
* used, that operation will not be cancelled. There is a race condition between the
* ObjectStore.execute() method registering the Statement and the Statement becoming
* cancellable.
public void testCancelMethods7() throws Exception {
Object id = "flibble7";
Connection c = ((ObjectStoreInterMineImpl) os).getConnection();
Statement s = null;
long start = 0;
try {
s = c.createStatement();
s.execute("CREATE TABLE test (col1 int, col2 int)");
s.execute("INSERT INTO test VALUES (1, 1)");
s.execute("INSERT INTO test VALUES (1, 2)");
s.execute("INSERT INTO test VALUES (2, 1)");
s.execute("INSERT INTO test VALUES (2, 2)");
((ObjectStoreInterMineImpl) os).registerRequestId(id);
((ObjectStoreInterMineImpl) os).registerStatement(s);
start = System.currentTimeMillis();
s.cancel();
s.executeQuery("SELECT * FROM test AS a, test AS b, test AS c, test AS d, test AS e, test AS f, test AS g, test AS h, test AS i, test AS j, test AS k, test AS l, test AS m WHERE a.col2 = b.col1 AND b.col2 = c.col1 AND c.col2 = d.col1 AND d.col2 = e.col1 AND e.col2 = f.col1 AND f.col2 = g.col1 AND g.col2 = h.col1 AND h.col2 = i.col1 AND i.col2 = j.col1 AND j.col2 = k.col1 AND k.col2 = l.col1 AND l.col2 = m.col1");
System.out.println("testCancelMethods6: time for query = " + (System.currentTimeMillis() - start) + " ms");
fail("Request should have been cancelled");
} catch (SQLException e) {
if (start != 0) {
System.out.println("testCancelMethods6: time for query = " + (System.currentTimeMillis() - start) + " ms");
}
assertEquals("ERROR: canceling query due to user request", e.getMessage());
} finally {
if (s != null) {
try {
((ObjectStoreInterMineImpl) os).deregisterStatement(s);
} catch (ObjectStoreException e) {
e.printStackTrace(System.out);
}
}
try {
((ObjectStoreInterMineImpl) os).deregisterRequestId(id);
} catch (ObjectStoreException e) {
e.printStackTrace(System.out);
}
try {
c.createStatement().execute("DROP TABLE test");
} catch (SQLException e) {
}
((ObjectStoreInterMineImpl) os).releaseConnection(c);
}
}
public void testCancel() throws Exception {
Object id = "flibble8";
Query q = new IqlQuery("SELECT a, b, c, d, e FROM Employee AS a, Employee AS b, Employee AS c, Employee AS d, Employee AS e", "org.intermine.model.testmodel").toQuery();
((ObjectStoreInterMineImpl) os).registerRequestId(id);
try {
Thread delayedCancel = new Thread(new DelayedCancel(id));
delayedCancel.start();
Results r = os.execute(q);
r.setBatchSize(10000);
r.setNoOptimise();
r.setNoExplain();
r.get(0);
fail("Operation should have been cancelled");
} catch (RuntimeException e) {
assertEquals("ObjectStore error has occured (in get)", e.getMessage());
Throwable t = e.getCause();
if (!"Request id flibble8 is cancelled".equals(t.getMessage())) {
t = t.getCause();
String errorString = t.getMessage().replaceFirst("statement", "query");
assertEquals("ERROR: canceling query due to user request",errorString);
}
} finally {
((ObjectStoreInterMineImpl) os).deregisterRequestId(id);
}
}
*/
public void testCreateTempBagTables() throws Exception {
Query q = ObjectStoreQueriesTestCase.bagConstraint();
Map bagTableNames = ((ObjectStoreInterMineImpl) os).bagConstraintTables;
bagTableNames.clear();
Connection con = null;
try {
con = ((ObjectStoreInterMineImpl) os).getConnection();
con.setAutoCommit(false);
int minBagSize = ((ObjectStoreInterMineImpl) os).minBagTableSize;
((ObjectStoreInterMineImpl) os).minBagTableSize = 1;
((ObjectStoreInterMineImpl) os).createTempBagTables(con, q);
((ObjectStoreInterMineImpl) os).minBagTableSize = minBagSize;
assertEquals("Entries: " + bagTableNames, 1, bagTableNames.size());
String tableName = (String) bagTableNames.values().iterator().next();
Set expected = new HashSet();
Iterator bagIter = ((BagConstraint) q.getConstraint()).getBag().iterator();
while (bagIter.hasNext()) {
Object thisObject = bagIter.next();
if (thisObject instanceof String) {
expected.add(thisObject);
}
}
Statement s = con.createStatement();
ResultSet r = s.executeQuery("SELECT value FROM " + tableName);
r.next();
Set resultStrings = new HashSet();
resultStrings.add(r.getString(1));
r.next();
resultStrings.add(r.getString(1));
r.next();
resultStrings.add(r.getString(1));
try {
r.next();
} catch (SQLException e) {
// expected
}
assertEquals(expected, resultStrings);
} finally {
if (con != null) {
con.commit();
con.setAutoCommit(true);
((ObjectStoreInterMineImpl) os).releaseConnection(con);
}
}
}
public void testGetUniqueInteger() throws Exception {
ObjectStoreInterMineImpl osii = (ObjectStoreInterMineImpl) os;
Connection con = osii.getConnection();
con.setAutoCommit(false);
int integer1 = osii.getUniqueInteger(con);
int integer2 = osii.getUniqueInteger(con);
assertTrue(integer2 > integer1);
con.setAutoCommit(true);
int integer3 = osii.getUniqueInteger(con);
int integer4 = osii.getUniqueInteger(con);
assertTrue(integer3 > integer2);
assertTrue(integer4 > integer3);
}
private static class DelayedCancel implements Runnable
{
private Object id;
public DelayedCancel(Object id) {
this.id = id;
}
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
try {
((ObjectStoreInterMineImpl) os).cancelRequest(id);
} catch (ObjectStoreException e) {
e.printStackTrace(System.out);
}
}
}
public void testIsPrecomputed() throws Exception {
Query q = new Query();
QueryClass qc = new QueryClass(Employee.class);
QueryField qf = new QueryField(qc,"age");
SimpleConstraint sc = new SimpleConstraint(qf,ConstraintOp.GREATER_THAN,new QueryValue(new Integer(20)));
q.addToSelect(qc);
q.addFrom(qc);
q.setConstraint(sc);
assertFalse(((ObjectStoreInterMineImpl)os).isPrecomputed(q,"template"));
((ObjectStoreInterMineImpl)os).precompute(q, "template");
assertTrue(((ObjectStoreInterMineImpl)os).isPrecomputed(q,"template"));
ObjectStoreBag osb = storeDataWriter.createObjectStoreBag();
storeDataWriter.addToBag(osb, new Integer(5));
assertTrue(((ObjectStoreInterMineImpl)os).isPrecomputed(q,"template"));
storeDataWriter.store((Employee) data.get("EmployeeA1"));
assertFalse(((ObjectStoreInterMineImpl)os).isPrecomputed(q,"template"));
}
public void testObjectStoreBag() throws Exception {
System.out.println("Starting testObjectStoreBag");
ObjectStoreBag osb = storeDataWriter.createObjectStoreBag();
ArrayList coll = new ArrayList();
coll.add(new Integer(3));
coll.add(((Employee) data.get("EmployeeA1")).getId());
coll.add(((Employee) data.get("EmployeeA2")).getId());
coll.add(new Integer(20));
coll.add(new Integer(23));
coll.add(new Integer(30));
storeDataWriter.beginTransaction();
storeDataWriter.addAllToBag(osb, coll);
Query q = new Query();
q.addToSelect(osb);
SingletonResults r = os.executeSingleton(q);
assertEquals(Collections.EMPTY_LIST, r);
q = new Query();
q.addToSelect(osb);
r = os.executeSingleton(q);
storeDataWriter.commitTransaction();
try {
r.get(0);
fail("Expected: ConcurrentModificationException");
} catch (ConcurrentModificationException e) {
}
q = new Query();
q.addToSelect(osb);
r = os.executeSingleton(q);
assertEquals(coll, r);
q = new Query();
QueryClass qc = new QueryClass(Employee.class);
q.addFrom(qc);
q.addToSelect(qc);
q.setConstraint(new BagConstraint(qc, ConstraintOp.IN, osb));
r = os.executeSingleton(q);
assertEquals(Arrays.asList(new Object[] {data.get("EmployeeA1"), data.get("EmployeeA2")}), r);
ObjectStoreBag osb2 = storeDataWriter.createObjectStoreBag();
storeDataWriter.addToBag(osb2, ((Employee) data.get("EmployeeA1")).getId());
storeDataWriter.addToBagFromQuery(osb2, q);
q = new Query();
q.addToSelect(osb2);
r = os.executeSingleton(q);
assertEquals(Arrays.asList(new Object[] {((Employee) data.get("EmployeeA1")).getId(), ((Employee) data.get("EmployeeA2")).getId()}), r);
}
public void testClosedConnectionBug() throws Exception {
Query pq = new Query();
QueryClass qc = new QueryClass(Employee.class);
pq.addFrom(qc);
pq.addToSelect(qc);
((ObjectStoreInterMineImpl) os).precompute(pq, "Whatever");
Query q = new Query();
QueryClass qc1 = new QueryClass(Manager.class);
QueryClass qc2 = new QueryClass(Manager.class);
QueryClass qc3 = new QueryClass(Manager.class);
QueryClass qc4 = new QueryClass(Manager.class);
QueryClass qc5 = new QueryClass(Manager.class);
QueryClass qc6 = new QueryClass(Manager.class);
QueryClass qc7 = new QueryClass(Manager.class);
QueryClass qc8 = new QueryClass(Manager.class);
QueryClass qc9 = new QueryClass(Manager.class);
q.addFrom(qc1);
q.addFrom(qc2);
q.addFrom(qc3);
q.addFrom(qc4);
q.addFrom(qc5);
q.addFrom(qc6);
q.addFrom(qc7);
q.addFrom(qc8);
q.addFrom(qc9);
q.addToSelect(qc1);
q.addToSelect(qc2);
q.addToSelect(qc3);
q.addToSelect(qc4);
q.addToSelect(qc5);
q.addToSelect(qc6);
q.addToSelect(qc7);
q.addToSelect(qc8);
q.addToSelect(qc9);
ConstraintSet cs = new ConstraintSet(ConstraintOp.AND);
q.setConstraint(cs);
cs.addConstraint(new SimpleConstraint(new QueryField(qc1, "id"), ConstraintOp.EQUALS, new QueryValue(new Integer(1))));
cs.addConstraint(new SimpleConstraint(new QueryField(qc1, "id"), ConstraintOp.EQUALS, new QueryValue(new Integer(2))));
cs.addConstraint(new ClassConstraint(qc1, ConstraintOp.EQUALS, qc2));
cs.addConstraint(new ClassConstraint(qc1, ConstraintOp.EQUALS, qc3));
cs.addConstraint(new ClassConstraint(qc1, ConstraintOp.EQUALS, qc4));
cs.addConstraint(new ClassConstraint(qc1, ConstraintOp.EQUALS, qc5));
cs.addConstraint(new ClassConstraint(qc1, ConstraintOp.EQUALS, qc6));
cs.addConstraint(new ClassConstraint(qc1, ConstraintOp.EQUALS, qc7));
cs.addConstraint(new ClassConstraint(qc1, ConstraintOp.EQUALS, qc8));
cs.addConstraint(new ClassConstraint(qc1, ConstraintOp.EQUALS, qc9));
assertEquals(Collections.EMPTY_LIST, os.execute(q, 0, 1000, true, true, ObjectStore.SEQUENCE_IGNORE));
}
public void testFailFast() throws Exception {
Query q1 = new Query();
ObjectStoreBag osb1 = new ObjectStoreBag(100);
q1.addToSelect(osb1);
Query q2 = new Query();
ObjectStoreBag osb2 = new ObjectStoreBag(200);
q2.addToSelect(osb2);
Query q3 = new Query();
QueryClass qc1 = new QueryClass(Employee.class);
q3.addFrom(qc1);
q3.addToSelect(qc1);
Results r1 = os.execute(q1);
Results r2 = os.execute(q2);
Results r3 = os.execute(q3);
storeDataWriter.addToBag(osb1, new Integer(1));
try {
r1.iterator().hasNext();
fail("Expected: ConcurrentModificationException");
} catch (ConcurrentModificationException e) {
}
r2.iterator().hasNext();
r3.iterator().hasNext();
r1 = os.execute(q1);
r2 = os.execute(q2);
r3 = os.execute(q3);
storeDataWriter.addToBag(osb2, new Integer(2));
r1.iterator().hasNext();
try {
r2.iterator().hasNext();
fail("Expected: ConcurrentModificationException");
} catch (ConcurrentModificationException e) {
}
r3.iterator().hasNext();
r1 = os.execute(q1);
r2 = os.execute(q2);
r3 = os.execute(q3);
storeDataWriter.store((Employee) data.get("EmployeeA1"));
r1.iterator().hasNext();
r2.iterator().hasNext();
try {
r3.iterator().hasNext();
fail("Expected: ConcurrentModificationException");
} catch (ConcurrentModificationException e) {
}
}
}
| Try to prevent cancel method tests from failing.
| intermine/objectstore/test/src/org/intermine/objectstore/intermine/ObjectStoreInterMineImplTest.java | Try to prevent cancel method tests from failing. |
|
Java | apache-2.0 | 76225a215c21037abe5f2e1b11c46c96d79b13b8 | 0 | yingyun001/ovirt-engine,walteryang47/ovirt-engine,walteryang47/ovirt-engine,eayun/ovirt-engine,eayun/ovirt-engine,halober/ovirt-engine,OpenUniversity/ovirt-engine,eayun/ovirt-engine,OpenUniversity/ovirt-engine,yingyun001/ovirt-engine,walteryang47/ovirt-engine,zerodengxinchao/ovirt-engine,yapengsong/ovirt-engine,yingyun001/ovirt-engine,halober/ovirt-engine,eayun/ovirt-engine,yapengsong/ovirt-engine,yapengsong/ovirt-engine,halober/ovirt-engine,zerodengxinchao/ovirt-engine,OpenUniversity/ovirt-engine,walteryang47/ovirt-engine,OpenUniversity/ovirt-engine,halober/ovirt-engine,yapengsong/ovirt-engine,zerodengxinchao/ovirt-engine,zerodengxinchao/ovirt-engine,eayun/ovirt-engine,walteryang47/ovirt-engine,zerodengxinchao/ovirt-engine,yingyun001/ovirt-engine,yingyun001/ovirt-engine,yapengsong/ovirt-engine,OpenUniversity/ovirt-engine | package org.ovirt.engine.core.aaa;
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.Map.Entry;
import java.util.Set;
import org.ovirt.engine.api.extensions.Base;
import org.ovirt.engine.api.extensions.ExtKey;
import org.ovirt.engine.api.extensions.ExtMap;
import org.ovirt.engine.api.extensions.aaa.Authn;
import org.ovirt.engine.api.extensions.aaa.Authz;
import org.ovirt.engine.api.extensions.aaa.Authz.GroupRecord;
import org.ovirt.engine.api.extensions.aaa.Authz.PrincipalRecord;
import org.ovirt.engine.core.extensions.mgr.ExtensionProxy;
import org.ovirt.engine.core.utils.collections.MultiValueMapUtils;
public class AuthzUtils {
private static interface QueryResultHandler {
public boolean handle(Collection<ExtMap> queryResults);
}
private static final int QUERIES_RESULTS_LIMIT = 1000;
private static final int PAGE_SIZE = 500;
public static String getName(ExtensionProxy proxy) {
return proxy.getContext().<String> get(Base.ContextKeys.INSTANCE_NAME);
}
public static ExtMap fetchPrincipalRecord(final ExtensionProxy extension, ExtMap authRecord) {
ExtMap ret = null;
ExtMap output = extension.invoke(new ExtMap().mput(
Base.InvokeKeys.COMMAND,
Authz.InvokeCommands.FETCH_PRINCIPAL_RECORD
).mput(
Authn.InvokeKeys.AUTH_RECORD,
authRecord
));
if (output.<Integer>get(Authz.InvokeKeys.STATUS) == Authz.Status.SUCCESS) {
ret = output.<ExtMap> get(Authz.InvokeKeys.PRINCIPAL_RECORD);
}
return ret;
}
public static Collection<ExtMap> fetchPrincipalsByIdsRecursively(
final ExtensionProxy extension,
final String namespace,
final Collection<String> ids) {
Map<String, ExtMap> groupsCache = new HashMap<>();
Map<String, Set<String>> idsToFetchPerNamespace = new HashMap<String, Set<String>>();
Collection<ExtMap> principals = findPrincipalsByIds(extension, namespace, ids, true, false);
for (ExtMap principal : principals) {
for (ExtMap memberOf : principal.get(PrincipalRecord.GROUPS, Collections.<ExtMap> emptyList())) {
addIdToFetch(idsToFetchPerNamespace, memberOf);
}
}
while (!idsToFetchPerNamespace.isEmpty()) {
List<ExtMap> groups = new ArrayList<>();
for (Entry<String, Set<String>> entry : idsToFetchPerNamespace.entrySet()) {
groups.addAll(findGroupRecordsByIds(extension,
entry.getKey(),
entry.getValue(),
true,
false));
}
idsToFetchPerNamespace.clear();
for (ExtMap group : groups) {
groupsCache.put(group.<String> get(GroupRecord.ID), group);
for (ExtMap memberOf : group.get(GroupRecord.GROUPS, Collections.<ExtMap> emptyList())) {
if (!groupsCache.containsKey(memberOf.get(GroupRecord.ID))) {
addIdToFetch(idsToFetchPerNamespace, memberOf);
}
}
}
}
// After the groups are fetched, the "group membership" tree for the principals should be modified accordingly.
for (ExtMap principal : principals) {
constructGroupsMembershipTree(principal, PrincipalRecord.GROUPS, groupsCache);
}
return principals;
}
private static void addIdToFetch(Map<String, Set<String>> idsToFetchPerNamespace, ExtMap memberOf) {
MultiValueMapUtils.addToMapOfSets(memberOf.<String>get(GroupRecord.NAMESPACE), memberOf.<String> get(GroupRecord.ID), idsToFetchPerNamespace);
}
private static ExtMap constructGroupsMembershipTree(ExtMap entity, ExtKey key, Map<String, ExtMap> groupsCache) {
List<ExtMap> groups = new ArrayList<>();
for (ExtMap memberOf : entity.get(key, Collections.<ExtMap> emptyList())) {
groups.add(
constructGroupsMembershipTree(
groupsCache.get(memberOf.get(GroupRecord.ID)).clone(),
GroupRecord.GROUPS,
groupsCache
)
);
}
entity.put(key, groups);
return entity;
}
public static Collection<ExtMap> queryPrincipalRecords(
final ExtensionProxy extension,
final String namespace,
final ExtMap filter,
boolean groupsResolving,
boolean groupsResolvingRecursive
) {
ExtMap inputMap = new ExtMap().mput(
Authz.InvokeKeys.QUERY_ENTITY,
Authz.QueryEntity.PRINCIPAL
).mput(
Authz.InvokeKeys.QUERY_FLAGS,
queryFlagValue(groupsResolving, groupsResolvingRecursive)
).mput(
Authz.InvokeKeys.QUERY_FILTER,
filter
).mput(
Authz.InvokeKeys.NAMESPACE,
namespace
);
return populatePrincipalRecords(
extension,
namespace,
inputMap);
}
public static Collection<ExtMap> queryGroupRecords(
final ExtensionProxy extension,
final String namespace,
final ExtMap filter,
boolean groupsResolving,
boolean groupsResolvingRecursive
) {
ExtMap inputMap = new ExtMap().mput(
Authz.InvokeKeys.QUERY_ENTITY,
Authz.QueryEntity.GROUP
).mput(
Authz.InvokeKeys.QUERY_FLAGS,
queryFlagValue(groupsResolving, groupsResolvingRecursive)
).mput(
Authz.InvokeKeys.QUERY_FILTER,
filter
).mput(
Authz.InvokeKeys.NAMESPACE,
namespace
);
return populateGroups(
extension,
namespace,
inputMap);
}
public static Collection<ExtMap> populatePrincipalRecords(
final ExtensionProxy extension,
final String namespace,
final ExtMap input) {
final Collection<ExtMap> principalRecords = new ArrayList<>();
queryImpl(extension, namespace, input, new QueryResultHandler() {
@Override
public boolean handle(Collection<ExtMap> queryResults) {
boolean result = true;
for (ExtMap queryResult : queryResults) {
if (principalRecords.size() < QUERIES_RESULTS_LIMIT) {
principalRecords.add(queryResult);
} else {
result = false;
break;
}
}
return result;
}
});
return principalRecords;
}
public static Collection<ExtMap> populateGroups(final ExtensionProxy extension, final String namespace,
final ExtMap input) {
final Collection<ExtMap> groups = new ArrayList<>();
queryImpl(extension, namespace, input, new QueryResultHandler() {
@Override
public boolean handle(Collection<ExtMap> queryResults) {
boolean result = true;
for (ExtMap queryResult : queryResults) {
if (groups.size() < QUERIES_RESULTS_LIMIT) {
groups.add(queryResult);
} else {
result = false;
}
}
return result;
}
});
return groups;
}
private static void queryImpl(
final ExtensionProxy extension,
final String namespace,
final ExtMap input,
final QueryResultHandler handler
) {
Object opaque = extension.invoke(
new ExtMap().mput(
Base.InvokeKeys.COMMAND,
Authz.InvokeCommands.QUERY_OPEN
).mput(
Authz.InvokeKeys.NAMESPACE,
namespace
).mput(
input
)
).get(Authz.InvokeKeys.QUERY_OPAQUE);
Collection<ExtMap> result = null;
try {
do {
result = extension.invoke(new ExtMap().mput(
Base.InvokeKeys.COMMAND,
Authz.InvokeCommands.QUERY_EXECUTE
).mput(
Authz.InvokeKeys.QUERY_OPAQUE,
opaque
).mput(
Authz.InvokeKeys.PAGE_SIZE,
PAGE_SIZE
)
).get(Authz.InvokeKeys.QUERY_RESULT);
} while (result != null && handler.handle(result));
} finally {
extension.invoke(new ExtMap().mput(
Base.InvokeKeys.COMMAND,
Authz.InvokeCommands.QUERY_CLOSE
).mput(
Authz.InvokeKeys.QUERY_OPAQUE,
opaque
)
);
}
}
public static Collection<ExtMap> findPrincipalsByIds(
final ExtensionProxy extension,
final String namespace,
final Collection<String> ids,
final boolean groupsResolving,
final boolean groupsResolvingRecursive
) {
Collection<ExtMap> results = new ArrayList<>();
for (Collection<String> batch : SearchQueryParsingUtils.getIdsBatches(extension.getContext(), ids)) {
results.addAll(
queryPrincipalRecords(
extension,
namespace,
SearchQueryParsingUtils.generateQueryMap(
batch,
Authz.QueryEntity.PRINCIPAL
),
groupsResolving,
groupsResolvingRecursive
)
);
}
return results;
}
public static Collection<ExtMap> findGroupRecordsByIds(
final ExtensionProxy extension,
final String namespace,
final Collection<String> ids,
final boolean groupsResolving,
final boolean groupsResolvingRecursive
) {
Collection<ExtMap> results = new ArrayList<>();
for (Collection<String> batch : SearchQueryParsingUtils.getIdsBatches(extension.getContext(), ids)) {
results.addAll(
queryGroupRecords(
extension,
namespace,
SearchQueryParsingUtils.generateQueryMap(
batch,
Authz.QueryEntity.GROUP
),
groupsResolving,
groupsResolvingRecursive
)
);
}
return results;
}
private static int queryFlagValue(boolean resolveGroups, boolean resolveGroupsRecursive) {
int result = 0;
if (resolveGroups) {
result |= Authz.QueryFlags.RESOLVE_GROUPS;
}
if (resolveGroupsRecursive) {
result |= Authz.QueryFlags.RESOLVE_GROUPS_RECURSIVE | Authz.QueryFlags.RESOLVE_GROUPS;
}
return result;
}
}
| backend/manager/modules/aaa/src/main/java/org/ovirt/engine/core/aaa/AuthzUtils.java | package org.ovirt.engine.core.aaa;
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.Map.Entry;
import java.util.Set;
import org.ovirt.engine.api.extensions.Base;
import org.ovirt.engine.api.extensions.ExtKey;
import org.ovirt.engine.api.extensions.ExtMap;
import org.ovirt.engine.api.extensions.aaa.Authn;
import org.ovirt.engine.api.extensions.aaa.Authz;
import org.ovirt.engine.api.extensions.aaa.Authz.GroupRecord;
import org.ovirt.engine.api.extensions.aaa.Authz.PrincipalRecord;
import org.ovirt.engine.core.extensions.mgr.ExtensionProxy;
import org.ovirt.engine.core.utils.collections.MultiValueMapUtils;
public class AuthzUtils {
private static interface QueryResultHandler {
public boolean handle(Collection<ExtMap> queryResults);
}
private static final int QUERIES_RESULTS_LIMIT = 1000;
private static final int PAGE_SIZE = 500;
public static String getName(ExtensionProxy proxy) {
return proxy.getContext().<String> get(Base.ContextKeys.INSTANCE_NAME);
}
public static ExtMap fetchPrincipalRecord(final ExtensionProxy extension, ExtMap authRecord) {
ExtMap ret = null;
ExtMap output = extension.invoke(new ExtMap().mput(
Base.InvokeKeys.COMMAND,
Authz.InvokeCommands.FETCH_PRINCIPAL_RECORD
).mput(
Authn.InvokeKeys.AUTH_RECORD,
authRecord
));
if (output.<Integer>get(Authz.InvokeKeys.STATUS) == Authz.Status.SUCCESS) {
ret = output.<ExtMap> get(Authz.InvokeKeys.PRINCIPAL_RECORD);
}
return ret;
}
public static Collection<ExtMap> fetchPrincipalsByIdsRecursively(
final ExtensionProxy extension,
final String namespace,
final Collection<String> ids) {
Map<String, ExtMap> groupsCache = new HashMap<>();
Map<String, Set<String>> idsToFetchPerNamespace = new HashMap<String, Set<String>>();
Collection<ExtMap> principals = findPrincipalsByIds(extension, namespace, ids, true, false);
for (ExtMap principal : principals) {
for (ExtMap memberOf : principal.get(PrincipalRecord.GROUPS, Collections.<ExtMap> emptyList())) {
addIdToFetch(idsToFetchPerNamespace, memberOf);
}
}
while (!idsToFetchPerNamespace.isEmpty()) {
List<ExtMap> groups = new ArrayList<>();
for (Entry<String, Set<String>> entry : idsToFetchPerNamespace.entrySet()) {
groups.addAll(findGroupRecordsByIds(extension,
entry.getKey(),
entry.getValue(),
true,
false));
}
idsToFetchPerNamespace.clear();
for (ExtMap group : groups) {
groupsCache.put(group.<String> get(GroupRecord.ID), group);
for (ExtMap memberOf : group.get(GroupRecord.GROUPS, Collections.<ExtMap> emptyList())) {
if (!groupsCache.containsKey(memberOf.get(GroupRecord.ID))) {
addIdToFetch(idsToFetchPerNamespace, memberOf);
}
}
}
}
// After the groups are fetched, the "group membership" tree for the principals should be modified accordingly.
for (ExtMap principal : principals) {
constructGroupsMembershipTree(principal, PrincipalRecord.GROUPS, groupsCache);
}
return principals;
}
private static void addIdToFetch(Map<String, Set<String>> idsToFetchPerNamespace, ExtMap memberOf) {
MultiValueMapUtils.addToMapOfSets(memberOf.<String>get(GroupRecord.NAMESPACE), memberOf.<String> get(GroupRecord.ID), idsToFetchPerNamespace);
}
private static void constructGroupsMembershipTree(ExtMap entity, ExtKey key, Map<String, ExtMap> groupsCache) {
List<ExtMap> groups = new ArrayList<>();
for (ExtMap memberOf : entity.get(key, Collections.<ExtMap> emptyList())) {
ExtMap cachedGroup = groupsCache.get(memberOf.get(GroupRecord.ID));
constructGroupsMembershipTree(cachedGroup, GroupRecord.GROUPS, groupsCache);
groups.add(cachedGroup);
}
entity.put(key, groups);
}
public static Collection<ExtMap> queryPrincipalRecords(
final ExtensionProxy extension,
final String namespace,
final ExtMap filter,
boolean groupsResolving,
boolean groupsResolvingRecursive
) {
ExtMap inputMap = new ExtMap().mput(
Authz.InvokeKeys.QUERY_ENTITY,
Authz.QueryEntity.PRINCIPAL
).mput(
Authz.InvokeKeys.QUERY_FLAGS,
queryFlagValue(groupsResolving, groupsResolvingRecursive)
).mput(
Authz.InvokeKeys.QUERY_FILTER,
filter
).mput(
Authz.InvokeKeys.NAMESPACE,
namespace
);
return populatePrincipalRecords(
extension,
namespace,
inputMap);
}
public static Collection<ExtMap> queryGroupRecords(
final ExtensionProxy extension,
final String namespace,
final ExtMap filter,
boolean groupsResolving,
boolean groupsResolvingRecursive
) {
ExtMap inputMap = new ExtMap().mput(
Authz.InvokeKeys.QUERY_ENTITY,
Authz.QueryEntity.GROUP
).mput(
Authz.InvokeKeys.QUERY_FLAGS,
queryFlagValue(groupsResolving, groupsResolvingRecursive)
).mput(
Authz.InvokeKeys.QUERY_FILTER,
filter
).mput(
Authz.InvokeKeys.NAMESPACE,
namespace
);
return populateGroups(
extension,
namespace,
inputMap);
}
public static Collection<ExtMap> populatePrincipalRecords(
final ExtensionProxy extension,
final String namespace,
final ExtMap input) {
final Collection<ExtMap> principalRecords = new ArrayList<>();
queryImpl(extension, namespace, input, new QueryResultHandler() {
@Override
public boolean handle(Collection<ExtMap> queryResults) {
boolean result = true;
for (ExtMap queryResult : queryResults) {
if (principalRecords.size() < QUERIES_RESULTS_LIMIT) {
principalRecords.add(queryResult);
} else {
result = false;
break;
}
}
return result;
}
});
return principalRecords;
}
public static Collection<ExtMap> populateGroups(final ExtensionProxy extension, final String namespace,
final ExtMap input) {
final Collection<ExtMap> groups = new ArrayList<>();
queryImpl(extension, namespace, input, new QueryResultHandler() {
@Override
public boolean handle(Collection<ExtMap> queryResults) {
boolean result = true;
for (ExtMap queryResult : queryResults) {
if (groups.size() < QUERIES_RESULTS_LIMIT) {
groups.add(queryResult);
} else {
result = false;
}
}
return result;
}
});
return groups;
}
private static void queryImpl(
final ExtensionProxy extension,
final String namespace,
final ExtMap input,
final QueryResultHandler handler
) {
Object opaque = extension.invoke(
new ExtMap().mput(
Base.InvokeKeys.COMMAND,
Authz.InvokeCommands.QUERY_OPEN
).mput(
Authz.InvokeKeys.NAMESPACE,
namespace
).mput(
input
)
).get(Authz.InvokeKeys.QUERY_OPAQUE);
Collection<ExtMap> result = null;
try {
do {
result = extension.invoke(new ExtMap().mput(
Base.InvokeKeys.COMMAND,
Authz.InvokeCommands.QUERY_EXECUTE
).mput(
Authz.InvokeKeys.QUERY_OPAQUE,
opaque
).mput(
Authz.InvokeKeys.PAGE_SIZE,
PAGE_SIZE
)
).get(Authz.InvokeKeys.QUERY_RESULT);
} while (result != null && handler.handle(result));
} finally {
extension.invoke(new ExtMap().mput(
Base.InvokeKeys.COMMAND,
Authz.InvokeCommands.QUERY_CLOSE
).mput(
Authz.InvokeKeys.QUERY_OPAQUE,
opaque
)
);
}
}
public static Collection<ExtMap> findPrincipalsByIds(
final ExtensionProxy extension,
final String namespace,
final Collection<String> ids,
final boolean groupsResolving,
final boolean groupsResolvingRecursive
) {
Collection<ExtMap> results = new ArrayList<>();
for (Collection<String> batch : SearchQueryParsingUtils.getIdsBatches(extension.getContext(), ids)) {
results.addAll(
queryPrincipalRecords(
extension,
namespace,
SearchQueryParsingUtils.generateQueryMap(
batch,
Authz.QueryEntity.PRINCIPAL
),
groupsResolving,
groupsResolvingRecursive
)
);
}
return results;
}
public static Collection<ExtMap> findGroupRecordsByIds(
final ExtensionProxy extension,
final String namespace,
final Collection<String> ids,
final boolean groupsResolving,
final boolean groupsResolvingRecursive
) {
Collection<ExtMap> results = new ArrayList<>();
for (Collection<String> batch : SearchQueryParsingUtils.getIdsBatches(extension.getContext(), ids)) {
results.addAll(
queryGroupRecords(
extension,
namespace,
SearchQueryParsingUtils.generateQueryMap(
batch,
Authz.QueryEntity.GROUP
),
groupsResolving,
groupsResolvingRecursive
)
);
}
return results;
}
private static int queryFlagValue(boolean resolveGroups, boolean resolveGroupsRecursive) {
int result = 0;
if (resolveGroups) {
result |= Authz.QueryFlags.RESOLVE_GROUPS;
}
if (resolveGroupsRecursive) {
result |= Authz.QueryFlags.RESOLVE_GROUPS_RECURSIVE | Authz.QueryFlags.RESOLVE_GROUPS;
}
return result;
}
}
| aaa: more sync fixes
Topic: AAA
Change-Id: Ib2611bdc3648525268f4deee8b2ceaa01caca3c1
Signed-off-by: Alon Bar-Lev <[email protected]>
| backend/manager/modules/aaa/src/main/java/org/ovirt/engine/core/aaa/AuthzUtils.java | aaa: more sync fixes |
|
Java | apache-2.0 | edeba8f2c0502687054453637fe500dae1596189 | 0 | inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service,inbloom/secure-data-service | package org.slc.sli.ingestion.tool;
import java.io.File;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.slc.sli.ingestion.BatchJob;
import org.slc.sli.ingestion.FaultsReport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
*Unit Test for ZipValidation
*
* @author npandey
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/spring/applicationContext.xml" })
public class ZipValidationTest {
@Autowired
private ZipValidation zipValidation;
@Test
public void testValidate() throws IOException {
Resource zipFileResource = new ClassPathResource("Session1.zip");
File zipFile = zipFileResource.getFile();
BatchJob job = BatchJob.createDefault("Test.zip");
FaultsReport fr = Mockito.mock(FaultsReport.class);
File ctlFile = zipValidation.validate(zipFile, job);
Assert.assertNotNull(ctlFile);
}
@Test
public void testInValidZip() throws IOException {
Resource zipFileResource = new ClassPathResource("SessionInValid.zip");
File zipFile = zipFileResource.getFile();
BatchJob job = BatchJob.createDefault("Test.zip");
FaultsReport fr = Mockito.mock(FaultsReport.class);
File ctlFile = zipValidation.validate(zipFile, job);
Assert.assertNull(ctlFile);
}
}
| sli/ingestion/ingestion-validation/src/test/java/org/slc/sli/ingestion/tool/ZipValidationTest.java | package org.slc.sli.ingestion.tool;
import java.io.File;
import java.io.IOException;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.slc.sli.ingestion.BatchJob;
import org.slc.sli.ingestion.FaultsReport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "/spring/applicationContext.xml" })
public class ZipValidationTest {
@Autowired
private ZipValidation zipValidation;
@Test
public void testValidate() throws IOException {
Resource zipFileResource = new ClassPathResource("Session1.zip");
File zipFile = zipFileResource.getFile();
BatchJob job = BatchJob.createDefault("Test.zip");
FaultsReport fr = Mockito.mock(FaultsReport.class);
File ctlFile = zipValidation.validate(zipFile, job);
Assert.assertNotNull(ctlFile);
}
}
| Updated the Unit Test
| sli/ingestion/ingestion-validation/src/test/java/org/slc/sli/ingestion/tool/ZipValidationTest.java | Updated the Unit Test |
|
Java | apache-2.0 | 0afe7fc0da49b844a2104a9e58d3f1ea386fc29a | 0 | powertac/powertac-server,powertac/powertac-server,powertac/powertac-server,powertac/powertac-server | package org.powertac.server;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.springframework.stereotype.Service;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
@Service
public class TournamentSchedulerService
{
static private Logger log =
LogManager.getLogger(TournamentSchedulerService.class.getName());
private String tournamentSchedulerUrl = "";
// URL offsets
// These cannot be set by initialization, because they are need to get
// initialization data.
private String interfaceUrl = "faces/serverInterface.jsp";
private String propertiesUrl = "faces/properties.jsp";
private int gameId = 0;
public int getGameId ()
{
return gameId;
}
public void setGameId (int gameId)
{
this.gameId = gameId;
}
public String getTournamentSchedulerUrl ()
{
return tournamentSchedulerUrl;
}
public void setTournamentSchedulerUrl (String tournamentSchedulerUrl)
{
this.tournamentSchedulerUrl = tournamentSchedulerUrl;
}
public URL getBootUrl ()
{
URL result = null;
String urlString = tournamentSchedulerUrl
+ interfaceUrl
+ "?action=boot"
+ "&gameId=" + gameId;
try {
result = new URL(urlString);
}
catch (MalformedURLException e) {
log.error("Bad URL: " + urlString);
e.printStackTrace();
}
return result;
}
public URL getConfigUrl ()
{
URL result = null;
String urlString = tournamentSchedulerUrl
+ propertiesUrl
+ "?gameId=" + gameId;
try {
result = new URL(urlString);
}
catch (MalformedURLException e) {
log.error("Bad URL: " + urlString);
e.printStackTrace();
}
return result;
}
public void ready ()
{
if (tournamentSchedulerUrl.isEmpty()) {
return;
}
String finalUrl = tournamentSchedulerUrl + interfaceUrl
+ "?action=status"
+ "&gameId=" + gameId
+ "&status=game_ready";
log.info("Sending game_ready to controller at: " + finalUrl);
try {
URL url = new URL(finalUrl);
URLConnection conn = url.openConnection();
// Get the response
conn.getInputStream();
}
catch (Exception e) {
e.printStackTrace();
System.out.println("Jenkins failure");
}
}
public void inProgress (int gameLength)
{
if (tournamentSchedulerUrl.isEmpty()) {
return;
}
String finalUrl = tournamentSchedulerUrl + interfaceUrl
+ "?action=status"
+ "&gameId=" + gameId
+ "&status=game_in_progress"
+ "&gameLength=" + gameLength;
log.info("Sending game_in_progress message to controller at: " + finalUrl);
try {
URL url = new URL(finalUrl);
URLConnection conn = url.openConnection();
// Get the response
conn.getInputStream();
}
catch (Exception e) {
e.printStackTrace();
System.out.println("Jenkins failure");
}
}
public void heartbeat (int timeslotIndex, String standings, long elapsed)
{
if (tournamentSchedulerUrl.isEmpty()) {
return;
}
try {
String finalUrl = tournamentSchedulerUrl + interfaceUrl
+ "?action=heartbeat"
+ "&gameId=" + gameId
+ "&message=" + timeslotIndex
+ "&standings=" + URLEncoder.encode(standings, "UTF-8")
+ "&elapsedTime=" + elapsed;
URL url = new URL(finalUrl);
URLConnection conn = url.openConnection();
// Get the response
conn.getInputStream();
}
catch (Exception e) {
e.printStackTrace();
System.out.println("heartbeat failure");
}
}
public void sendResults (String results)
{
if (tournamentSchedulerUrl.isEmpty()) {
return;
}
try {
String finalUrl = tournamentSchedulerUrl + interfaceUrl;
String postData = "action=gameresults"
+ "&gameId=" + gameId
+ "&message=" + URLEncoder.encode(results, "UTF-8");
URL url = new URL(finalUrl);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(postData);
wr.flush();
// Get the response
// TODO is this necessary? already doing an output write/flush
conn.getInputStream();
}
catch (Exception e) {
e.printStackTrace();
System.out.println("heartbeat failure");
}
}
}
| src/main/java/org/powertac/server/TournamentSchedulerService.java | package org.powertac.server;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.springframework.stereotype.Service;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
@Service
public class TournamentSchedulerService
{
static private Logger log =
LogManager.getLogger(TournamentSchedulerService.class.getName());
private String tournamentSchedulerUrl = "";
// URL offsets
// These cannot be set by initialization, because they are need to get
// initialization data.
private String interfaceUrl = "faces/serverInterface.jsp";
private String propertiesUrl = "faces/properties.jsp";
private int gameId = 0;
public int getGameId ()
{
return gameId;
}
public void setGameId (int gameId)
{
this.gameId = gameId;
}
public String getTournamentSchedulerUrl ()
{
return tournamentSchedulerUrl;
}
public void setTournamentSchedulerUrl (String tournamentSchedulerUrl)
{
this.tournamentSchedulerUrl = tournamentSchedulerUrl;
}
public URL getBootUrl ()
{
URL result = null;
String urlString = tournamentSchedulerUrl
+ interfaceUrl
+ "?action=boot"
+ "&gameId=" + gameId;
try {
result = new URL(urlString);
}
catch (MalformedURLException e) {
log.error("Bad URL: " + urlString);
e.printStackTrace();
}
return result;
}
public URL getConfigUrl ()
{
URL result = null;
String urlString = tournamentSchedulerUrl
+ propertiesUrl
+ "?gameId=" + gameId;
try {
result = new URL(urlString);
}
catch (MalformedURLException e) {
log.error("Bad URL: " + urlString);
e.printStackTrace();
}
return result;
}
public void ready ()
{
if (tournamentSchedulerUrl.isEmpty()) {
return;
}
String finalUrl = tournamentSchedulerUrl + interfaceUrl
+ "?action=status"
+ "&gameId=" + gameId
+ "&status=game_ready";
log.info("Sending game_ready to controller at: " + finalUrl);
try {
URL url = new URL(finalUrl);
URLConnection conn = url.openConnection();
// Get the response
InputStream input = conn.getInputStream();
}
catch (Exception e) {
e.printStackTrace();
System.out.println("Jenkins failure");
}
}
public void inProgress (int gameLength)
{
if (tournamentSchedulerUrl.isEmpty()) {
return;
}
String finalUrl = tournamentSchedulerUrl + interfaceUrl
+ "?action=status"
+ "&gameId=" + gameId
+ "&status=game_in_progress"
+ "&gameLength=" + gameLength;
log.info("Sending game_in_progress message to controller at: " + finalUrl);
try {
URL url = new URL(finalUrl);
URLConnection conn = url.openConnection();
// Get the response
InputStream input = conn.getInputStream();
}
catch (Exception e) {
e.printStackTrace();
System.out.println("Jenkins failure");
}
}
public void heartbeat (int timeslotIndex, String standings, long elapsed)
{
if (tournamentSchedulerUrl.isEmpty()) {
return;
}
try {
String finalUrl = tournamentSchedulerUrl + interfaceUrl
+ "?action=heartbeat"
+ "&gameId=" + gameId
+ "&message=" + timeslotIndex
+ "&standings=" + URLEncoder.encode(standings, "UTF-8")
+ "&elapsedTime=" + elapsed;
URL url = new URL(finalUrl);
URLConnection conn = url.openConnection();
// Get the response
InputStream input = conn.getInputStream();
}
catch (Exception e) {
e.printStackTrace();
System.out.println("heartbeat failure");
}
}
public void sendResults (String results)
{
if (tournamentSchedulerUrl.isEmpty()) {
return;
}
try {
String finalUrl = tournamentSchedulerUrl + interfaceUrl;
String postData = "action=gameresults"
+ "&gameId=" + gameId
+ "&message=" + URLEncoder.encode(results, "UTF-8");
URL url = new URL(finalUrl);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(postData);
wr.flush();
// Get the response
InputStream input = conn.getInputStream();
}
catch (Exception e) {
e.printStackTrace();
System.out.println("heartbeat failure");
}
}
}
| Remove unused variables, keep assignments with side-effects
| src/main/java/org/powertac/server/TournamentSchedulerService.java | Remove unused variables, keep assignments with side-effects |
|
Java | apache-2.0 | a37ac6338b7f7e4f1280a87c76619247cd7db8c0 | 0 | ericzundel/commons,cevaris/commons,cevaris/commons,pombredanne/commons,ericzundel/commons,pombredanne/commons,ericzundel/commons,pombredanne/commons,WCCCEDU/twitter-commons,VaybhavSharma/commons,Yasumoto/commons,cevaris/commons,Yasumoto/commons,Yasumoto/commons,atollena/commons,nkhuyu/commons,pombredanne/commons,abel-von/commons,VaybhavSharma/commons,brutkin/commons,WCCCEDU/twitter-commons,abel-von/commons,cevaris/commons,nkhuyu/commons,nkhuyu/commons,ericzundel/commons,brutkin/commons,abel-von/commons,atollena/commons,pombredanne/commons,jsirois/commons,abel-von/commons,brutkin/commons,atollena/commons,jsirois/commons,WCCCEDU/twitter-commons,ericzundel/commons,WCCCEDU/twitter-commons,VaybhavSharma/commons,nkhuyu/commons,jsirois/commons,abel-von/commons,brutkin/commons,atollena/commons,atollena/commons,VaybhavSharma/commons,cevaris/commons,jsirois/commons,Yasumoto/commons,WCCCEDU/twitter-commons,brutkin/commons,Yasumoto/commons,jsirois/commons,nkhuyu/commons,VaybhavSharma/commons | // =================================================================================================
// Copyright 2011 Twitter, Inc.
// -------------------------------------------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this work except in compliance with the License.
// You may obtain a copy of the License in the LICENSE file, or 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.twitter.common.text.extractor;
import java.util.regex.Pattern;
import com.google.common.base.Preconditions;
import com.twitter.common.text.detector.PunctuationDetector;
/**
* Extracts emoticons (e.g., :), :-( ) from a text.
*/
public class EmoticonExtractor extends RegexExtractor {
private static final String EMOTICON_DELIMITER =
PunctuationDetector.SPACE_REGEX + "|" + PunctuationDetector.PUNCTUATION_REGEX;
public static final Pattern SMILEY_REGEX_PATTERN = Pattern.compile(":[)DdpP]|:[ -]\\)|<3");
public static final Pattern FROWNY_REGEX_PATTERN = Pattern.compile(":[(<]|:[ -]\\(");
public static final Pattern EMOTICON_REGEX_PATTERN =
Pattern.compile("(?<=^|" + EMOTICON_DELIMITER + ")("
+ SMILEY_REGEX_PATTERN.pattern() + "|" + FROWNY_REGEX_PATTERN.pattern()
+ ")+(?=$|" + EMOTICON_DELIMITER + ")");
/** The term of art for referring to {positive, negative} sentiment is polarity. */
public enum Polarity {
HAPPY,
SAD
}
/** Default constructor. **/
public EmoticonExtractor() {
setRegexPattern(EMOTICON_REGEX_PATTERN, 1, 1);
}
@Override
public void reset(CharSequence input) {
// check if input contains ':' or '<'
boolean found = false;
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == ':' || input.charAt(i) == '<') {
found = true;
break;
}
}
// apply Regex only if input contains ':' or '<'
if (found) {
super.reset(input);
}
}
/**
* Returns the polarity (happy, sad...) of a given emoticon.
*
* @param emoticon emoticon text
* @return polarity of the emoticon
*/
public static final Polarity getPolarityOf(CharSequence emoticon) {
Preconditions.checkNotNull(emoticon);
Preconditions.checkArgument(emoticon.length() > 0);
char lastChar = emoticon.charAt(emoticon.length() - 1);
if (lastChar == '(' || lastChar == '<') {
return Polarity.SAD;
}
return Polarity.HAPPY;
}
}
| src/java/com/twitter/common/text/extractor/EmoticonExtractor.java | // =================================================================================================
// Copyright 2011 Twitter, Inc.
// -------------------------------------------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this work except in compliance with the License.
// You may obtain a copy of the License in the LICENSE file, or 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.twitter.common.text.extractor;
import java.util.regex.Pattern;
import com.google.common.base.Preconditions;
import com.twitter.common.text.detector.PunctuationDetector;
/**
* Extracts emoticons (e.g., :), :-( ) from a text.
*/
public class EmoticonExtractor extends RegexExtractor {
private static final String EMOTICON_DELIMITER =
PunctuationDetector.SPACE_REGEX + "|" + PunctuationDetector.PUNCTUATION_REGEX;
public static final Pattern SMILEY_REGEX_PATTERN = Pattern.compile(":[)DdpP]|:[ -]\\)|<3");
public static final Pattern FROWNY_REGEX_PATTERN = Pattern.compile(":[(<]|:[ -]\\(");
public static final Pattern EMOTICON_REGEX_PATTERN =
Pattern.compile("(?<=^|" + EMOTICON_DELIMITER + ")("
+ SMILEY_REGEX_PATTERN.pattern() + "|" + FROWNY_REGEX_PATTERN.pattern()
+ ")+(?=$|" + EMOTICON_DELIMITER + ")");
/** The term of art for referring to {positive, negative} sentiment is polarity. */
public enum Polarity {
HAPPY,
SAD
}
/** Default constructor. **/
public EmoticonExtractor() {
setRegexPattern(EMOTICON_REGEX_PATTERN, 1, 1);
}
/**
* Returns the polarity (happy, sad...) of a given emoticon.
*
* @param emoticon emoticon text
* @return polarity of the emoticon
*/
public static final Polarity getPolarityOf(CharSequence emoticon) {
Preconditions.checkNotNull(emoticon);
Preconditions.checkArgument(emoticon.length() > 0);
char lastChar = emoticon.charAt(emoticon.length() - 1);
if (lastChar == '(' || lastChar == '<') {
return Polarity.SAD;
}
return Polarity.HAPPY;
}
}
| [PATCH 2534/7508] Modify EmoticonExctractor to only apply regex if needed
RB_ID=216052
(sapling split of 08c4b29889d1134045b50a6c4bc5bcd6e4692738)
| src/java/com/twitter/common/text/extractor/EmoticonExtractor.java | [PATCH 2534/7508] Modify EmoticonExctractor to only apply regex if needed |
|
Java | apache-2.0 | ff03b49cd4f5fbe314ec3c96d320a6121d51f827 | 0 | cgruber/dagger,ronshapiro/dagger,hansonchar/dagger,hansonchar/dagger,ronshapiro/dagger,google/dagger,hansonchar/dagger,dushmis/dagger,google/dagger,ronshapiro/dagger,cgruber/dagger,dushmis/dagger,cgruber/dagger,google/dagger,ze-pequeno/dagger,google/dagger,ze-pequeno/dagger,ze-pequeno/dagger,ze-pequeno/dagger | /*
* Copyright (C) 2014 The Dagger 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 dagger.internal;
import static dagger.internal.Preconditions.checkNotNull;
import dagger.MembersInjector;
import javax.inject.Inject;
/**
* Basic {@link MembersInjector} implementations used by the framework.
*
* @author Gregory Kick
* @since 2.0
*/
public final class MembersInjectors {
/**
* Injects members into {@code instance} using {@code membersInjector}. This method is a
* convenience for cases in which you would want to chain members injection, but can't because
* {@link MembersInjector#injectMembers} returns {@code void}.
*/
public static <T> T injectMembers(MembersInjector<T> membersInjector, T instance) {
membersInjector.injectMembers(instance);
return instance;
}
/**
* Returns a {@link MembersInjector} implementation that injects no members
*
* <p>Note that there is no verification that the type being injected does not have {@link Inject}
* members, so care should be taken to ensure appropriate use.
*/
@SuppressWarnings("unchecked")
public static <T> MembersInjector<T> noOp() {
return (MembersInjector<T>) NoOpMembersInjector.INSTANCE;
}
private static enum NoOpMembersInjector implements MembersInjector<Object> {
INSTANCE;
@Override public void injectMembers(Object instance) {
checkNotNull(instance);
}
}
private MembersInjectors() {}
}
| java/dagger/internal/MembersInjectors.java | /*
* Copyright (C) 2014 The Dagger 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 dagger.internal;
import static dagger.internal.Preconditions.checkNotNull;
import dagger.MembersInjector;
import javax.inject.Inject;
/**
* Basic {@link MembersInjector} implementations used by the framework.
*
* @author Gregory Kick
* @since 2.0
*/
public final class MembersInjectors {
/**
* Injects members into {@code instance} using {@code membersInjector}. This method is a
* convenience for cases in which you would want to chain members injection, but can't because
* {@link MembersInjector#injectMembers} returns {@code void}.
*/
public static <T> T injectMembers(MembersInjector<T> membersInjector, T instance) {
membersInjector.injectMembers(instance);
return instance;
}
/**
* Returns a {@link MembersInjector} implementation that injects no members
*
* <p>Note that there is no verification that the type being injected does not have {@link Inject}
* members, so care should be taken to ensure appropriate use.
*/
@SuppressWarnings("unchecked")
public static <T> MembersInjector<T> noOp() {
return (MembersInjector<T>) NoOpMembersInjector.INSTANCE;
}
private static enum NoOpMembersInjector implements MembersInjector<Object> {
INSTANCE;
@Override public void injectMembers(Object instance) {
checkNotNull(instance);
}
}
/**
* Returns a {@link MembersInjector} that delegates to the {@link MembersInjector} of its
* supertype. This is useful for cases where a type is known not to have its own {@link Inject}
* members, but must still inject members on its supertype(s).
*
* <p>Note that there is no verification that the type being injected does not have {@link Inject}
* members, so care should be taken to ensure appropriate use.
*/
@SuppressWarnings("unchecked")
public static <T> MembersInjector<T> delegatingTo(MembersInjector<? super T> delegate) {
return (MembersInjector<T>) checkNotNull(delegate);
}
private MembersInjectors() {}
}
| Remove MembersInjectors.delegatingTo(), which is unused
-------------
Created by MOE: https://github.com/google/moe
MOE_MIGRATED_REVID=157463581
| java/dagger/internal/MembersInjectors.java | Remove MembersInjectors.delegatingTo(), which is unused |
|
Java | apache-2.0 | 038bf7e72a27592cba4d138ba605bb9c8907ad67 | 0 | apache/solr,apache/solr,apache/solr,apache/solr,apache/solr | package org.apache.lucene.queryParser.standard;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.io.Reader;
import java.text.Collator;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.analysis.MockTokenFilter;
import org.apache.lucene.analysis.MockTokenizer;
import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;
import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
import org.apache.lucene.document.DateField;
import org.apache.lucene.document.DateTools;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.messages.MessageImpl;
import org.apache.lucene.queryParser.core.QueryNodeException;
import org.apache.lucene.queryParser.core.messages.QueryParserMessages;
import org.apache.lucene.queryParser.core.nodes.FuzzyQueryNode;
import org.apache.lucene.queryParser.core.nodes.QueryNode;
import org.apache.lucene.queryParser.core.processors.QueryNodeProcessorImpl;
import org.apache.lucene.queryParser.core.processors.QueryNodeProcessorPipeline;
import org.apache.lucene.queryParser.standard.config.DefaultOperatorAttribute.Operator;
import org.apache.lucene.queryParser.standard.nodes.WildcardQueryNode;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.FuzzyQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.MultiPhraseQuery;
import org.apache.lucene.search.MultiTermQuery;
import org.apache.lucene.search.PhraseQuery;
import org.apache.lucene.search.PrefixQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.RegexpQuery;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TermRangeQuery;
import org.apache.lucene.search.WildcardQuery;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.automaton.BasicAutomata;
import org.apache.lucene.util.automaton.CharacterRunAutomaton;
import org.apache.lucene.util.automaton.RegExp;
import org.junit.runner.RunWith;
/**
* This test case is a copy of the core Lucene query parser test, it was adapted
* to use new QueryParserHelper instead of the old query parser.
*
* Tests QueryParser.
*/
@RunWith(LuceneTestCase.LocalizedTestCaseRunner.class)
public class TestQPHelper extends LuceneTestCase {
public static Analyzer qpAnalyzer = new QPTestAnalyzer();
public static final class QPTestFilter extends TokenFilter {
private final CharTermAttribute termAtt = addAttribute(CharTermAttribute.class);
private final OffsetAttribute offsetAtt = addAttribute(OffsetAttribute.class);
/**
* Filter which discards the token 'stop' and which expands the token
* 'phrase' into 'phrase1 phrase2'
*/
public QPTestFilter(TokenStream in) {
super(in);
}
boolean inPhrase = false;
int savedStart = 0, savedEnd = 0;
@Override
public boolean incrementToken() throws IOException {
if (inPhrase) {
inPhrase = false;
clearAttributes();
termAtt.setEmpty().append("phrase2");
offsetAtt.setOffset(savedStart, savedEnd);
return true;
} else
while (input.incrementToken()) {
if (termAtt.toString().equals("phrase")) {
inPhrase = true;
savedStart = offsetAtt.startOffset();
savedEnd = offsetAtt.endOffset();
termAtt.setEmpty().append("phrase1");
offsetAtt.setOffset(savedStart, savedEnd);
return true;
} else if (!termAtt.toString().equals("stop"))
return true;
}
return false;
}
}
public static final class QPTestAnalyzer extends Analyzer {
/** Filters MockTokenizer with StopFilter. */
@Override
public final TokenStream tokenStream(String fieldName, Reader reader) {
return new QPTestFilter(new MockTokenizer(reader, MockTokenizer.SIMPLE, true));
}
}
public static class QPTestParser extends StandardQueryParser {
public QPTestParser(Analyzer a) {
((QueryNodeProcessorPipeline)getQueryNodeProcessor())
.addProcessor(new QPTestParserQueryNodeProcessor());
this.setAnalyzer(a);
}
private static class QPTestParserQueryNodeProcessor extends
QueryNodeProcessorImpl {
@Override
protected QueryNode postProcessNode(QueryNode node)
throws QueryNodeException {
return node;
}
@Override
protected QueryNode preProcessNode(QueryNode node)
throws QueryNodeException {
if (node instanceof WildcardQueryNode || node instanceof FuzzyQueryNode) {
throw new QueryNodeException(new MessageImpl(
QueryParserMessages.EMPTY_MESSAGE));
}
return node;
}
@Override
protected List<QueryNode> setChildrenOrder(List<QueryNode> children)
throws QueryNodeException {
return children;
}
}
}
private int originalMaxClauses;
@Override
public void setUp() throws Exception {
super.setUp();
originalMaxClauses = BooleanQuery.getMaxClauseCount();
}
public StandardQueryParser getParser(Analyzer a) throws Exception {
if (a == null)
a = new MockAnalyzer(MockTokenizer.SIMPLE, true);
StandardQueryParser qp = new StandardQueryParser();
qp.setAnalyzer(a);
qp.setDefaultOperator(Operator.OR);
return qp;
}
public Query getQuery(String query, Analyzer a) throws Exception {
return getParser(a).parse(query, "field");
}
public Query getQueryAllowLeadingWildcard(String query, Analyzer a) throws Exception {
StandardQueryParser parser = getParser(a);
parser.setAllowLeadingWildcard(true);
return parser.parse(query, "field");
}
public void assertQueryEquals(String query, Analyzer a, String result)
throws Exception {
Query q = getQuery(query, a);
String s = q.toString("field");
if (!s.equals(result)) {
fail("Query /" + query + "/ yielded /" + s + "/, expecting /" + result
+ "/");
}
}
public void assertQueryEqualsAllowLeadingWildcard(String query, Analyzer a, String result)
throws Exception {
Query q = getQueryAllowLeadingWildcard(query, a);
String s = q.toString("field");
if (!s.equals(result)) {
fail("Query /" + query + "/ yielded /" + s + "/, expecting /" + result
+ "/");
}
}
public void assertQueryEquals(StandardQueryParser qp, String field,
String query, String result) throws Exception {
Query q = qp.parse(query, field);
String s = q.toString(field);
if (!s.equals(result)) {
fail("Query /" + query + "/ yielded /" + s + "/, expecting /" + result
+ "/");
}
}
public void assertEscapedQueryEquals(String query, Analyzer a, String result)
throws Exception {
String escapedQuery = QueryParserUtil.escape(query);
if (!escapedQuery.equals(result)) {
fail("Query /" + query + "/ yielded /" + escapedQuery + "/, expecting /"
+ result + "/");
}
}
public void assertWildcardQueryEquals(String query, boolean lowercase,
String result, boolean allowLeadingWildcard) throws Exception {
StandardQueryParser qp = getParser(null);
qp.setLowercaseExpandedTerms(lowercase);
qp.setAllowLeadingWildcard(allowLeadingWildcard);
Query q = qp.parse(query, "field");
String s = q.toString("field");
if (!s.equals(result)) {
fail("WildcardQuery /" + query + "/ yielded /" + s + "/, expecting /"
+ result + "/");
}
}
public void assertWildcardQueryEquals(String query, boolean lowercase,
String result) throws Exception {
assertWildcardQueryEquals(query, lowercase, result, false);
}
public void assertWildcardQueryEquals(String query, String result)
throws Exception {
StandardQueryParser qp = getParser(null);
Query q = qp.parse(query, "field");
String s = q.toString("field");
if (!s.equals(result)) {
fail("WildcardQuery /" + query + "/ yielded /" + s + "/, expecting /"
+ result + "/");
}
}
public Query getQueryDOA(String query, Analyzer a) throws Exception {
if (a == null)
a = new MockAnalyzer(MockTokenizer.SIMPLE, true);
StandardQueryParser qp = new StandardQueryParser();
qp.setAnalyzer(a);
qp.setDefaultOperator(Operator.AND);
return qp.parse(query, "field");
}
public void assertQueryEqualsDOA(String query, Analyzer a, String result)
throws Exception {
Query q = getQueryDOA(query, a);
String s = q.toString("field");
if (!s.equals(result)) {
fail("Query /" + query + "/ yielded /" + s + "/, expecting /" + result
+ "/");
}
}
public void testConstantScoreAutoRewrite() throws Exception {
StandardQueryParser qp = new StandardQueryParser(new MockAnalyzer(MockTokenizer.WHITESPACE, false));
Query q = qp.parse("foo*bar", "field");
assertTrue(q instanceof WildcardQuery);
assertEquals(MultiTermQuery.CONSTANT_SCORE_AUTO_REWRITE_DEFAULT, ((MultiTermQuery) q).getRewriteMethod());
q = qp.parse("foo*", "field");
assertTrue(q instanceof PrefixQuery);
assertEquals(MultiTermQuery.CONSTANT_SCORE_AUTO_REWRITE_DEFAULT, ((MultiTermQuery) q).getRewriteMethod());
q = qp.parse("[a TO z]", "field");
assertTrue(q instanceof TermRangeQuery);
assertEquals(MultiTermQuery.CONSTANT_SCORE_AUTO_REWRITE_DEFAULT, ((MultiTermQuery) q).getRewriteMethod());
}
public void testCJK() throws Exception {
// Test Ideographic Space - As wide as a CJK character cell (fullwidth)
// used google to translate the word "term" to japanese -> ??
assertQueryEquals("term\u3000term\u3000term", null,
"term\u0020term\u0020term");
assertQueryEqualsAllowLeadingWildcard("??\u3000??\u3000??", null, "??\u0020??\u0020??");
}
//individual CJK chars as terms, like StandardAnalyzer
private class SimpleCJKTokenizer extends Tokenizer {
private CharTermAttribute termAtt = addAttribute(CharTermAttribute.class);
public SimpleCJKTokenizer(Reader input) {
super(input);
}
@Override
public boolean incrementToken() throws IOException {
int ch = input.read();
if (ch < 0)
return false;
clearAttributes();
termAtt.setEmpty().append((char) ch);
return true;
}
}
private class SimpleCJKAnalyzer extends Analyzer {
@Override
public TokenStream tokenStream(String fieldName, Reader reader) {
return new SimpleCJKTokenizer(reader);
}
}
public void testCJKTerm() throws Exception {
// individual CJK chars as terms
SimpleCJKAnalyzer analyzer = new SimpleCJKAnalyzer();
BooleanQuery expected = new BooleanQuery();
expected.add(new TermQuery(new Term("field", "中")), BooleanClause.Occur.SHOULD);
expected.add(new TermQuery(new Term("field", "国")), BooleanClause.Occur.SHOULD);
assertEquals(expected, getQuery("中国", analyzer));
}
public void testCJKBoostedTerm() throws Exception {
// individual CJK chars as terms
SimpleCJKAnalyzer analyzer = new SimpleCJKAnalyzer();
BooleanQuery expected = new BooleanQuery();
expected.setBoost(0.5f);
expected.add(new TermQuery(new Term("field", "中")), BooleanClause.Occur.SHOULD);
expected.add(new TermQuery(new Term("field", "国")), BooleanClause.Occur.SHOULD);
assertEquals(expected, getQuery("中国^0.5", analyzer));
}
public void testCJKPhrase() throws Exception {
// individual CJK chars as terms
SimpleCJKAnalyzer analyzer = new SimpleCJKAnalyzer();
PhraseQuery expected = new PhraseQuery();
expected.add(new Term("field", "中"));
expected.add(new Term("field", "国"));
assertEquals(expected, getQuery("\"中国\"", analyzer));
}
public void testCJKBoostedPhrase() throws Exception {
// individual CJK chars as terms
SimpleCJKAnalyzer analyzer = new SimpleCJKAnalyzer();
PhraseQuery expected = new PhraseQuery();
expected.setBoost(0.5f);
expected.add(new Term("field", "中"));
expected.add(new Term("field", "国"));
assertEquals(expected, getQuery("\"中国\"^0.5", analyzer));
}
public void testCJKSloppyPhrase() throws Exception {
// individual CJK chars as terms
SimpleCJKAnalyzer analyzer = new SimpleCJKAnalyzer();
PhraseQuery expected = new PhraseQuery();
expected.setSlop(3);
expected.add(new Term("field", "中"));
expected.add(new Term("field", "国"));
assertEquals(expected, getQuery("\"中国\"~3", analyzer));
}
public void testSimple() throws Exception {
assertQueryEquals("\"term germ\"~2", null, "\"term germ\"~2");
assertQueryEquals("term term term", null, "term term term");
assertQueryEquals("t�rm term term", new MockAnalyzer(MockTokenizer.WHITESPACE, false),
"t�rm term term");
assertQueryEquals("�mlaut", new MockAnalyzer(MockTokenizer.WHITESPACE, false), "�mlaut");
// FIXME: change MockAnalyzer to not extend CharTokenizer for this test
//assertQueryEquals("\"\"", new KeywordAnalyzer(), "");
//assertQueryEquals("foo:\"\"", new KeywordAnalyzer(), "foo:");
assertQueryEquals("a AND b", null, "+a +b");
assertQueryEquals("(a AND b)", null, "+a +b");
assertQueryEquals("c OR (a AND b)", null, "c (+a +b)");
assertQueryEquals("a AND NOT b", null, "+a -b");
assertQueryEquals("a AND -b", null, "+a -b");
assertQueryEquals("a AND !b", null, "+a -b");
assertQueryEquals("a && b", null, "+a +b");
assertQueryEquals("a && ! b", null, "+a -b");
assertQueryEquals("a OR b", null, "a b");
assertQueryEquals("a || b", null, "a b");
assertQueryEquals("a OR !b", null, "a -b");
assertQueryEquals("a OR ! b", null, "a -b");
assertQueryEquals("a OR -b", null, "a -b");
assertQueryEquals("+term -term term", null, "+term -term term");
assertQueryEquals("foo:term AND field:anotherTerm", null,
"+foo:term +anotherterm");
assertQueryEquals("term AND \"phrase phrase\"", null,
"+term +\"phrase phrase\"");
assertQueryEquals("\"hello there\"", null, "\"hello there\"");
assertTrue(getQuery("a AND b", null) instanceof BooleanQuery);
assertTrue(getQuery("hello", null) instanceof TermQuery);
assertTrue(getQuery("\"hello there\"", null) instanceof PhraseQuery);
assertQueryEquals("germ term^2.0", null, "germ term^2.0");
assertQueryEquals("(term)^2.0", null, "term^2.0");
assertQueryEquals("(germ term)^2.0", null, "(germ term)^2.0");
assertQueryEquals("term^2.0", null, "term^2.0");
assertQueryEquals("term^2", null, "term^2.0");
assertQueryEquals("\"germ term\"^2.0", null, "\"germ term\"^2.0");
assertQueryEquals("\"term germ\"^2", null, "\"term germ\"^2.0");
assertQueryEquals("(foo OR bar) AND (baz OR boo)", null,
"+(foo bar) +(baz boo)");
assertQueryEquals("((a OR b) AND NOT c) OR d", null, "(+(a b) -c) d");
assertQueryEquals("+(apple \"steve jobs\") -(foo bar baz)", null,
"+(apple \"steve jobs\") -(foo bar baz)");
assertQueryEquals("+title:(dog OR cat) -author:\"bob dole\"", null,
"+(title:dog title:cat) -author:\"bob dole\"");
}
public void testPunct() throws Exception {
Analyzer a = new MockAnalyzer(MockTokenizer.WHITESPACE, false);
assertQueryEquals("a&b", a, "a&b");
assertQueryEquals("a&&b", a, "a&&b");
assertQueryEquals(".NET", a, ".NET");
}
public void testSlop() throws Exception {
assertQueryEquals("\"term germ\"~2", null, "\"term germ\"~2");
assertQueryEquals("\"term germ\"~2 flork", null, "\"term germ\"~2 flork");
assertQueryEquals("\"term\"~2", null, "term");
assertQueryEquals("\" \"~2 germ", null, "germ");
assertQueryEquals("\"term germ\"~2^2", null, "\"term germ\"~2^2.0");
}
public void testNumber() throws Exception {
// The numbers go away because SimpleAnalzyer ignores them
assertQueryEquals("3", null, "");
assertQueryEquals("term 1.0 1 2", null, "term");
assertQueryEquals("term term1 term2", null, "term term term");
Analyzer a = new MockAnalyzer(MockTokenizer.WHITESPACE, false);
assertQueryEquals("3", a, "3");
assertQueryEquals("term 1.0 1 2", a, "term 1.0 1 2");
assertQueryEquals("term term1 term2", a, "term term1 term2");
}
public void testWildcard() throws Exception {
assertQueryEquals("term*", null, "term*");
assertQueryEquals("term*^2", null, "term*^2.0");
assertQueryEquals("term~", null, "term~0.5");
assertQueryEquals("term~0.7", null, "term~0.7");
assertQueryEquals("term~^2", null, "term~0.5^2.0");
assertQueryEquals("term^2~", null, "term~0.5^2.0");
assertQueryEquals("term*germ", null, "term*germ");
assertQueryEquals("term*germ^3", null, "term*germ^3.0");
assertTrue(getQuery("term*", null) instanceof PrefixQuery);
assertTrue(getQuery("term*^2", null) instanceof PrefixQuery);
assertTrue(getQuery("term~", null) instanceof FuzzyQuery);
assertTrue(getQuery("term~0.7", null) instanceof FuzzyQuery);
FuzzyQuery fq = (FuzzyQuery) getQuery("term~0.7", null);
assertEquals(0.7f, fq.getMinSimilarity(), 0.1f);
assertEquals(FuzzyQuery.defaultPrefixLength, fq.getPrefixLength());
fq = (FuzzyQuery) getQuery("term~", null);
assertEquals(0.5f, fq.getMinSimilarity(), 0.1f);
assertEquals(FuzzyQuery.defaultPrefixLength, fq.getPrefixLength());
assertQueryNodeException("term~1.1"); // value > 1, throws exception
assertTrue(getQuery("term*germ", null) instanceof WildcardQuery);
/*
* Tests to see that wild card terms are (or are not) properly lower-cased
* with propery parser configuration
*/
// First prefix queries:
// by default, convert to lowercase:
assertWildcardQueryEquals("Term*", true, "term*");
// explicitly set lowercase:
assertWildcardQueryEquals("term*", true, "term*");
assertWildcardQueryEquals("Term*", true, "term*");
assertWildcardQueryEquals("TERM*", true, "term*");
// explicitly disable lowercase conversion:
assertWildcardQueryEquals("term*", false, "term*");
assertWildcardQueryEquals("Term*", false, "Term*");
assertWildcardQueryEquals("TERM*", false, "TERM*");
// Then 'full' wildcard queries:
// by default, convert to lowercase:
assertWildcardQueryEquals("Te?m", "te?m");
// explicitly set lowercase:
assertWildcardQueryEquals("te?m", true, "te?m");
assertWildcardQueryEquals("Te?m", true, "te?m");
assertWildcardQueryEquals("TE?M", true, "te?m");
assertWildcardQueryEquals("Te?m*gerM", true, "te?m*germ");
// explicitly disable lowercase conversion:
assertWildcardQueryEquals("te?m", false, "te?m");
assertWildcardQueryEquals("Te?m", false, "Te?m");
assertWildcardQueryEquals("TE?M", false, "TE?M");
assertWildcardQueryEquals("Te?m*gerM", false, "Te?m*gerM");
// Fuzzy queries:
assertWildcardQueryEquals("Term~", "term~0.5");
assertWildcardQueryEquals("Term~", true, "term~0.5");
assertWildcardQueryEquals("Term~", false, "Term~0.5");
// Range queries:
// TODO: implement this on QueryParser
// Q0002E_INVALID_SYNTAX_CANNOT_PARSE: Syntax Error, cannot parse '[A TO
// C]': Lexical error at line 1, column 1. Encountered: "[" (91), after
// : ""
assertWildcardQueryEquals("[A TO C]", "[a TO c]");
assertWildcardQueryEquals("[A TO C]", true, "[a TO c]");
assertWildcardQueryEquals("[A TO C]", false, "[A TO C]");
// Test suffix queries: first disallow
try {
assertWildcardQueryEquals("*Term", true, "*term");
fail();
} catch (QueryNodeException pe) {
// expected exception
}
try {
assertWildcardQueryEquals("?Term", true, "?term");
fail();
} catch (QueryNodeException pe) {
// expected exception
}
// Test suffix queries: then allow
assertWildcardQueryEquals("*Term", true, "*term", true);
assertWildcardQueryEquals("?Term", true, "?term", true);
}
public void testLeadingWildcardType() throws Exception {
StandardQueryParser qp = getParser(null);
qp.setAllowLeadingWildcard(true);
assertEquals(WildcardQuery.class, qp.parse("t*erm*", "field").getClass());
assertEquals(WildcardQuery.class, qp.parse("?term*", "field").getClass());
assertEquals(WildcardQuery.class, qp.parse("*term*", "field").getClass());
}
public void testQPA() throws Exception {
assertQueryEquals("term term^3.0 term", qpAnalyzer, "term term^3.0 term");
assertQueryEquals("term stop^3.0 term", qpAnalyzer, "term term");
assertQueryEquals("term term term", qpAnalyzer, "term term term");
assertQueryEquals("term +stop term", qpAnalyzer, "term term");
assertQueryEquals("term -stop term", qpAnalyzer, "term term");
assertQueryEquals("drop AND (stop) AND roll", qpAnalyzer, "+drop +roll");
assertQueryEquals("term +(stop) term", qpAnalyzer, "term term");
assertQueryEquals("term -(stop) term", qpAnalyzer, "term term");
assertQueryEquals("drop AND stop AND roll", qpAnalyzer, "+drop +roll");
assertQueryEquals("term phrase term", qpAnalyzer,
"term phrase1 phrase2 term");
assertQueryEquals("term AND NOT phrase term", qpAnalyzer,
"+term -(phrase1 phrase2) term");
assertQueryEquals("stop^3", qpAnalyzer, "");
assertQueryEquals("stop", qpAnalyzer, "");
assertQueryEquals("(stop)^3", qpAnalyzer, "");
assertQueryEquals("((stop))^3", qpAnalyzer, "");
assertQueryEquals("(stop^3)", qpAnalyzer, "");
assertQueryEquals("((stop)^3)", qpAnalyzer, "");
assertQueryEquals("(stop)", qpAnalyzer, "");
assertQueryEquals("((stop))", qpAnalyzer, "");
assertTrue(getQuery("term term term", qpAnalyzer) instanceof BooleanQuery);
assertTrue(getQuery("term +stop", qpAnalyzer) instanceof TermQuery);
}
public void testRange() throws Exception {
assertQueryEquals("[ a TO z]", null, "[a TO z]");
assertEquals(MultiTermQuery.CONSTANT_SCORE_AUTO_REWRITE_DEFAULT, ((TermRangeQuery)getQuery("[ a TO z]", null)).getRewriteMethod());
StandardQueryParser qp = new StandardQueryParser();
qp.setMultiTermRewriteMethod(MultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE);
assertEquals(MultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE,((TermRangeQuery)qp.parse("[ a TO z]", "field")).getRewriteMethod());
assertQueryEquals("[ a TO z ]", null, "[a TO z]");
assertQueryEquals("{ a TO z}", null, "{a TO z}");
assertQueryEquals("{ a TO z }", null, "{a TO z}");
assertQueryEquals("{ a TO z }^2.0", null, "{a TO z}^2.0");
assertQueryEquals("[ a TO z] OR bar", null, "[a TO z] bar");
assertQueryEquals("[ a TO z] AND bar", null, "+[a TO z] +bar");
assertQueryEquals("( bar blar { a TO z}) ", null, "bar blar {a TO z}");
assertQueryEquals("gack ( bar blar { a TO z}) ", null,
"gack (bar blar {a TO z})");
}
public void testFarsiRangeCollating() throws Exception {
Directory ramDir = newDirectory();
IndexWriter iw = new IndexWriter(ramDir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(MockTokenizer.WHITESPACE, false)));
Document doc = new Document();
doc.add(newField("content", "\u0633\u0627\u0628", Field.Store.YES,
Field.Index.NOT_ANALYZED));
iw.addDocument(doc);
iw.close();
IndexSearcher is = new IndexSearcher(ramDir, true);
StandardQueryParser qp = new StandardQueryParser();
qp.setAnalyzer(new MockAnalyzer(MockTokenizer.WHITESPACE, false));
// Neither Java 1.4.2 nor 1.5.0 has Farsi Locale collation available in
// RuleBasedCollator. However, the Arabic Locale seems to order the
// Farsi
// characters properly.
Collator c = Collator.getInstance(new Locale("ar"));
qp.setRangeCollator(c);
// Unicode order would include U+0633 in [ U+062F - U+0698 ], but Farsi
// orders the U+0698 character before the U+0633 character, so the
// single
// index Term below should NOT be returned by a ConstantScoreRangeQuery
// with a Farsi Collator (or an Arabic one for the case when Farsi is
// not
// supported).
// Test ConstantScoreRangeQuery
qp.setMultiTermRewriteMethod(MultiTermQuery.CONSTANT_SCORE_FILTER_REWRITE);
ScoreDoc[] result = is.search(qp.parse("[ \u062F TO \u0698 ]", "content"),
null, 1000).scoreDocs;
assertEquals("The index Term should not be included.", 0, result.length);
result = is.search(qp.parse("[ \u0633 TO \u0638 ]", "content"), null, 1000).scoreDocs;
assertEquals("The index Term should be included.", 1, result.length);
// Test RangeQuery
qp.setMultiTermRewriteMethod(MultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE);
result = is.search(qp.parse("[ \u062F TO \u0698 ]", "content"), null, 1000).scoreDocs;
assertEquals("The index Term should not be included.", 0, result.length);
result = is.search(qp.parse("[ \u0633 TO \u0638 ]", "content"), null, 1000).scoreDocs;
assertEquals("The index Term should be included.", 1, result.length);
is.close();
ramDir.close();
}
/** for testing legacy DateField support */
private String getLegacyDate(String s) throws Exception {
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
return DateField.dateToString(df.parse(s));
}
/** for testing DateTools support */
private String getDate(String s, DateTools.Resolution resolution)
throws Exception {
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
return getDate(df.parse(s), resolution);
}
/** for testing DateTools support */
private String getDate(Date d, DateTools.Resolution resolution)
throws Exception {
if (resolution == null) {
return DateField.dateToString(d);
} else {
return DateTools.dateToString(d, resolution);
}
}
private String escapeDateString(String s) {
if (s.contains(" ")) {
return "\"" + s + "\"";
} else {
return s;
}
}
private String getLocalizedDate(int year, int month, int day) {
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
Calendar calendar = new GregorianCalendar();
calendar.clear();
calendar.set(year, month, day);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
return df.format(calendar.getTime());
}
/** for testing legacy DateField support */
public void testLegacyDateRange() throws Exception {
String startDate = getLocalizedDate(2002, 1, 1);
String endDate = getLocalizedDate(2002, 1, 4);
Calendar endDateExpected = new GregorianCalendar();
endDateExpected.clear();
endDateExpected.set(2002, 1, 4, 23, 59, 59);
endDateExpected.set(Calendar.MILLISECOND, 999);
assertQueryEquals("[ " + escapeDateString(startDate) + " TO " + escapeDateString(endDate) + "]", null, "["
+ getLegacyDate(startDate) + " TO "
+ DateField.dateToString(endDateExpected.getTime()) + "]");
assertQueryEquals("{ " + escapeDateString(startDate) + " " + escapeDateString(endDate) + " }", null, "{"
+ getLegacyDate(startDate) + " TO " + getLegacyDate(endDate) + "}");
}
public void testDateRange() throws Exception {
String startDate = getLocalizedDate(2002, 1, 1);
String endDate = getLocalizedDate(2002, 1, 4);
Calendar endDateExpected = new GregorianCalendar();
endDateExpected.clear();
endDateExpected.set(2002, 1, 4, 23, 59, 59);
endDateExpected.set(Calendar.MILLISECOND, 999);
final String defaultField = "default";
final String monthField = "month";
final String hourField = "hour";
StandardQueryParser qp = new StandardQueryParser();
// Don't set any date resolution and verify if DateField is used
assertDateRangeQueryEquals(qp, defaultField, startDate, endDate,
endDateExpected.getTime(), null);
Map<CharSequence, DateTools.Resolution> dateRes = new HashMap<CharSequence, DateTools.Resolution>();
// set a field specific date resolution
dateRes.put(monthField, DateTools.Resolution.MONTH);
qp.setDateResolution(dateRes);
// DateField should still be used for defaultField
assertDateRangeQueryEquals(qp, defaultField, startDate, endDate,
endDateExpected.getTime(), null);
// set default date resolution to MILLISECOND
qp.setDateResolution(DateTools.Resolution.MILLISECOND);
// set second field specific date resolution
dateRes.put(hourField, DateTools.Resolution.HOUR);
qp.setDateResolution(dateRes);
// for this field no field specific date resolution has been set,
// so verify if the default resolution is used
assertDateRangeQueryEquals(qp, defaultField, startDate, endDate,
endDateExpected.getTime(), DateTools.Resolution.MILLISECOND);
// verify if field specific date resolutions are used for these two
// fields
assertDateRangeQueryEquals(qp, monthField, startDate, endDate,
endDateExpected.getTime(), DateTools.Resolution.MONTH);
assertDateRangeQueryEquals(qp, hourField, startDate, endDate,
endDateExpected.getTime(), DateTools.Resolution.HOUR);
}
public void assertDateRangeQueryEquals(StandardQueryParser qp,
String field, String startDate, String endDate, Date endDateInclusive,
DateTools.Resolution resolution) throws Exception {
assertQueryEquals(qp, field, field + ":[" + escapeDateString(startDate) + " TO " + escapeDateString(endDate)
+ "]", "[" + getDate(startDate, resolution) + " TO "
+ getDate(endDateInclusive, resolution) + "]");
assertQueryEquals(qp, field, field + ":{" + escapeDateString(startDate) + " TO " + escapeDateString(endDate)
+ "}", "{" + getDate(startDate, resolution) + " TO "
+ getDate(endDate, resolution) + "}");
}
public void testEscaped() throws Exception {
Analyzer a = new MockAnalyzer(MockTokenizer.WHITESPACE, false);
/*
* assertQueryEquals("\\[brackets", a, "\\[brackets");
* assertQueryEquals("\\[brackets", null, "brackets");
* assertQueryEquals("\\\\", a, "\\\\"); assertQueryEquals("\\+blah", a,
* "\\+blah"); assertQueryEquals("\\(blah", a, "\\(blah");
*
* assertQueryEquals("\\-blah", a, "\\-blah"); assertQueryEquals("\\!blah",
* a, "\\!blah"); assertQueryEquals("\\{blah", a, "\\{blah");
* assertQueryEquals("\\}blah", a, "\\}blah"); assertQueryEquals("\\:blah",
* a, "\\:blah"); assertQueryEquals("\\^blah", a, "\\^blah");
* assertQueryEquals("\\[blah", a, "\\[blah"); assertQueryEquals("\\]blah",
* a, "\\]blah"); assertQueryEquals("\\\"blah", a, "\\\"blah");
* assertQueryEquals("\\(blah", a, "\\(blah"); assertQueryEquals("\\)blah",
* a, "\\)blah"); assertQueryEquals("\\~blah", a, "\\~blah");
* assertQueryEquals("\\*blah", a, "\\*blah"); assertQueryEquals("\\?blah",
* a, "\\?blah"); //assertQueryEquals("foo \\&\\& bar", a,
* "foo \\&\\& bar"); //assertQueryEquals("foo \\|| bar", a,
* "foo \\|| bar"); //assertQueryEquals("foo \\AND bar", a,
* "foo \\AND bar");
*/
assertQueryEquals("\\*", a, "*");
assertQueryEquals("\\a", a, "a");
assertQueryEquals("a\\-b:c", a, "a-b:c");
assertQueryEquals("a\\+b:c", a, "a+b:c");
assertQueryEquals("a\\:b:c", a, "a:b:c");
assertQueryEquals("a\\\\b:c", a, "a\\b:c");
assertQueryEquals("a:b\\-c", a, "a:b-c");
assertQueryEquals("a:b\\+c", a, "a:b+c");
assertQueryEquals("a:b\\:c", a, "a:b:c");
assertQueryEquals("a:b\\\\c", a, "a:b\\c");
assertQueryEquals("a:b\\-c*", a, "a:b-c*");
assertQueryEquals("a:b\\+c*", a, "a:b+c*");
assertQueryEquals("a:b\\:c*", a, "a:b:c*");
assertQueryEquals("a:b\\\\c*", a, "a:b\\c*");
assertQueryEquals("a:b\\-?c", a, "a:b-?c");
assertQueryEquals("a:b\\+?c", a, "a:b+?c");
assertQueryEquals("a:b\\:?c", a, "a:b:?c");
assertQueryEquals("a:b\\\\?c", a, "a:b\\?c");
assertQueryEquals("a:b\\-c~", a, "a:b-c~0.5");
assertQueryEquals("a:b\\+c~", a, "a:b+c~0.5");
assertQueryEquals("a:b\\:c~", a, "a:b:c~0.5");
assertQueryEquals("a:b\\\\c~", a, "a:b\\c~0.5");
// TODO: implement Range queries on QueryParser
assertQueryEquals("[ a\\- TO a\\+ ]", null, "[a- TO a+]");
assertQueryEquals("[ a\\: TO a\\~ ]", null, "[a: TO a~]");
assertQueryEquals("[ a\\\\ TO a\\* ]", null, "[a\\ TO a*]");
assertQueryEquals(
"[\"c\\:\\\\temp\\\\\\~foo0.txt\" TO \"c\\:\\\\temp\\\\\\~foo9.txt\"]",
a, "[c:\\temp\\~foo0.txt TO c:\\temp\\~foo9.txt]");
assertQueryEquals("a\\\\\\+b", a, "a\\+b");
assertQueryEquals("a \\\"b c\\\" d", a, "a \"b c\" d");
assertQueryEquals("\"a \\\"b c\\\" d\"", a, "\"a \"b c\" d\"");
assertQueryEquals("\"a \\+b c d\"", a, "\"a +b c d\"");
assertQueryEquals("c\\:\\\\temp\\\\\\~foo.txt", a, "c:\\temp\\~foo.txt");
assertQueryNodeException("XY\\"); // there must be a character after the
// escape char
// test unicode escaping
assertQueryEquals("a\\u0062c", a, "abc");
assertQueryEquals("XY\\u005a", a, "XYZ");
assertQueryEquals("XY\\u005A", a, "XYZ");
assertQueryEquals("\"a \\\\\\u0028\\u0062\\\" c\"", a, "\"a \\(b\" c\"");
assertQueryNodeException("XY\\u005G"); // test non-hex character in escaped
// unicode sequence
assertQueryNodeException("XY\\u005"); // test incomplete escaped unicode
// sequence
// Tests bug LUCENE-800
assertQueryEquals("(item:\\\\ item:ABCD\\\\)", a, "item:\\ item:ABCD\\");
assertQueryNodeException("(item:\\\\ item:ABCD\\\\))"); // unmatched closing
// paranthesis
assertQueryEquals("\\*", a, "*");
assertQueryEquals("\\\\", a, "\\"); // escaped backslash
assertQueryNodeException("\\"); // a backslash must always be escaped
// LUCENE-1189
assertQueryEquals("(\"a\\\\\") or (\"b\")", a, "a\\ or b");
}
public void testQueryStringEscaping() throws Exception {
Analyzer a = new MockAnalyzer(MockTokenizer.WHITESPACE, false);
assertEscapedQueryEquals("a-b:c", a, "a\\-b\\:c");
assertEscapedQueryEquals("a+b:c", a, "a\\+b\\:c");
assertEscapedQueryEquals("a:b:c", a, "a\\:b\\:c");
assertEscapedQueryEquals("a\\b:c", a, "a\\\\b\\:c");
assertEscapedQueryEquals("a:b-c", a, "a\\:b\\-c");
assertEscapedQueryEquals("a:b+c", a, "a\\:b\\+c");
assertEscapedQueryEquals("a:b:c", a, "a\\:b\\:c");
assertEscapedQueryEquals("a:b\\c", a, "a\\:b\\\\c");
assertEscapedQueryEquals("a:b-c*", a, "a\\:b\\-c\\*");
assertEscapedQueryEquals("a:b+c*", a, "a\\:b\\+c\\*");
assertEscapedQueryEquals("a:b:c*", a, "a\\:b\\:c\\*");
assertEscapedQueryEquals("a:b\\\\c*", a, "a\\:b\\\\\\\\c\\*");
assertEscapedQueryEquals("a:b-?c", a, "a\\:b\\-\\?c");
assertEscapedQueryEquals("a:b+?c", a, "a\\:b\\+\\?c");
assertEscapedQueryEquals("a:b:?c", a, "a\\:b\\:\\?c");
assertEscapedQueryEquals("a:b?c", a, "a\\:b\\?c");
assertEscapedQueryEquals("a:b-c~", a, "a\\:b\\-c\\~");
assertEscapedQueryEquals("a:b+c~", a, "a\\:b\\+c\\~");
assertEscapedQueryEquals("a:b:c~", a, "a\\:b\\:c\\~");
assertEscapedQueryEquals("a:b\\c~", a, "a\\:b\\\\c\\~");
assertEscapedQueryEquals("[ a - TO a+ ]", null, "\\[ a \\- TO a\\+ \\]");
assertEscapedQueryEquals("[ a : TO a~ ]", null, "\\[ a \\: TO a\\~ \\]");
assertEscapedQueryEquals("[ a\\ TO a* ]", null, "\\[ a\\\\ TO a\\* \\]");
// LUCENE-881
assertEscapedQueryEquals("|| abc ||", a, "\\|\\| abc \\|\\|");
assertEscapedQueryEquals("&& abc &&", a, "\\&\\& abc \\&\\&");
}
public void testTabNewlineCarriageReturn() throws Exception {
assertQueryEqualsDOA("+weltbank +worlbank", null, "+weltbank +worlbank");
assertQueryEqualsDOA("+weltbank\n+worlbank", null, "+weltbank +worlbank");
assertQueryEqualsDOA("weltbank \n+worlbank", null, "+weltbank +worlbank");
assertQueryEqualsDOA("weltbank \n +worlbank", null, "+weltbank +worlbank");
assertQueryEqualsDOA("+weltbank\r+worlbank", null, "+weltbank +worlbank");
assertQueryEqualsDOA("weltbank \r+worlbank", null, "+weltbank +worlbank");
assertQueryEqualsDOA("weltbank \r +worlbank", null, "+weltbank +worlbank");
assertQueryEqualsDOA("+weltbank\r\n+worlbank", null, "+weltbank +worlbank");
assertQueryEqualsDOA("weltbank \r\n+worlbank", null, "+weltbank +worlbank");
assertQueryEqualsDOA("weltbank \r\n +worlbank", null, "+weltbank +worlbank");
assertQueryEqualsDOA("weltbank \r \n +worlbank", null,
"+weltbank +worlbank");
assertQueryEqualsDOA("+weltbank\t+worlbank", null, "+weltbank +worlbank");
assertQueryEqualsDOA("weltbank \t+worlbank", null, "+weltbank +worlbank");
assertQueryEqualsDOA("weltbank \t +worlbank", null, "+weltbank +worlbank");
}
public void testSimpleDAO() throws Exception {
assertQueryEqualsDOA("term term term", null, "+term +term +term");
assertQueryEqualsDOA("term +term term", null, "+term +term +term");
assertQueryEqualsDOA("term term +term", null, "+term +term +term");
assertQueryEqualsDOA("term +term +term", null, "+term +term +term");
assertQueryEqualsDOA("-term term term", null, "-term +term +term");
}
public void testBoost() throws Exception {
CharacterRunAutomaton stopSet = new CharacterRunAutomaton(BasicAutomata.makeString("on"));
Analyzer oneStopAnalyzer = new MockAnalyzer(MockTokenizer.SIMPLE, true, stopSet, true);
StandardQueryParser qp = new StandardQueryParser();
qp.setAnalyzer(oneStopAnalyzer);
Query q = qp.parse("on^1.0", "field");
assertNotNull(q);
q = qp.parse("\"hello\"^2.0", "field");
assertNotNull(q);
assertEquals(q.getBoost(), (float) 2.0, (float) 0.5);
q = qp.parse("hello^2.0", "field");
assertNotNull(q);
assertEquals(q.getBoost(), (float) 2.0, (float) 0.5);
q = qp.parse("\"on\"^1.0", "field");
assertNotNull(q);
StandardQueryParser qp2 = new StandardQueryParser();
qp2.setAnalyzer(new MockAnalyzer(MockTokenizer.SIMPLE, true, MockTokenFilter.ENGLISH_STOPSET, true));
q = qp2.parse("the^3", "field");
// "the" is a stop word so the result is an empty query:
assertNotNull(q);
assertEquals("", q.toString());
assertEquals(1.0f, q.getBoost(), 0.01f);
}
public void assertQueryNodeException(String queryString) throws Exception {
try {
getQuery(queryString, null);
} catch (QueryNodeException expected) {
return;
}
fail("ParseException expected, not thrown");
}
public void testException() throws Exception {
assertQueryNodeException("*leadingWildcard"); // disallowed by default
assertQueryNodeException("\"some phrase");
assertQueryNodeException("(foo bar");
assertQueryNodeException("foo bar))");
assertQueryNodeException("field:term:with:colon some more terms");
assertQueryNodeException("(sub query)^5.0^2.0 plus more");
assertQueryNodeException("secret AND illegal) AND access:confidential");
}
public void testCustomQueryParserWildcard() {
try {
new QPTestParser(new MockAnalyzer(MockTokenizer.WHITESPACE, false)).parse("a?t", "contents");
fail("Wildcard queries should not be allowed");
} catch (QueryNodeException expected) {
// expected exception
}
}
public void testCustomQueryParserFuzzy() throws Exception {
try {
new QPTestParser(new MockAnalyzer(MockTokenizer.WHITESPACE, false)).parse("xunit~", "contents");
fail("Fuzzy queries should not be allowed");
} catch (QueryNodeException expected) {
// expected exception
}
}
public void testBooleanQuery() throws Exception {
BooleanQuery.setMaxClauseCount(2);
try {
StandardQueryParser qp = new StandardQueryParser();
qp.setAnalyzer(new MockAnalyzer(MockTokenizer.WHITESPACE, false));
qp.parse("one two three", "field");
fail("ParseException expected due to too many boolean clauses");
} catch (QueryNodeException expected) {
// too many boolean clauses, so ParseException is expected
}
}
/**
* This test differs from TestPrecedenceQueryParser
*/
public void testPrecedence() throws Exception {
StandardQueryParser qp = new StandardQueryParser();
qp.setAnalyzer(new MockAnalyzer(MockTokenizer.WHITESPACE, false));
Query query1 = qp.parse("A AND B OR C AND D", "field");
Query query2 = qp.parse("+A +B +C +D", "field");
assertEquals(query1, query2);
}
public void testLocalDateFormat() throws IOException, QueryNodeException {
Directory ramDir = newDirectory();
IndexWriter iw = new IndexWriter(ramDir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(MockTokenizer.WHITESPACE, false)));
addDateDoc("a", 2005, 12, 2, 10, 15, 33, iw);
addDateDoc("b", 2005, 12, 4, 22, 15, 00, iw);
iw.close();
IndexSearcher is = new IndexSearcher(ramDir, true);
assertHits(1, "[12/1/2005 TO 12/3/2005]", is);
assertHits(2, "[12/1/2005 TO 12/4/2005]", is);
assertHits(1, "[12/3/2005 TO 12/4/2005]", is);
assertHits(1, "{12/1/2005 TO 12/3/2005}", is);
assertHits(1, "{12/1/2005 TO 12/4/2005}", is);
assertHits(0, "{12/3/2005 TO 12/4/2005}", is);
is.close();
ramDir.close();
}
public void testStarParsing() throws Exception {
// final int[] type = new int[1];
// StandardQueryParser qp = new StandardQueryParser("field", new
// WhitespaceAnalyzer()) {
// protected Query getWildcardQuery(String field, String termStr) throws
// ParseException {
// // override error checking of superclass
// type[0]=1;
// return new TermQuery(new Term(field,termStr));
// }
// protected Query getPrefixQuery(String field, String termStr) throws
// ParseException {
// // override error checking of superclass
// type[0]=2;
// return new TermQuery(new Term(field,termStr));
// }
//
// protected Query getFieldQuery(String field, String queryText) throws
// ParseException {
// type[0]=3;
// return super.getFieldQuery(field, queryText);
// }
// };
//
// TermQuery tq;
//
// tq = (TermQuery)qp.parse("foo:zoo*");
// assertEquals("zoo",tq.getTerm().text());
// assertEquals(2,type[0]);
//
// tq = (TermQuery)qp.parse("foo:zoo*^2");
// assertEquals("zoo",tq.getTerm().text());
// assertEquals(2,type[0]);
// assertEquals(tq.getBoost(),2,0);
//
// tq = (TermQuery)qp.parse("foo:*");
// assertEquals("*",tq.getTerm().text());
// assertEquals(1,type[0]); // could be a valid prefix query in the
// future too
//
// tq = (TermQuery)qp.parse("foo:*^2");
// assertEquals("*",tq.getTerm().text());
// assertEquals(1,type[0]);
// assertEquals(tq.getBoost(),2,0);
//
// tq = (TermQuery)qp.parse("*:foo");
// assertEquals("*",tq.getTerm().field());
// assertEquals("foo",tq.getTerm().text());
// assertEquals(3,type[0]);
//
// tq = (TermQuery)qp.parse("*:*");
// assertEquals("*",tq.getTerm().field());
// assertEquals("*",tq.getTerm().text());
// assertEquals(1,type[0]); // could be handled as a prefix query in the
// future
//
// tq = (TermQuery)qp.parse("(*:*)");
// assertEquals("*",tq.getTerm().field());
// assertEquals("*",tq.getTerm().text());
// assertEquals(1,type[0]);
}
public void testRegexps() throws Exception {
StandardQueryParser qp = new StandardQueryParser();
final String df = "field" ;
RegexpQuery q = new RegexpQuery(new Term("field", "[a-z][123]"));
assertEquals(q, qp.parse("/[a-z][123]/", df));
qp.setLowercaseExpandedTerms(true);
assertEquals(q, qp.parse("/[A-Z][123]/", df));
q.setBoost(0.5f);
assertEquals(q, qp.parse("/[A-Z][123]/^0.5", df));
qp.setMultiTermRewriteMethod(MultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE);
q.setRewriteMethod(MultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE);
assertTrue(qp.parse("/[A-Z][123]/^0.5", df) instanceof RegexpQuery);
assertEquals(q, qp.parse("/[A-Z][123]/^0.5", df));
assertEquals(MultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE, ((RegexpQuery)qp.parse("/[A-Z][123]/^0.5", df)).getRewriteMethod());
qp.setMultiTermRewriteMethod(MultiTermQuery.CONSTANT_SCORE_AUTO_REWRITE_DEFAULT);
Query escaped = new RegexpQuery(new Term("field", "[a-z]\\/[123]"));
assertEquals(escaped, qp.parse("/[a-z]\\/[123]/", df));
Query escaped2 = new RegexpQuery(new Term("field", "[a-z]\\*[123]"));
assertEquals(escaped2, qp.parse("/[a-z]\\*[123]/", df));
BooleanQuery complex = new BooleanQuery();
complex.add(new RegexpQuery(new Term("field", "[a-z]\\/[123]")), Occur.MUST);
complex.add(new TermQuery(new Term("path", "/etc/init.d/")), Occur.MUST);
complex.add(new TermQuery(new Term("field", "/etc/init[.]d/lucene/")), Occur.SHOULD);
assertEquals(complex, qp.parse("/[a-z]\\/[123]/ AND path:/etc/init.d/ OR /etc\\/init\\[.\\]d/lucene/ ", df));
}
public void testStopwords() throws Exception {
StandardQueryParser qp = new StandardQueryParser();
CharacterRunAutomaton stopSet = new CharacterRunAutomaton(new RegExp("the|foo").toAutomaton());
qp.setAnalyzer(new MockAnalyzer(MockTokenizer.SIMPLE, true, stopSet, true));
Query result = qp.parse("a:the OR a:foo", "a");
assertNotNull("result is null and it shouldn't be", result);
assertTrue("result is not a BooleanQuery", result instanceof BooleanQuery);
assertTrue(((BooleanQuery) result).clauses().size() + " does not equal: "
+ 0, ((BooleanQuery) result).clauses().size() == 0);
result = qp.parse("a:woo OR a:the", "a");
assertNotNull("result is null and it shouldn't be", result);
assertTrue("result is not a TermQuery", result instanceof TermQuery);
result = qp.parse(
"(fieldX:xxxxx OR fieldy:xxxxxxxx)^2 AND (fieldx:the OR fieldy:foo)",
"a");
assertNotNull("result is null and it shouldn't be", result);
assertTrue("result is not a BooleanQuery", result instanceof BooleanQuery);
if (VERBOSE)
System.out.println("Result: " + result);
assertTrue(((BooleanQuery) result).clauses().size() + " does not equal: "
+ 2, ((BooleanQuery) result).clauses().size() == 2);
}
public void testPositionIncrement() throws Exception {
StandardQueryParser qp = new StandardQueryParser();
qp.setAnalyzer(
new MockAnalyzer(MockTokenizer.SIMPLE, true, MockTokenFilter.ENGLISH_STOPSET, true));
qp.setEnablePositionIncrements(true);
String qtxt = "\"the words in poisitions pos02578 are stopped in this phrasequery\"";
// 0 2 5 7 8
int expectedPositions[] = { 1, 3, 4, 6, 9 };
PhraseQuery pq = (PhraseQuery) qp.parse(qtxt, "a");
// System.out.println("Query text: "+qtxt);
// System.out.println("Result: "+pq);
Term t[] = pq.getTerms();
int pos[] = pq.getPositions();
for (int i = 0; i < t.length; i++) {
// System.out.println(i+". "+t[i]+" pos: "+pos[i]);
assertEquals("term " + i + " = " + t[i] + " has wrong term-position!",
expectedPositions[i], pos[i]);
}
}
public void testMatchAllDocs() throws Exception {
StandardQueryParser qp = new StandardQueryParser();
qp.setAnalyzer(new MockAnalyzer(MockTokenizer.WHITESPACE, false));
assertEquals(new MatchAllDocsQuery(), qp.parse("*:*", "field"));
assertEquals(new MatchAllDocsQuery(), qp.parse("(*:*)", "field"));
BooleanQuery bq = (BooleanQuery) qp.parse("+*:* -*:*", "field");
assertTrue(bq.getClauses()[0].getQuery() instanceof MatchAllDocsQuery);
assertTrue(bq.getClauses()[1].getQuery() instanceof MatchAllDocsQuery);
}
private void assertHits(int expected, String query, IndexSearcher is)
throws IOException, QueryNodeException {
StandardQueryParser qp = new StandardQueryParser();
qp.setAnalyzer(new MockAnalyzer(MockTokenizer.WHITESPACE, false));
qp.setLocale(Locale.ENGLISH);
Query q = qp.parse(query, "date");
ScoreDoc[] hits = is.search(q, null, 1000).scoreDocs;
assertEquals(expected, hits.length);
}
private void addDateDoc(String content, int year, int month, int day,
int hour, int minute, int second, IndexWriter iw) throws IOException {
Document d = new Document();
d.add(newField("f", content, Field.Store.YES, Field.Index.ANALYZED));
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
cal.set(year, month - 1, day, hour, minute, second);
d.add(newField("date", DateField.dateToString(cal.getTime()),
Field.Store.YES, Field.Index.NOT_ANALYZED));
iw.addDocument(d);
}
@Override
public void tearDown() throws Exception {
BooleanQuery.setMaxClauseCount(originalMaxClauses);
super.tearDown();
}
private class CannedTokenStream extends TokenStream {
private int upto = 0;
final PositionIncrementAttribute posIncr = addAttribute(PositionIncrementAttribute.class);
final CharTermAttribute term = addAttribute(CharTermAttribute.class);
@Override
public boolean incrementToken() {
clearAttributes();
if (upto == 4) {
return false;
}
if (upto == 0) {
posIncr.setPositionIncrement(1);
term.setEmpty().append("a");
} else if (upto == 1) {
posIncr.setPositionIncrement(1);
term.setEmpty().append("b");
} else if (upto == 2) {
posIncr.setPositionIncrement(0);
term.setEmpty().append("c");
} else {
posIncr.setPositionIncrement(0);
term.setEmpty().append("d");
}
upto++;
return true;
}
}
private class CannedAnalyzer extends Analyzer {
@Override
public TokenStream tokenStream(String ignored, Reader alsoIgnored) {
return new CannedTokenStream();
}
}
public void testMultiPhraseQuery() throws Exception {
Directory dir = newDirectory();
IndexWriter w = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new CannedAnalyzer()));
Document doc = new Document();
doc.add(newField("field", "", Field.Store.NO, Field.Index.ANALYZED));
w.addDocument(doc);
IndexReader r = w.getReader();
IndexSearcher s = new IndexSearcher(r);
Query q = new StandardQueryParser(new CannedAnalyzer()).parse("\"a\"", "field");
assertTrue(q instanceof MultiPhraseQuery);
assertEquals(1, s.search(q, 10).totalHits);
r.close();
w.close();
dir.close();
}
}
| lucene/contrib/queryparser/src/test/org/apache/lucene/queryParser/standard/TestQPHelper.java | package org.apache.lucene.queryParser.standard;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.io.Reader;
import java.text.Collator;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.analysis.MockTokenFilter;
import org.apache.lucene.analysis.MockTokenizer;
import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;
import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
import org.apache.lucene.document.DateField;
import org.apache.lucene.document.DateTools;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.messages.MessageImpl;
import org.apache.lucene.queryParser.core.QueryNodeException;
import org.apache.lucene.queryParser.core.messages.QueryParserMessages;
import org.apache.lucene.queryParser.core.nodes.FuzzyQueryNode;
import org.apache.lucene.queryParser.core.nodes.QueryNode;
import org.apache.lucene.queryParser.core.processors.QueryNodeProcessorImpl;
import org.apache.lucene.queryParser.core.processors.QueryNodeProcessorPipeline;
import org.apache.lucene.queryParser.standard.config.DefaultOperatorAttribute.Operator;
import org.apache.lucene.queryParser.standard.nodes.WildcardQueryNode;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.FuzzyQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.MultiPhraseQuery;
import org.apache.lucene.search.MultiTermQuery;
import org.apache.lucene.search.PhraseQuery;
import org.apache.lucene.search.PrefixQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.RegexpQuery;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TermRangeQuery;
import org.apache.lucene.search.WildcardQuery;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.automaton.BasicAutomata;
import org.apache.lucene.util.automaton.CharacterRunAutomaton;
import org.apache.lucene.util.automaton.RegExp;
import org.junit.runner.RunWith;
/**
* This test case is a copy of the core Lucene query parser test, it was adapted
* to use new QueryParserHelper instead of the old query parser.
*
* Tests QueryParser.
*/
@RunWith(LuceneTestCase.LocalizedTestCaseRunner.class)
public class TestQPHelper extends LuceneTestCase {
public static Analyzer qpAnalyzer = new QPTestAnalyzer();
public static final class QPTestFilter extends TokenFilter {
private final CharTermAttribute termAtt = addAttribute(CharTermAttribute.class);
private final OffsetAttribute offsetAtt = addAttribute(OffsetAttribute.class);
/**
* Filter which discards the token 'stop' and which expands the token
* 'phrase' into 'phrase1 phrase2'
*/
public QPTestFilter(TokenStream in) {
super(in);
}
boolean inPhrase = false;
int savedStart = 0, savedEnd = 0;
@Override
public boolean incrementToken() throws IOException {
if (inPhrase) {
inPhrase = false;
clearAttributes();
termAtt.setEmpty().append("phrase2");
offsetAtt.setOffset(savedStart, savedEnd);
return true;
} else
while (input.incrementToken()) {
if (termAtt.toString().equals("phrase")) {
inPhrase = true;
savedStart = offsetAtt.startOffset();
savedEnd = offsetAtt.endOffset();
termAtt.setEmpty().append("phrase1");
offsetAtt.setOffset(savedStart, savedEnd);
return true;
} else if (!termAtt.toString().equals("stop"))
return true;
}
return false;
}
}
public static final class QPTestAnalyzer extends Analyzer {
/** Filters MockTokenizer with StopFilter. */
@Override
public final TokenStream tokenStream(String fieldName, Reader reader) {
return new QPTestFilter(new MockTokenizer(reader, MockTokenizer.SIMPLE, true));
}
}
public static class QPTestParser extends StandardQueryParser {
public QPTestParser(Analyzer a) {
((QueryNodeProcessorPipeline)getQueryNodeProcessor())
.addProcessor(new QPTestParserQueryNodeProcessor());
this.setAnalyzer(a);
}
private static class QPTestParserQueryNodeProcessor extends
QueryNodeProcessorImpl {
@Override
protected QueryNode postProcessNode(QueryNode node)
throws QueryNodeException {
return node;
}
@Override
protected QueryNode preProcessNode(QueryNode node)
throws QueryNodeException {
if (node instanceof WildcardQueryNode || node instanceof FuzzyQueryNode) {
throw new QueryNodeException(new MessageImpl(
QueryParserMessages.EMPTY_MESSAGE));
}
return node;
}
@Override
protected List<QueryNode> setChildrenOrder(List<QueryNode> children)
throws QueryNodeException {
return children;
}
}
}
private int originalMaxClauses;
@Override
public void setUp() throws Exception {
super.setUp();
originalMaxClauses = BooleanQuery.getMaxClauseCount();
}
public StandardQueryParser getParser(Analyzer a) throws Exception {
if (a == null)
a = new MockAnalyzer(MockTokenizer.SIMPLE, true);
StandardQueryParser qp = new StandardQueryParser();
qp.setAnalyzer(a);
qp.setDefaultOperator(Operator.OR);
return qp;
}
public Query getQuery(String query, Analyzer a) throws Exception {
return getParser(a).parse(query, "field");
}
public Query getQueryAllowLeadingWildcard(String query, Analyzer a) throws Exception {
StandardQueryParser parser = getParser(a);
parser.setAllowLeadingWildcard(true);
return parser.parse(query, "field");
}
public void assertQueryEquals(String query, Analyzer a, String result)
throws Exception {
Query q = getQuery(query, a);
String s = q.toString("field");
if (!s.equals(result)) {
fail("Query /" + query + "/ yielded /" + s + "/, expecting /" + result
+ "/");
}
}
public void assertQueryEqualsAllowLeadingWildcard(String query, Analyzer a, String result)
throws Exception {
Query q = getQueryAllowLeadingWildcard(query, a);
String s = q.toString("field");
if (!s.equals(result)) {
fail("Query /" + query + "/ yielded /" + s + "/, expecting /" + result
+ "/");
}
}
public void assertQueryEquals(StandardQueryParser qp, String field,
String query, String result) throws Exception {
Query q = qp.parse(query, field);
String s = q.toString(field);
if (!s.equals(result)) {
fail("Query /" + query + "/ yielded /" + s + "/, expecting /" + result
+ "/");
}
}
public void assertEscapedQueryEquals(String query, Analyzer a, String result)
throws Exception {
String escapedQuery = QueryParserUtil.escape(query);
if (!escapedQuery.equals(result)) {
fail("Query /" + query + "/ yielded /" + escapedQuery + "/, expecting /"
+ result + "/");
}
}
public void assertWildcardQueryEquals(String query, boolean lowercase,
String result, boolean allowLeadingWildcard) throws Exception {
StandardQueryParser qp = getParser(null);
qp.setLowercaseExpandedTerms(lowercase);
qp.setAllowLeadingWildcard(allowLeadingWildcard);
Query q = qp.parse(query, "field");
String s = q.toString("field");
if (!s.equals(result)) {
fail("WildcardQuery /" + query + "/ yielded /" + s + "/, expecting /"
+ result + "/");
}
}
public void assertWildcardQueryEquals(String query, boolean lowercase,
String result) throws Exception {
assertWildcardQueryEquals(query, lowercase, result, false);
}
public void assertWildcardQueryEquals(String query, String result)
throws Exception {
StandardQueryParser qp = getParser(null);
Query q = qp.parse(query, "field");
String s = q.toString("field");
if (!s.equals(result)) {
fail("WildcardQuery /" + query + "/ yielded /" + s + "/, expecting /"
+ result + "/");
}
}
public Query getQueryDOA(String query, Analyzer a) throws Exception {
if (a == null)
a = new MockAnalyzer(MockTokenizer.SIMPLE, true);
StandardQueryParser qp = new StandardQueryParser();
qp.setAnalyzer(a);
qp.setDefaultOperator(Operator.AND);
return qp.parse(query, "field");
}
public void assertQueryEqualsDOA(String query, Analyzer a, String result)
throws Exception {
Query q = getQueryDOA(query, a);
String s = q.toString("field");
if (!s.equals(result)) {
fail("Query /" + query + "/ yielded /" + s + "/, expecting /" + result
+ "/");
}
}
public void testConstantScoreAutoRewrite() throws Exception {
StandardQueryParser qp = new StandardQueryParser(new MockAnalyzer(MockTokenizer.WHITESPACE, false));
Query q = qp.parse("foo*bar", "field");
assertTrue(q instanceof WildcardQuery);
assertEquals(MultiTermQuery.CONSTANT_SCORE_AUTO_REWRITE_DEFAULT, ((MultiTermQuery) q).getRewriteMethod());
q = qp.parse("foo*", "field");
assertTrue(q instanceof PrefixQuery);
assertEquals(MultiTermQuery.CONSTANT_SCORE_AUTO_REWRITE_DEFAULT, ((MultiTermQuery) q).getRewriteMethod());
q = qp.parse("[a TO z]", "field");
assertTrue(q instanceof TermRangeQuery);
assertEquals(MultiTermQuery.CONSTANT_SCORE_AUTO_REWRITE_DEFAULT, ((MultiTermQuery) q).getRewriteMethod());
}
public void testCJK() throws Exception {
// Test Ideographic Space - As wide as a CJK character cell (fullwidth)
// used google to translate the word "term" to japanese -> ??
assertQueryEquals("term\u3000term\u3000term", null,
"term\u0020term\u0020term");
assertQueryEqualsAllowLeadingWildcard("??\u3000??\u3000??", null, "??\u0020??\u0020??");
}
//individual CJK chars as terms, like StandardAnalyzer
private class SimpleCJKTokenizer extends Tokenizer {
private CharTermAttribute termAtt = addAttribute(CharTermAttribute.class);
public SimpleCJKTokenizer(Reader input) {
super(input);
}
@Override
public boolean incrementToken() throws IOException {
int ch = input.read();
if (ch < 0)
return false;
clearAttributes();
termAtt.setEmpty().append((char) ch);
return true;
}
}
private class SimpleCJKAnalyzer extends Analyzer {
@Override
public TokenStream tokenStream(String fieldName, Reader reader) {
return new SimpleCJKTokenizer(reader);
}
}
public void testCJKTerm() throws Exception {
// individual CJK chars as terms
SimpleCJKAnalyzer analyzer = new SimpleCJKAnalyzer();
BooleanQuery expected = new BooleanQuery();
expected.add(new TermQuery(new Term("field", "中")), BooleanClause.Occur.SHOULD);
expected.add(new TermQuery(new Term("field", "国")), BooleanClause.Occur.SHOULD);
assertEquals(expected, getQuery("中国", analyzer));
}
public void testCJKBoostedTerm() throws Exception {
// individual CJK chars as terms
SimpleCJKAnalyzer analyzer = new SimpleCJKAnalyzer();
BooleanQuery expected = new BooleanQuery();
expected.setBoost(0.5f);
expected.add(new TermQuery(new Term("field", "中")), BooleanClause.Occur.SHOULD);
expected.add(new TermQuery(new Term("field", "国")), BooleanClause.Occur.SHOULD);
assertEquals(expected, getQuery("中国^0.5", analyzer));
}
public void testCJKPhrase() throws Exception {
// individual CJK chars as terms
SimpleCJKAnalyzer analyzer = new SimpleCJKAnalyzer();
PhraseQuery expected = new PhraseQuery();
expected.add(new Term("field", "中"));
expected.add(new Term("field", "国"));
assertEquals(expected, getQuery("\"中国\"", analyzer));
}
public void testCJKBoostedPhrase() throws Exception {
// individual CJK chars as terms
SimpleCJKAnalyzer analyzer = new SimpleCJKAnalyzer();
PhraseQuery expected = new PhraseQuery();
expected.setBoost(0.5f);
expected.add(new Term("field", "中"));
expected.add(new Term("field", "国"));
assertEquals(expected, getQuery("\"中国\"^0.5", analyzer));
}
public void testCJKSloppyPhrase() throws Exception {
// individual CJK chars as terms
SimpleCJKAnalyzer analyzer = new SimpleCJKAnalyzer();
PhraseQuery expected = new PhraseQuery();
expected.setSlop(3);
expected.add(new Term("field", "中"));
expected.add(new Term("field", "国"));
assertEquals(expected, getQuery("\"中国\"~3", analyzer));
}
public void testSimple() throws Exception {
assertQueryEquals("\"term germ\"~2", null, "\"term germ\"~2");
assertQueryEquals("term term term", null, "term term term");
assertQueryEquals("t�rm term term", new MockAnalyzer(MockTokenizer.WHITESPACE, false),
"t�rm term term");
assertQueryEquals("�mlaut", new MockAnalyzer(MockTokenizer.WHITESPACE, false), "�mlaut");
// FIXME: change MockAnalyzer to not extend CharTokenizer for this test
//assertQueryEquals("\"\"", new KeywordAnalyzer(), "");
//assertQueryEquals("foo:\"\"", new KeywordAnalyzer(), "foo:");
assertQueryEquals("a AND b", null, "+a +b");
assertQueryEquals("(a AND b)", null, "+a +b");
assertQueryEquals("c OR (a AND b)", null, "c (+a +b)");
assertQueryEquals("a AND NOT b", null, "+a -b");
assertQueryEquals("a AND -b", null, "+a -b");
assertQueryEquals("a AND !b", null, "+a -b");
assertQueryEquals("a && b", null, "+a +b");
assertQueryEquals("a && ! b", null, "+a -b");
assertQueryEquals("a OR b", null, "a b");
assertQueryEquals("a || b", null, "a b");
assertQueryEquals("a OR !b", null, "a -b");
assertQueryEquals("a OR ! b", null, "a -b");
assertQueryEquals("a OR -b", null, "a -b");
assertQueryEquals("+term -term term", null, "+term -term term");
assertQueryEquals("foo:term AND field:anotherTerm", null,
"+foo:term +anotherterm");
assertQueryEquals("term AND \"phrase phrase\"", null,
"+term +\"phrase phrase\"");
assertQueryEquals("\"hello there\"", null, "\"hello there\"");
assertTrue(getQuery("a AND b", null) instanceof BooleanQuery);
assertTrue(getQuery("hello", null) instanceof TermQuery);
assertTrue(getQuery("\"hello there\"", null) instanceof PhraseQuery);
assertQueryEquals("germ term^2.0", null, "germ term^2.0");
assertQueryEquals("(term)^2.0", null, "term^2.0");
assertQueryEquals("(germ term)^2.0", null, "(germ term)^2.0");
assertQueryEquals("term^2.0", null, "term^2.0");
assertQueryEquals("term^2", null, "term^2.0");
assertQueryEquals("\"germ term\"^2.0", null, "\"germ term\"^2.0");
assertQueryEquals("\"term germ\"^2", null, "\"term germ\"^2.0");
assertQueryEquals("(foo OR bar) AND (baz OR boo)", null,
"+(foo bar) +(baz boo)");
assertQueryEquals("((a OR b) AND NOT c) OR d", null, "(+(a b) -c) d");
assertQueryEquals("+(apple \"steve jobs\") -(foo bar baz)", null,
"+(apple \"steve jobs\") -(foo bar baz)");
assertQueryEquals("+title:(dog OR cat) -author:\"bob dole\"", null,
"+(title:dog title:cat) -author:\"bob dole\"");
}
public void testPunct() throws Exception {
Analyzer a = new MockAnalyzer(MockTokenizer.WHITESPACE, false);
assertQueryEquals("a&b", a, "a&b");
assertQueryEquals("a&&b", a, "a&&b");
assertQueryEquals(".NET", a, ".NET");
}
public void testSlop() throws Exception {
assertQueryEquals("\"term germ\"~2", null, "\"term germ\"~2");
assertQueryEquals("\"term germ\"~2 flork", null, "\"term germ\"~2 flork");
assertQueryEquals("\"term\"~2", null, "term");
assertQueryEquals("\" \"~2 germ", null, "germ");
assertQueryEquals("\"term germ\"~2^2", null, "\"term germ\"~2^2.0");
}
public void testNumber() throws Exception {
// The numbers go away because SimpleAnalzyer ignores them
assertQueryEquals("3", null, "");
assertQueryEquals("term 1.0 1 2", null, "term");
assertQueryEquals("term term1 term2", null, "term term term");
Analyzer a = new MockAnalyzer(MockTokenizer.WHITESPACE, false);
assertQueryEquals("3", a, "3");
assertQueryEquals("term 1.0 1 2", a, "term 1.0 1 2");
assertQueryEquals("term term1 term2", a, "term term1 term2");
}
public void testWildcard() throws Exception {
assertQueryEquals("term*", null, "term*");
assertQueryEquals("term*^2", null, "term*^2.0");
assertQueryEquals("term~", null, "term~0.5");
assertQueryEquals("term~0.7", null, "term~0.7");
assertQueryEquals("term~^2", null, "term~0.5^2.0");
assertQueryEquals("term^2~", null, "term~0.5^2.0");
assertQueryEquals("term*germ", null, "term*germ");
assertQueryEquals("term*germ^3", null, "term*germ^3.0");
assertTrue(getQuery("term*", null) instanceof PrefixQuery);
assertTrue(getQuery("term*^2", null) instanceof PrefixQuery);
assertTrue(getQuery("term~", null) instanceof FuzzyQuery);
assertTrue(getQuery("term~0.7", null) instanceof FuzzyQuery);
FuzzyQuery fq = (FuzzyQuery) getQuery("term~0.7", null);
assertEquals(0.7f, fq.getMinSimilarity(), 0.1f);
assertEquals(FuzzyQuery.defaultPrefixLength, fq.getPrefixLength());
fq = (FuzzyQuery) getQuery("term~", null);
assertEquals(0.5f, fq.getMinSimilarity(), 0.1f);
assertEquals(FuzzyQuery.defaultPrefixLength, fq.getPrefixLength());
assertQueryNodeException("term~1.1"); // value > 1, throws exception
assertTrue(getQuery("term*germ", null) instanceof WildcardQuery);
/*
* Tests to see that wild card terms are (or are not) properly lower-cased
* with propery parser configuration
*/
// First prefix queries:
// by default, convert to lowercase:
assertWildcardQueryEquals("Term*", true, "term*");
// explicitly set lowercase:
assertWildcardQueryEquals("term*", true, "term*");
assertWildcardQueryEquals("Term*", true, "term*");
assertWildcardQueryEquals("TERM*", true, "term*");
// explicitly disable lowercase conversion:
assertWildcardQueryEquals("term*", false, "term*");
assertWildcardQueryEquals("Term*", false, "Term*");
assertWildcardQueryEquals("TERM*", false, "TERM*");
// Then 'full' wildcard queries:
// by default, convert to lowercase:
assertWildcardQueryEquals("Te?m", "te?m");
// explicitly set lowercase:
assertWildcardQueryEquals("te?m", true, "te?m");
assertWildcardQueryEquals("Te?m", true, "te?m");
assertWildcardQueryEquals("TE?M", true, "te?m");
assertWildcardQueryEquals("Te?m*gerM", true, "te?m*germ");
// explicitly disable lowercase conversion:
assertWildcardQueryEquals("te?m", false, "te?m");
assertWildcardQueryEquals("Te?m", false, "Te?m");
assertWildcardQueryEquals("TE?M", false, "TE?M");
assertWildcardQueryEquals("Te?m*gerM", false, "Te?m*gerM");
// Fuzzy queries:
assertWildcardQueryEquals("Term~", "term~0.5");
assertWildcardQueryEquals("Term~", true, "term~0.5");
assertWildcardQueryEquals("Term~", false, "Term~0.5");
// Range queries:
// TODO: implement this on QueryParser
// Q0002E_INVALID_SYNTAX_CANNOT_PARSE: Syntax Error, cannot parse '[A TO
// C]': Lexical error at line 1, column 1. Encountered: "[" (91), after
// : ""
assertWildcardQueryEquals("[A TO C]", "[a TO c]");
assertWildcardQueryEquals("[A TO C]", true, "[a TO c]");
assertWildcardQueryEquals("[A TO C]", false, "[A TO C]");
// Test suffix queries: first disallow
try {
assertWildcardQueryEquals("*Term", true, "*term");
fail();
} catch (QueryNodeException pe) {
// expected exception
}
try {
assertWildcardQueryEquals("?Term", true, "?term");
fail();
} catch (QueryNodeException pe) {
// expected exception
}
// Test suffix queries: then allow
assertWildcardQueryEquals("*Term", true, "*term", true);
assertWildcardQueryEquals("?Term", true, "?term", true);
}
public void testLeadingWildcardType() throws Exception {
StandardQueryParser qp = getParser(null);
qp.setAllowLeadingWildcard(true);
assertEquals(WildcardQuery.class, qp.parse("t*erm*", "field").getClass());
assertEquals(WildcardQuery.class, qp.parse("?term*", "field").getClass());
assertEquals(WildcardQuery.class, qp.parse("*term*", "field").getClass());
}
public void testQPA() throws Exception {
assertQueryEquals("term term^3.0 term", qpAnalyzer, "term term^3.0 term");
assertQueryEquals("term stop^3.0 term", qpAnalyzer, "term term");
assertQueryEquals("term term term", qpAnalyzer, "term term term");
assertQueryEquals("term +stop term", qpAnalyzer, "term term");
assertQueryEquals("term -stop term", qpAnalyzer, "term term");
assertQueryEquals("drop AND (stop) AND roll", qpAnalyzer, "+drop +roll");
assertQueryEquals("term +(stop) term", qpAnalyzer, "term term");
assertQueryEquals("term -(stop) term", qpAnalyzer, "term term");
assertQueryEquals("drop AND stop AND roll", qpAnalyzer, "+drop +roll");
assertQueryEquals("term phrase term", qpAnalyzer,
"term phrase1 phrase2 term");
assertQueryEquals("term AND NOT phrase term", qpAnalyzer,
"+term -(phrase1 phrase2) term");
assertQueryEquals("stop^3", qpAnalyzer, "");
assertQueryEquals("stop", qpAnalyzer, "");
assertQueryEquals("(stop)^3", qpAnalyzer, "");
assertQueryEquals("((stop))^3", qpAnalyzer, "");
assertQueryEquals("(stop^3)", qpAnalyzer, "");
assertQueryEquals("((stop)^3)", qpAnalyzer, "");
assertQueryEquals("(stop)", qpAnalyzer, "");
assertQueryEquals("((stop))", qpAnalyzer, "");
assertTrue(getQuery("term term term", qpAnalyzer) instanceof BooleanQuery);
assertTrue(getQuery("term +stop", qpAnalyzer) instanceof TermQuery);
}
public void testRange() throws Exception {
assertQueryEquals("[ a TO z]", null, "[a TO z]");
assertEquals(MultiTermQuery.CONSTANT_SCORE_AUTO_REWRITE_DEFAULT, ((TermRangeQuery)getQuery("[ a TO z]", null)).getRewriteMethod());
StandardQueryParser qp = new StandardQueryParser();
qp.setMultiTermRewriteMethod(MultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE);
assertEquals(MultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE,((TermRangeQuery)qp.parse("[ a TO z]", "field")).getRewriteMethod());
assertQueryEquals("[ a TO z ]", null, "[a TO z]");
assertQueryEquals("{ a TO z}", null, "{a TO z}");
assertQueryEquals("{ a TO z }", null, "{a TO z}");
assertQueryEquals("{ a TO z }^2.0", null, "{a TO z}^2.0");
assertQueryEquals("[ a TO z] OR bar", null, "[a TO z] bar");
assertQueryEquals("[ a TO z] AND bar", null, "+[a TO z] +bar");
assertQueryEquals("( bar blar { a TO z}) ", null, "bar blar {a TO z}");
assertQueryEquals("gack ( bar blar { a TO z}) ", null,
"gack (bar blar {a TO z})");
}
public void testFarsiRangeCollating() throws Exception {
Directory ramDir = newDirectory();
IndexWriter iw = new IndexWriter(ramDir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(MockTokenizer.WHITESPACE, false)));
Document doc = new Document();
doc.add(newField("content", "\u0633\u0627\u0628", Field.Store.YES,
Field.Index.NOT_ANALYZED));
iw.addDocument(doc);
iw.close();
IndexSearcher is = new IndexSearcher(ramDir, true);
StandardQueryParser qp = new StandardQueryParser();
qp.setAnalyzer(new MockAnalyzer(MockTokenizer.WHITESPACE, false));
// Neither Java 1.4.2 nor 1.5.0 has Farsi Locale collation available in
// RuleBasedCollator. However, the Arabic Locale seems to order the
// Farsi
// characters properly.
Collator c = Collator.getInstance(new Locale("ar"));
qp.setRangeCollator(c);
// Unicode order would include U+0633 in [ U+062F - U+0698 ], but Farsi
// orders the U+0698 character before the U+0633 character, so the
// single
// index Term below should NOT be returned by a ConstantScoreRangeQuery
// with a Farsi Collator (or an Arabic one for the case when Farsi is
// not
// supported).
// Test ConstantScoreRangeQuery
qp.setMultiTermRewriteMethod(MultiTermQuery.CONSTANT_SCORE_FILTER_REWRITE);
ScoreDoc[] result = is.search(qp.parse("[ \u062F TO \u0698 ]", "content"),
null, 1000).scoreDocs;
assertEquals("The index Term should not be included.", 0, result.length);
result = is.search(qp.parse("[ \u0633 TO \u0638 ]", "content"), null, 1000).scoreDocs;
assertEquals("The index Term should be included.", 1, result.length);
// Test RangeQuery
qp.setMultiTermRewriteMethod(MultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE);
result = is.search(qp.parse("[ \u062F TO \u0698 ]", "content"), null, 1000).scoreDocs;
assertEquals("The index Term should not be included.", 0, result.length);
result = is.search(qp.parse("[ \u0633 TO \u0638 ]", "content"), null, 1000).scoreDocs;
assertEquals("The index Term should be included.", 1, result.length);
is.close();
ramDir.close();
}
/** for testing legacy DateField support */
private String getLegacyDate(String s) throws Exception {
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
return DateField.dateToString(df.parse(s));
}
/** for testing DateTools support */
private String getDate(String s, DateTools.Resolution resolution)
throws Exception {
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
return getDate(df.parse(s), resolution);
}
/** for testing DateTools support */
private String getDate(Date d, DateTools.Resolution resolution)
throws Exception {
if (resolution == null) {
return DateField.dateToString(d);
} else {
return DateTools.dateToString(d, resolution);
}
}
private String escapeDateString(String s) {
if (s.contains(" ")) {
return "\"" + s + "\"";
} else {
return s;
}
}
private String getLocalizedDate(int year, int month, int day) {
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
Calendar calendar = new GregorianCalendar();
calendar.clear();
calendar.set(year, month, day);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
return df.format(calendar.getTime());
}
/** for testing legacy DateField support */
public void testLegacyDateRange() throws Exception {
String startDate = getLocalizedDate(2002, 1, 1);
String endDate = getLocalizedDate(2002, 1, 4);
Calendar endDateExpected = new GregorianCalendar();
endDateExpected.clear();
endDateExpected.set(2002, 1, 4, 23, 59, 59);
endDateExpected.set(Calendar.MILLISECOND, 999);
assertQueryEquals("[ " + escapeDateString(startDate) + " TO " + escapeDateString(endDate) + "]", null, "["
+ getLegacyDate(startDate) + " TO "
+ DateField.dateToString(endDateExpected.getTime()) + "]");
assertQueryEquals("{ " + escapeDateString(startDate) + " " + escapeDateString(endDate) + " }", null, "{"
+ getLegacyDate(startDate) + " TO " + getLegacyDate(endDate) + "}");
}
public void testDateRange() throws Exception {
String startDate = getLocalizedDate(2002, 1, 1);
String endDate = getLocalizedDate(2002, 1, 4);
Calendar endDateExpected = new GregorianCalendar();
endDateExpected.clear();
endDateExpected.set(2002, 1, 4, 23, 59, 59);
endDateExpected.set(Calendar.MILLISECOND, 999);
final String defaultField = "default";
final String monthField = "month";
final String hourField = "hour";
StandardQueryParser qp = new StandardQueryParser();
// Don't set any date resolution and verify if DateField is used
assertDateRangeQueryEquals(qp, defaultField, startDate, endDate,
endDateExpected.getTime(), null);
Map<CharSequence, DateTools.Resolution> dateRes = new HashMap<CharSequence, DateTools.Resolution>();
// set a field specific date resolution
dateRes.put(monthField, DateTools.Resolution.MONTH);
qp.setDateResolution(dateRes);
// DateField should still be used for defaultField
assertDateRangeQueryEquals(qp, defaultField, startDate, endDate,
endDateExpected.getTime(), null);
// set default date resolution to MILLISECOND
qp.setDateResolution(DateTools.Resolution.MILLISECOND);
// set second field specific date resolution
dateRes.put(hourField, DateTools.Resolution.HOUR);
qp.setDateResolution(dateRes);
// for this field no field specific date resolution has been set,
// so verify if the default resolution is used
assertDateRangeQueryEquals(qp, defaultField, startDate, endDate,
endDateExpected.getTime(), DateTools.Resolution.MILLISECOND);
// verify if field specific date resolutions are used for these two
// fields
assertDateRangeQueryEquals(qp, monthField, startDate, endDate,
endDateExpected.getTime(), DateTools.Resolution.MONTH);
assertDateRangeQueryEquals(qp, hourField, startDate, endDate,
endDateExpected.getTime(), DateTools.Resolution.HOUR);
}
public void assertDateRangeQueryEquals(StandardQueryParser qp,
String field, String startDate, String endDate, Date endDateInclusive,
DateTools.Resolution resolution) throws Exception {
assertQueryEquals(qp, field, field + ":[" + escapeDateString(startDate) + " TO " + escapeDateString(endDate)
+ "]", "[" + getDate(startDate, resolution) + " TO "
+ getDate(endDateInclusive, resolution) + "]");
assertQueryEquals(qp, field, field + ":{" + escapeDateString(startDate) + " TO " + escapeDateString(endDate)
+ "}", "{" + getDate(startDate, resolution) + " TO "
+ getDate(endDate, resolution) + "}");
}
public void testEscaped() throws Exception {
Analyzer a = new MockAnalyzer(MockTokenizer.WHITESPACE, false);
/*
* assertQueryEquals("\\[brackets", a, "\\[brackets");
* assertQueryEquals("\\[brackets", null, "brackets");
* assertQueryEquals("\\\\", a, "\\\\"); assertQueryEquals("\\+blah", a,
* "\\+blah"); assertQueryEquals("\\(blah", a, "\\(blah");
*
* assertQueryEquals("\\-blah", a, "\\-blah"); assertQueryEquals("\\!blah",
* a, "\\!blah"); assertQueryEquals("\\{blah", a, "\\{blah");
* assertQueryEquals("\\}blah", a, "\\}blah"); assertQueryEquals("\\:blah",
* a, "\\:blah"); assertQueryEquals("\\^blah", a, "\\^blah");
* assertQueryEquals("\\[blah", a, "\\[blah"); assertQueryEquals("\\]blah",
* a, "\\]blah"); assertQueryEquals("\\\"blah", a, "\\\"blah");
* assertQueryEquals("\\(blah", a, "\\(blah"); assertQueryEquals("\\)blah",
* a, "\\)blah"); assertQueryEquals("\\~blah", a, "\\~blah");
* assertQueryEquals("\\*blah", a, "\\*blah"); assertQueryEquals("\\?blah",
* a, "\\?blah"); //assertQueryEquals("foo \\&\\& bar", a,
* "foo \\&\\& bar"); //assertQueryEquals("foo \\|| bar", a,
* "foo \\|| bar"); //assertQueryEquals("foo \\AND bar", a,
* "foo \\AND bar");
*/
assertQueryEquals("\\*", a, "*");
assertQueryEquals("\\a", a, "a");
assertQueryEquals("a\\-b:c", a, "a-b:c");
assertQueryEquals("a\\+b:c", a, "a+b:c");
assertQueryEquals("a\\:b:c", a, "a:b:c");
assertQueryEquals("a\\\\b:c", a, "a\\b:c");
assertQueryEquals("a:b\\-c", a, "a:b-c");
assertQueryEquals("a:b\\+c", a, "a:b+c");
assertQueryEquals("a:b\\:c", a, "a:b:c");
assertQueryEquals("a:b\\\\c", a, "a:b\\c");
assertQueryEquals("a:b\\-c*", a, "a:b-c*");
assertQueryEquals("a:b\\+c*", a, "a:b+c*");
assertQueryEquals("a:b\\:c*", a, "a:b:c*");
assertQueryEquals("a:b\\\\c*", a, "a:b\\c*");
assertQueryEquals("a:b\\-?c", a, "a:b-?c");
assertQueryEquals("a:b\\+?c", a, "a:b+?c");
assertQueryEquals("a:b\\:?c", a, "a:b:?c");
assertQueryEquals("a:b\\\\?c", a, "a:b\\?c");
assertQueryEquals("a:b\\-c~", a, "a:b-c~0.5");
assertQueryEquals("a:b\\+c~", a, "a:b+c~0.5");
assertQueryEquals("a:b\\:c~", a, "a:b:c~0.5");
assertQueryEquals("a:b\\\\c~", a, "a:b\\c~0.5");
// TODO: implement Range queries on QueryParser
assertQueryEquals("[ a\\- TO a\\+ ]", null, "[a- TO a+]");
assertQueryEquals("[ a\\: TO a\\~ ]", null, "[a: TO a~]");
assertQueryEquals("[ a\\\\ TO a\\* ]", null, "[a\\ TO a*]");
assertQueryEquals(
"[\"c\\:\\\\temp\\\\\\~foo0.txt\" TO \"c\\:\\\\temp\\\\\\~foo9.txt\"]",
a, "[c:\\temp\\~foo0.txt TO c:\\temp\\~foo9.txt]");
assertQueryEquals("a\\\\\\+b", a, "a\\+b");
assertQueryEquals("a \\\"b c\\\" d", a, "a \"b c\" d");
assertQueryEquals("\"a \\\"b c\\\" d\"", a, "\"a \"b c\" d\"");
assertQueryEquals("\"a \\+b c d\"", a, "\"a +b c d\"");
assertQueryEquals("c\\:\\\\temp\\\\\\~foo.txt", a, "c:\\temp\\~foo.txt");
assertQueryNodeException("XY\\"); // there must be a character after the
// escape char
// test unicode escaping
assertQueryEquals("a\\u0062c", a, "abc");
assertQueryEquals("XY\\u005a", a, "XYZ");
assertQueryEquals("XY\\u005A", a, "XYZ");
assertQueryEquals("\"a \\\\\\u0028\\u0062\\\" c\"", a, "\"a \\(b\" c\"");
assertQueryNodeException("XY\\u005G"); // test non-hex character in escaped
// unicode sequence
assertQueryNodeException("XY\\u005"); // test incomplete escaped unicode
// sequence
// Tests bug LUCENE-800
assertQueryEquals("(item:\\\\ item:ABCD\\\\)", a, "item:\\ item:ABCD\\");
assertQueryNodeException("(item:\\\\ item:ABCD\\\\))"); // unmatched closing
// paranthesis
assertQueryEquals("\\*", a, "*");
assertQueryEquals("\\\\", a, "\\"); // escaped backslash
assertQueryNodeException("\\"); // a backslash must always be escaped
// LUCENE-1189
assertQueryEquals("(\"a\\\\\") or (\"b\")", a, "a\\ or b");
}
public void testQueryStringEscaping() throws Exception {
Analyzer a = new MockAnalyzer(MockTokenizer.WHITESPACE, false);
assertEscapedQueryEquals("a-b:c", a, "a\\-b\\:c");
assertEscapedQueryEquals("a+b:c", a, "a\\+b\\:c");
assertEscapedQueryEquals("a:b:c", a, "a\\:b\\:c");
assertEscapedQueryEquals("a\\b:c", a, "a\\\\b\\:c");
assertEscapedQueryEquals("a:b-c", a, "a\\:b\\-c");
assertEscapedQueryEquals("a:b+c", a, "a\\:b\\+c");
assertEscapedQueryEquals("a:b:c", a, "a\\:b\\:c");
assertEscapedQueryEquals("a:b\\c", a, "a\\:b\\\\c");
assertEscapedQueryEquals("a:b-c*", a, "a\\:b\\-c\\*");
assertEscapedQueryEquals("a:b+c*", a, "a\\:b\\+c\\*");
assertEscapedQueryEquals("a:b:c*", a, "a\\:b\\:c\\*");
assertEscapedQueryEquals("a:b\\\\c*", a, "a\\:b\\\\\\\\c\\*");
assertEscapedQueryEquals("a:b-?c", a, "a\\:b\\-\\?c");
assertEscapedQueryEquals("a:b+?c", a, "a\\:b\\+\\?c");
assertEscapedQueryEquals("a:b:?c", a, "a\\:b\\:\\?c");
assertEscapedQueryEquals("a:b?c", a, "a\\:b\\?c");
assertEscapedQueryEquals("a:b-c~", a, "a\\:b\\-c\\~");
assertEscapedQueryEquals("a:b+c~", a, "a\\:b\\+c\\~");
assertEscapedQueryEquals("a:b:c~", a, "a\\:b\\:c\\~");
assertEscapedQueryEquals("a:b\\c~", a, "a\\:b\\\\c\\~");
assertEscapedQueryEquals("[ a - TO a+ ]", null, "\\[ a \\- TO a\\+ \\]");
assertEscapedQueryEquals("[ a : TO a~ ]", null, "\\[ a \\: TO a\\~ \\]");
assertEscapedQueryEquals("[ a\\ TO a* ]", null, "\\[ a\\\\ TO a\\* \\]");
// LUCENE-881
assertEscapedQueryEquals("|| abc ||", a, "\\|\\| abc \\|\\|");
assertEscapedQueryEquals("&& abc &&", a, "\\&\\& abc \\&\\&");
}
public void testTabNewlineCarriageReturn() throws Exception {
assertQueryEqualsDOA("+weltbank +worlbank", null, "+weltbank +worlbank");
assertQueryEqualsDOA("+weltbank\n+worlbank", null, "+weltbank +worlbank");
assertQueryEqualsDOA("weltbank \n+worlbank", null, "+weltbank +worlbank");
assertQueryEqualsDOA("weltbank \n +worlbank", null, "+weltbank +worlbank");
assertQueryEqualsDOA("+weltbank\r+worlbank", null, "+weltbank +worlbank");
assertQueryEqualsDOA("weltbank \r+worlbank", null, "+weltbank +worlbank");
assertQueryEqualsDOA("weltbank \r +worlbank", null, "+weltbank +worlbank");
assertQueryEqualsDOA("+weltbank\r\n+worlbank", null, "+weltbank +worlbank");
assertQueryEqualsDOA("weltbank \r\n+worlbank", null, "+weltbank +worlbank");
assertQueryEqualsDOA("weltbank \r\n +worlbank", null, "+weltbank +worlbank");
assertQueryEqualsDOA("weltbank \r \n +worlbank", null,
"+weltbank +worlbank");
assertQueryEqualsDOA("+weltbank\t+worlbank", null, "+weltbank +worlbank");
assertQueryEqualsDOA("weltbank \t+worlbank", null, "+weltbank +worlbank");
assertQueryEqualsDOA("weltbank \t +worlbank", null, "+weltbank +worlbank");
}
public void testSimpleDAO() throws Exception {
assertQueryEqualsDOA("term term term", null, "+term +term +term");
assertQueryEqualsDOA("term +term term", null, "+term +term +term");
assertQueryEqualsDOA("term term +term", null, "+term +term +term");
assertQueryEqualsDOA("term +term +term", null, "+term +term +term");
assertQueryEqualsDOA("-term term term", null, "-term +term +term");
}
public void testBoost() throws Exception {
CharacterRunAutomaton stopSet = new CharacterRunAutomaton(BasicAutomata.makeString("on"));
Analyzer oneStopAnalyzer = new MockAnalyzer(MockTokenizer.SIMPLE, true, stopSet, true);
StandardQueryParser qp = new StandardQueryParser();
qp.setAnalyzer(oneStopAnalyzer);
Query q = qp.parse("on^1.0", "field");
assertNotNull(q);
q = qp.parse("\"hello\"^2.0", "field");
assertNotNull(q);
assertEquals(q.getBoost(), (float) 2.0, (float) 0.5);
q = qp.parse("hello^2.0", "field");
assertNotNull(q);
assertEquals(q.getBoost(), (float) 2.0, (float) 0.5);
q = qp.parse("\"on\"^1.0", "field");
assertNotNull(q);
StandardQueryParser qp2 = new StandardQueryParser();
qp2.setAnalyzer(new MockAnalyzer(MockTokenizer.SIMPLE, true, MockTokenFilter.ENGLISH_STOPSET, true));
q = qp2.parse("the^3", "field");
// "the" is a stop word so the result is an empty query:
assertNotNull(q);
assertEquals("", q.toString());
assertEquals(1.0f, q.getBoost(), 0.01f);
}
public void assertQueryNodeException(String queryString) throws Exception {
try {
getQuery(queryString, null);
} catch (QueryNodeException expected) {
return;
}
fail("ParseException expected, not thrown");
}
public void testException() throws Exception {
assertQueryNodeException("*leadingWildcard"); // disallowed by default
assertQueryNodeException("\"some phrase");
assertQueryNodeException("(foo bar");
assertQueryNodeException("foo bar))");
assertQueryNodeException("field:term:with:colon some more terms");
assertQueryNodeException("(sub query)^5.0^2.0 plus more");
assertQueryNodeException("secret AND illegal) AND access:confidential");
}
public void testCustomQueryParserWildcard() {
try {
new QPTestParser(new MockAnalyzer(MockTokenizer.WHITESPACE, false)).parse("a?t", "contents");
fail("Wildcard queries should not be allowed");
} catch (QueryNodeException expected) {
// expected exception
}
}
public void testCustomQueryParserFuzzy() throws Exception {
try {
new QPTestParser(new MockAnalyzer(MockTokenizer.WHITESPACE, false)).parse("xunit~", "contents");
fail("Fuzzy queries should not be allowed");
} catch (QueryNodeException expected) {
// expected exception
}
}
public void testBooleanQuery() throws Exception {
BooleanQuery.setMaxClauseCount(2);
try {
StandardQueryParser qp = new StandardQueryParser();
qp.setAnalyzer(new MockAnalyzer(MockTokenizer.WHITESPACE, false));
qp.parse("one two three", "field");
fail("ParseException expected due to too many boolean clauses");
} catch (QueryNodeException expected) {
// too many boolean clauses, so ParseException is expected
}
}
/**
* This test differs from TestPrecedenceQueryParser
*/
public void testPrecedence() throws Exception {
StandardQueryParser qp = new StandardQueryParser();
qp.setAnalyzer(new MockAnalyzer(MockTokenizer.WHITESPACE, false));
Query query1 = qp.parse("A AND B OR C AND D", "field");
Query query2 = qp.parse("+A +B +C +D", "field");
assertEquals(query1, query2);
}
public void testLocalDateFormat() throws IOException, QueryNodeException {
Directory ramDir = newDirectory();
IndexWriter iw = new IndexWriter(ramDir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(MockTokenizer.WHITESPACE, false)));
addDateDoc("a", 2005, 12, 2, 10, 15, 33, iw);
addDateDoc("b", 2005, 12, 4, 22, 15, 00, iw);
iw.close();
IndexSearcher is = new IndexSearcher(ramDir, true);
assertHits(1, "[12/1/2005 TO 12/3/2005]", is);
assertHits(2, "[12/1/2005 TO 12/4/2005]", is);
assertHits(1, "[12/3/2005 TO 12/4/2005]", is);
assertHits(1, "{12/1/2005 TO 12/3/2005}", is);
assertHits(1, "{12/1/2005 TO 12/4/2005}", is);
assertHits(0, "{12/3/2005 TO 12/4/2005}", is);
is.close();
ramDir.close();
}
public void testStarParsing() throws Exception {
// final int[] type = new int[1];
// StandardQueryParser qp = new StandardQueryParser("field", new
// WhitespaceAnalyzer()) {
// protected Query getWildcardQuery(String field, String termStr) throws
// ParseException {
// // override error checking of superclass
// type[0]=1;
// return new TermQuery(new Term(field,termStr));
// }
// protected Query getPrefixQuery(String field, String termStr) throws
// ParseException {
// // override error checking of superclass
// type[0]=2;
// return new TermQuery(new Term(field,termStr));
// }
//
// protected Query getFieldQuery(String field, String queryText) throws
// ParseException {
// type[0]=3;
// return super.getFieldQuery(field, queryText);
// }
// };
//
// TermQuery tq;
//
// tq = (TermQuery)qp.parse("foo:zoo*");
// assertEquals("zoo",tq.getTerm().text());
// assertEquals(2,type[0]);
//
// tq = (TermQuery)qp.parse("foo:zoo*^2");
// assertEquals("zoo",tq.getTerm().text());
// assertEquals(2,type[0]);
// assertEquals(tq.getBoost(),2,0);
//
// tq = (TermQuery)qp.parse("foo:*");
// assertEquals("*",tq.getTerm().text());
// assertEquals(1,type[0]); // could be a valid prefix query in the
// future too
//
// tq = (TermQuery)qp.parse("foo:*^2");
// assertEquals("*",tq.getTerm().text());
// assertEquals(1,type[0]);
// assertEquals(tq.getBoost(),2,0);
//
// tq = (TermQuery)qp.parse("*:foo");
// assertEquals("*",tq.getTerm().field());
// assertEquals("foo",tq.getTerm().text());
// assertEquals(3,type[0]);
//
// tq = (TermQuery)qp.parse("*:*");
// assertEquals("*",tq.getTerm().field());
// assertEquals("*",tq.getTerm().text());
// assertEquals(1,type[0]); // could be handled as a prefix query in the
// future
//
// tq = (TermQuery)qp.parse("(*:*)");
// assertEquals("*",tq.getTerm().field());
// assertEquals("*",tq.getTerm().text());
// assertEquals(1,type[0]);
}
public void testRegexps() throws Exception {
StandardQueryParser qp = new StandardQueryParser();
final String df = "field" ;
RegexpQuery q = new RegexpQuery(new Term("field", "[a-z][123]"));
assertEquals(q, qp.parse("/[a-z][123]/", df));
qp.setLowercaseExpandedTerms(true);
assertEquals(q, qp.parse("/[A-Z][123]/", df));
q.setBoost(0.5f);
assertEquals(q, qp.parse("/[A-Z][123]/^0.5", df));
qp.setMultiTermRewriteMethod(MultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE);
q.setRewriteMethod(MultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE);
assertTrue(qp.parse("/[A-Z][123]/^0.5", df) instanceof RegexpQuery);
assertEquals(q, qp.parse("/[A-Z][123]/^0.5", df));
assertEquals(MultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE, ((RegexpQuery)qp.parse("/[A-Z][123]/^0.5", df)).getRewriteMethod());
qp.setMultiTermRewriteMethod(MultiTermQuery.CONSTANT_SCORE_AUTO_REWRITE_DEFAULT);
Query escaped = new RegexpQuery(new Term("field", "[a-z]\\/[123]"));
assertEquals(escaped, qp.parse("/[a-z]\\/[123]/", df));
Query escaped2 = new RegexpQuery(new Term("field", "[a-z]\\*[123]"));
assertEquals(escaped2, qp.parse("/[a-z]\\*[123]/", df));
BooleanQuery complex = new BooleanQuery();
complex.add(new RegexpQuery(new Term("field", "[a-z]\\/[123]")), Occur.MUST);
complex.add(new TermQuery(new Term("path", "/etc/init.d/")), Occur.MUST);
complex.add(new TermQuery(new Term("field", "/etc/init[.]d/lucene/")), Occur.SHOULD);
assertEquals(complex, qp.parse("/[a-z]\\/[123]/ AND path:/etc/init.d/ OR /etc\\/init\\[.\\]d/lucene/ ", df));
}
public void testStopwords() throws Exception {
StandardQueryParser qp = new StandardQueryParser();
CharacterRunAutomaton stopSet = new CharacterRunAutomaton(new RegExp("the|foo").toAutomaton());
qp.setAnalyzer(new MockAnalyzer(MockTokenizer.SIMPLE, true, stopSet, true));
Query result = qp.parse("a:the OR a:foo", "a");
assertNotNull("result is null and it shouldn't be", result);
assertTrue("result is not a BooleanQuery", result instanceof BooleanQuery);
assertTrue(((BooleanQuery) result).clauses().size() + " does not equal: "
+ 0, ((BooleanQuery) result).clauses().size() == 0);
result = qp.parse("a:woo OR a:the", "a");
assertNotNull("result is null and it shouldn't be", result);
assertTrue("result is not a TermQuery", result instanceof TermQuery);
result = qp.parse(
"(fieldX:xxxxx OR fieldy:xxxxxxxx)^2 AND (fieldx:the OR fieldy:foo)",
"a");
assertNotNull("result is null and it shouldn't be", result);
assertTrue("result is not a BooleanQuery", result instanceof BooleanQuery);
System.out.println("Result: " + result);
assertTrue(((BooleanQuery) result).clauses().size() + " does not equal: "
+ 2, ((BooleanQuery) result).clauses().size() == 2);
}
public void testPositionIncrement() throws Exception {
StandardQueryParser qp = new StandardQueryParser();
qp.setAnalyzer(
new MockAnalyzer(MockTokenizer.SIMPLE, true, MockTokenFilter.ENGLISH_STOPSET, true));
qp.setEnablePositionIncrements(true);
String qtxt = "\"the words in poisitions pos02578 are stopped in this phrasequery\"";
// 0 2 5 7 8
int expectedPositions[] = { 1, 3, 4, 6, 9 };
PhraseQuery pq = (PhraseQuery) qp.parse(qtxt, "a");
// System.out.println("Query text: "+qtxt);
// System.out.println("Result: "+pq);
Term t[] = pq.getTerms();
int pos[] = pq.getPositions();
for (int i = 0; i < t.length; i++) {
// System.out.println(i+". "+t[i]+" pos: "+pos[i]);
assertEquals("term " + i + " = " + t[i] + " has wrong term-position!",
expectedPositions[i], pos[i]);
}
}
public void testMatchAllDocs() throws Exception {
StandardQueryParser qp = new StandardQueryParser();
qp.setAnalyzer(new MockAnalyzer(MockTokenizer.WHITESPACE, false));
assertEquals(new MatchAllDocsQuery(), qp.parse("*:*", "field"));
assertEquals(new MatchAllDocsQuery(), qp.parse("(*:*)", "field"));
BooleanQuery bq = (BooleanQuery) qp.parse("+*:* -*:*", "field");
assertTrue(bq.getClauses()[0].getQuery() instanceof MatchAllDocsQuery);
assertTrue(bq.getClauses()[1].getQuery() instanceof MatchAllDocsQuery);
}
private void assertHits(int expected, String query, IndexSearcher is)
throws IOException, QueryNodeException {
StandardQueryParser qp = new StandardQueryParser();
qp.setAnalyzer(new MockAnalyzer(MockTokenizer.WHITESPACE, false));
qp.setLocale(Locale.ENGLISH);
Query q = qp.parse(query, "date");
ScoreDoc[] hits = is.search(q, null, 1000).scoreDocs;
assertEquals(expected, hits.length);
}
private void addDateDoc(String content, int year, int month, int day,
int hour, int minute, int second, IndexWriter iw) throws IOException {
Document d = new Document();
d.add(newField("f", content, Field.Store.YES, Field.Index.ANALYZED));
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
cal.set(year, month - 1, day, hour, minute, second);
d.add(newField("date", DateField.dateToString(cal.getTime()),
Field.Store.YES, Field.Index.NOT_ANALYZED));
iw.addDocument(d);
}
@Override
public void tearDown() throws Exception {
BooleanQuery.setMaxClauseCount(originalMaxClauses);
super.tearDown();
}
private class CannedTokenStream extends TokenStream {
private int upto = 0;
final PositionIncrementAttribute posIncr = addAttribute(PositionIncrementAttribute.class);
final CharTermAttribute term = addAttribute(CharTermAttribute.class);
@Override
public boolean incrementToken() {
clearAttributes();
if (upto == 4) {
return false;
}
if (upto == 0) {
posIncr.setPositionIncrement(1);
term.setEmpty().append("a");
} else if (upto == 1) {
posIncr.setPositionIncrement(1);
term.setEmpty().append("b");
} else if (upto == 2) {
posIncr.setPositionIncrement(0);
term.setEmpty().append("c");
} else {
posIncr.setPositionIncrement(0);
term.setEmpty().append("d");
}
upto++;
return true;
}
}
private class CannedAnalyzer extends Analyzer {
@Override
public TokenStream tokenStream(String ignored, Reader alsoIgnored) {
return new CannedTokenStream();
}
}
public void testMultiPhraseQuery() throws Exception {
Directory dir = newDirectory();
IndexWriter w = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new CannedAnalyzer()));
Document doc = new Document();
doc.add(newField("field", "", Field.Store.NO, Field.Index.ANALYZED));
w.addDocument(doc);
IndexReader r = w.getReader();
IndexSearcher s = new IndexSearcher(r);
Query q = new StandardQueryParser(new CannedAnalyzer()).parse("\"a\"", "field");
assertTrue(q instanceof MultiPhraseQuery);
assertEquals(1, s.search(q, 10).totalHits);
r.close();
w.close();
dir.close();
}
}
| quiet this test
git-svn-id: 308d55f399f3bd9aa0560a10e81a003040006c48@996720 13f79535-47bb-0310-9956-ffa450edef68
| lucene/contrib/queryparser/src/test/org/apache/lucene/queryParser/standard/TestQPHelper.java | quiet this test |
|
Java | apache-2.0 | 30e956361a1a4a30b4c93465939e114f7c1b9b6d | 0 | max3163/jmeter,liwangbest/jmeter,ubikloadpack/jmeter,irfanah/jmeter,ra0077/jmeter,thomsonreuters/jmeter,etnetera/jmeter,d0k1/jmeter,ubikloadpack/jmeter,liwangbest/jmeter,hizhangqi/jmeter-1,DoctorQ/jmeter,etnetera/jmeter,thomsonreuters/jmeter,irfanah/jmeter,vherilier/jmeter,max3163/jmeter,d0k1/jmeter,hizhangqi/jmeter-1,kyroskoh/jmeter,ubikfsabbe/jmeter,ubikloadpack/jmeter,fj11/jmeter,ra0077/jmeter,ubikfsabbe/jmeter,fj11/jmeter,kyroskoh/jmeter,hemikak/jmeter,etnetera/jmeter,etnetera/jmeter,etnetera/jmeter,max3163/jmeter,kschroeder/jmeter,vherilier/jmeter,hizhangqi/jmeter-1,irfanah/jmeter,hemikak/jmeter,hemikak/jmeter,kschroeder/jmeter,ubikfsabbe/jmeter,vherilier/jmeter,DoctorQ/jmeter,ubikfsabbe/jmeter,ubikloadpack/jmeter,d0k1/jmeter,kyroskoh/jmeter,tuanhq/jmeter,hemikak/jmeter,vherilier/jmeter,ra0077/jmeter,ThiagoGarciaAlves/jmeter,liwangbest/jmeter,tuanhq/jmeter,max3163/jmeter,ThiagoGarciaAlves/jmeter,tuanhq/jmeter,thomsonreuters/jmeter,ThiagoGarciaAlves/jmeter,DoctorQ/jmeter,d0k1/jmeter,fj11/jmeter,kschroeder/jmeter,ra0077/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.gui;
import java.awt.BorderLayout;
import java.awt.Insets;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.Element;
import org.apache.jmeter.gui.util.JSyntaxTextArea;
import org.apache.jmeter.gui.util.JTextScrollPane;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.LogEvent;
import org.apache.log.LogTarget;
import org.apache.log.format.PatternFormatter;
import org.fife.ui.rsyntaxtextarea.SyntaxConstants;
/**
* Panel that shows log events
*/
public class LoggerPanel extends JPanel implements LogTarget {
private static final long serialVersionUID = 6911128494402594429L;
private JSyntaxTextArea textArea;
private final PatternFormatter format;
// Limit length of log content
private static final int LOGGER_PANEL_MAX_LENGTH =
JMeterUtils.getPropDefault("jmeter.loggerpanel.maxlength", 80000); // $NON-NLS-1$
private static final int LOGGER_PANEL_MAX_LINES_COUNT = LOGGER_PANEL_MAX_LENGTH / 80; // $NON-NLS-1$
// Make panel handle event even if closed
private static final boolean LOGGER_PANEL_RECEIVE_WHEN_CLOSED =
JMeterUtils.getPropDefault("jmeter.loggerpanel.enable_when_closed", true); // $NON-NLS-1$
/**
* Pane for display JMeter log file
*/
public LoggerPanel() {
init();
format = new PatternFormatter(LoggingManager.DEFAULT_PATTERN + "\n"); // $NON-NLS-1$
}
private void init() {
this.setLayout(new BorderLayout());
// TEXTAREA
textArea = new JSyntaxTextArea(15, 80, true);
textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_NONE);
textArea.setCodeFoldingEnabled(false);
textArea.setAntiAliasingEnabled(false);
textArea.setEditable(false);
textArea.setLineWrap(false);
textArea.setLanguage("text");
textArea.setMargin(new Insets(2, 2, 2, 2)); // space between borders and text
JScrollPane areaScrollPane = new JTextScrollPane(textArea);
areaScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
areaScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
this.add(areaScrollPane, BorderLayout.CENTER);
}
/* (non-Javadoc)
* @see org.apache.log.LogTarget#processEvent(org.apache.log.LogEvent)
*/
@Override
public void processEvent(final LogEvent logEvent) {
if(!LOGGER_PANEL_RECEIVE_WHEN_CLOSED && !GuiPackage.getInstance().getMenuItemLoggerPanel().getModel().isSelected()) {
return;
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
synchronized (textArea) {
Document doc;
try {
doc = textArea.getDocument();
Element root = doc.getDefaultRootElement();
int lineCount = root.getElementCount();
if (lineCount>LOGGER_PANEL_MAX_LINES_COUNT) {
int end = root.getElement(lineCount-LOGGER_PANEL_MAX_LINES_COUNT-1).getEndOffset();
doc.remove(0, end);
}
doc.insertString(doc.getLength(), format.format(logEvent), null);
textArea.setCaretPosition(doc.getLength()-1);
} catch (BadLocationException e) {
// NOOP
}
}
}
});
}
/**
* Clear panel content
*/
public void clear() {
this.textArea.setText(""); // $NON-NLS-1$
}
}
| src/core/org/apache/jmeter/gui/LoggerPanel.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.gui;
import java.awt.BorderLayout;
import java.awt.Insets;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingUtilities;
import org.apache.jmeter.gui.util.JSyntaxTextArea;
import org.apache.jmeter.gui.util.JTextScrollPane;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.LogEvent;
import org.apache.log.LogTarget;
import org.apache.log.format.PatternFormatter;
/**
* Panel that shows log events
*/
public class LoggerPanel extends JPanel implements LogTarget {
private static final long serialVersionUID = 6911128494402594429L;
private JSyntaxTextArea textArea;
private final PatternFormatter format;
// Limit length of log content
private static final int LOGGER_PANEL_MAX_LENGTH =
JMeterUtils.getPropDefault("jmeter.loggerpanel.maxlength", 80000); // $NON-NLS-1$
// Make panel handle event even if closed
private static final boolean LOGGER_PANEL_RECEIVE_WHEN_CLOSED =
JMeterUtils.getPropDefault("jmeter.loggerpanel.enable_when_closed", true); // $NON-NLS-1$
/**
* Pane for display JMeter log file
*/
public LoggerPanel() {
init();
format = new PatternFormatter(LoggingManager.DEFAULT_PATTERN + "\n"); // $NON-NLS-1$
}
private void init() {
this.setLayout(new BorderLayout());
// TEXTAREA
textArea = new JSyntaxTextArea(15, 50, true);
textArea.setEditable(false);
textArea.setLineWrap(false);
textArea.setLanguage("text");
textArea.setMargin(new Insets(2, 2, 2, 2)); // space between borders and text
JScrollPane areaScrollPane = new JTextScrollPane(textArea);
areaScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
areaScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
this.add(areaScrollPane, BorderLayout.CENTER);
}
/* (non-Javadoc)
* @see org.apache.log.LogTarget#processEvent(org.apache.log.LogEvent)
*/
@Override
public void processEvent(final LogEvent logEvent) {
if(!LOGGER_PANEL_RECEIVE_WHEN_CLOSED && !GuiPackage.getInstance().getMenuItemLoggerPanel().getModel().isSelected()) {
return;
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
synchronized (textArea) {
textArea.append(format.format(logEvent));
int currentLength = textArea.getText().length();
// If LOGGER_PANEL_MAX_LENGTH is 0, it means all log events are kept
if(LOGGER_PANEL_MAX_LENGTH != 0 && currentLength> LOGGER_PANEL_MAX_LENGTH) {
textArea.setText(textArea.getText().substring(Math.max(0, currentLength-LOGGER_PANEL_MAX_LENGTH),
currentLength));
}
textArea.setCaretPosition(textArea.getText().length());
}
}
});
}
/**
* Clear panel content
*/
public void clear() {
this.textArea.setText(""); // $NON-NLS-1$
}
}
| Improve content update
git-svn-id: 5ccfe34f605a6c2f9041ff2965ab60012c62539a@1629964 13f79535-47bb-0310-9956-ffa450edef68
| src/core/org/apache/jmeter/gui/LoggerPanel.java | Improve content update |
|
Java | apache-2.0 | 77d48ad165ffe797a2920d3070942cb372f3d55b | 0 | narry/cloud-slang,CloudSlang/cloud-slang,shajyhia/score-language,natabeck/cloud-slang,shajyhia/score-language,narry/cloud-slang,jrosadohp/cloud-slang,jrosadohp/cloud-slang,CloudSlang/cloud-slang,CloudSlang/cloud-slang,natabeck/cloud-slang,CloudSlang/cloud-slang | /*
* (c) Copyright 2014 Hewlett-Packard Development Company, L.P.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Apache License v2.0 which accompany this distribution.
*
* The Apache License is available at
* http://www.apache.org/licenses/LICENSE-2.0
*/
package org.openscore.lang.cli.services;
import org.apache.commons.collections4.MapUtils;
import org.openscore.lang.api.Slang;
import org.openscore.lang.entities.CompilationArtifact;
import org.openscore.lang.entities.ScoreLangConstants;
import org.openscore.lang.runtime.env.ExecutionPath;
import org.openscore.lang.runtime.events.LanguageEventData;
import org.apache.commons.lang.StringUtils;
import org.openscore.events.EventConstants;
import org.openscore.events.ScoreEvent;
import org.openscore.events.ScoreEventListener;
import org.fusesource.jansi.Ansi;
import org.fusesource.jansi.AnsiConsole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.openscore.lang.entities.ScoreLangConstants.*;
import static org.openscore.lang.runtime.events.LanguageEventData.EXCEPTION;
import static org.openscore.lang.runtime.events.LanguageEventData.RESULT;
import static org.fusesource.jansi.Ansi.ansi;
/**
* @author Bonczidai Levente
* @since 11/13/2014
* @version $Id$
*/
@Service
public class ScoreServicesImpl implements ScoreServices{
public static final String SLANG_STEP_ERROR_MSG = "Slang Error : ";
public static final String SCORE_ERROR_EVENT_MSG = "Score Error Event :";
public static final String FLOW_FINISHED_WITH_FAILURE_MSG = "Flow finished with failure";
public static final String EXEC_START_PATH = "0/0";
public static final int OUTPUT_VALUE_LIMIT = 40;
@Autowired
private Slang slang;
private final static String TASK_PATH_PREFIX = "- ";
public void subscribe(ScoreEventListener eventHandler, Set<String> eventTypes) {
slang.subscribeOnEvents(eventHandler, eventTypes);
}
/**
* This method will trigger the flow in an Async matter.
* @param compilationArtifact the artifact to trigger
* @param inputs : flow inputs
* @return executionId
*/
@Override
public Long trigger(CompilationArtifact compilationArtifact, Map<String, ? extends Serializable> inputs, Map<String, ? extends Serializable> systemProperties) {
return slang.run(compilationArtifact, inputs, systemProperties);
}
/**
* This method will trigger the flow in a synchronize matter, meaning only one flow can run at a time.
* @param compilationArtifact the artifact to trigger
* @param inputs : flow inputs
* @return executionId
*/
@Override
public Long triggerSync(CompilationArtifact compilationArtifact, Map<String, ? extends Serializable> inputs, Map<String, ? extends Serializable> systemProperties){
//add start event
Set<String> handlerTypes = new HashSet<>();
handlerTypes.add(EventConstants.SCORE_FINISHED_EVENT);
handlerTypes.add(EventConstants.SCORE_ERROR_EVENT);
handlerTypes.add(EventConstants.SCORE_FAILURE_EVENT);
handlerTypes.add(SLANG_EXECUTION_EXCEPTION);
handlerTypes.add(EVENT_EXECUTION_FINISHED);
handlerTypes.add(EVENT_INPUT_END);
handlerTypes.add(EVENT_OUTPUT_END);
SyncTriggerEventListener scoreEventListener = new SyncTriggerEventListener();
slang.subscribeOnEvents(scoreEventListener, handlerTypes);
Long executionId = trigger(compilationArtifact, inputs, systemProperties);
while(!scoreEventListener.isFlowFinished()){
try {
Thread.sleep(200);
} catch (InterruptedException ignore) {}
}
slang.unSubscribeOnEvents(scoreEventListener);
return executionId;
}
private class SyncTriggerEventListener implements ScoreEventListener{
private AtomicBoolean flowFinished = new AtomicBoolean(false);
public boolean isFlowFinished() {
return flowFinished.get();
}
@Override
public synchronized void onEvent(ScoreEvent scoreEvent) throws InterruptedException {
@SuppressWarnings("unchecked") Map<String,Serializable> data = (Map<String,Serializable>)scoreEvent.getData();
switch (scoreEvent.getEventType()){
case EventConstants.SCORE_FINISHED_EVENT :
flowFinished.set(true);
break;
case EventConstants.SCORE_ERROR_EVENT :
printWithColor(Ansi.Color.RED, SCORE_ERROR_EVENT_MSG + data.get(EventConstants.SCORE_ERROR_LOG_MSG) + " , " +
data.get(EventConstants.SCORE_ERROR_MSG));
break;
case EventConstants.SCORE_FAILURE_EVENT :
printWithColor(Ansi.Color.RED,FLOW_FINISHED_WITH_FAILURE_MSG);
flowFinished.set(true);
break;
case ScoreLangConstants.SLANG_EXECUTION_EXCEPTION:
printWithColor(Ansi.Color.RED,SLANG_STEP_ERROR_MSG + data.get(EXCEPTION));
break;
case ScoreLangConstants.EVENT_INPUT_END:
String taskName = (String)data.get(LanguageEventData.levelName.TASK_NAME.name());
if(StringUtils.isNotEmpty(taskName)){
String prefix = getPrefix(data);
printWithColor(Ansi.Color.YELLOW, prefix + taskName);
}
break;
case ScoreLangConstants.EVENT_OUTPUT_END:
printOutputs(data);
break;
case EVENT_EXECUTION_FINISHED :
printFinishEvent(data);
break;
}
}
private void printOutputs(Map<String, Serializable> data) {
if(data.containsKey(LanguageEventData.OUTPUTS) && data.containsKey(LanguageEventData.PATH) && data.get(LanguageEventData.PATH).equals(EXEC_START_PATH)) {
@SuppressWarnings("unchecked") Map<String, String> outputs = new HashMap((Map<String, String>) data.get(LanguageEventData.OUTPUTS));
outputs.putAll(outputs);
if (MapUtils.isNotEmpty(outputs)) {
for (String key : outputs.keySet()) {
String outputValue = outputs.get(key);
if(StringUtils.isNotEmpty(outputValue)) {
outputs.put(key, StringUtils.abbreviate(outputValue, 0, OUTPUT_VALUE_LIMIT));
}
printWithColor(Ansi.Color.WHITE, "- " + key + " = " + outputs.get(key));
}
}
}
}
private String getPrefix(Map<String, Serializable> data) {
String path = (String) data.get(LanguageEventData.PATH);
int matches = StringUtils.countMatches(path, ExecutionPath.PATH_SEPARATOR);
return StringUtils.repeat(TASK_PATH_PREFIX, matches);
}
private void printFinishEvent(Map<String, Serializable> data) {
String flowResult = (String)data.get(RESULT);
String flowName = (String)data.get(LanguageEventData.levelName.EXECUTABLE_NAME.toString());
printWithColor(Ansi.Color.CYAN,"Flow : " + flowName + " finished with result : " + flowResult);
}
private void printWithColor(Ansi.Color color, String msg){
AnsiConsole.out().print(ansi().fg(color).a(msg).newline());
AnsiConsole.out().print(ansi().fg(Ansi.Color.WHITE));
}
}
}
| score-lang-cli/src/main/java/org/openscore/lang/cli/services/ScoreServicesImpl.java | /*
* (c) Copyright 2014 Hewlett-Packard Development Company, L.P.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Apache License v2.0 which accompany this distribution.
*
* The Apache License is available at
* http://www.apache.org/licenses/LICENSE-2.0
*/
package org.openscore.lang.cli.services;
import org.apache.commons.collections4.MapUtils;
import org.openscore.lang.api.Slang;
import org.openscore.lang.entities.CompilationArtifact;
import org.openscore.lang.entities.ScoreLangConstants;
import org.openscore.lang.runtime.env.ExecutionPath;
import org.openscore.lang.runtime.events.LanguageEventData;
import org.apache.commons.lang.StringUtils;
import org.openscore.events.EventConstants;
import org.openscore.events.ScoreEvent;
import org.openscore.events.ScoreEventListener;
import org.fusesource.jansi.Ansi;
import org.fusesource.jansi.AnsiConsole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.openscore.lang.entities.ScoreLangConstants.*;
import static org.openscore.lang.runtime.events.LanguageEventData.EXCEPTION;
import static org.openscore.lang.runtime.events.LanguageEventData.RESULT;
import static org.fusesource.jansi.Ansi.ansi;
/**
* @author Bonczidai Levente
* @since 11/13/2014
* @version $Id$
*/
@Service
public class ScoreServicesImpl implements ScoreServices{
public static final String SLANG_STEP_ERROR_MSG = "Slang Error : ";
public static final String SCORE_ERROR_EVENT_MSG = "Score Error Event :";
public static final String FLOW_FINISHED_WITH_FAILURE_MSG = "Flow finished with failure";
public static final String EXEC_START_PATH = "0/0";
public static final int OUTPUT_VALUE_LIMIT = 40;
@Autowired
private Slang slang;
private final static String TASK_PATH_PREFIX = "- ";
public void subscribe(ScoreEventListener eventHandler, Set<String> eventTypes) {
slang.subscribeOnEvents(eventHandler, eventTypes);
}
/**
* This method will trigger the flow in an Async matter.
* @param compilationArtifact the artifact to trigger
* @param inputs : flow inputs
* @return executionId
*/
@Override
public Long trigger(CompilationArtifact compilationArtifact, Map<String, ? extends Serializable> inputs, Map<String, ? extends Serializable> systemProperties) {
return slang.run(compilationArtifact, inputs, systemProperties);
}
/**
* This method will trigger the flow in a synchronize matter, meaning only one flow can run at a time.
* @param compilationArtifact the artifact to trigger
* @param inputs : flow inputs
* @return executionId
*/
@Override
public Long triggerSync(CompilationArtifact compilationArtifact, Map<String, ? extends Serializable> inputs, Map<String, ? extends Serializable> systemProperties){
//add start event
Set<String> handlerTypes = new HashSet<>();
handlerTypes.add(EventConstants.SCORE_FINISHED_EVENT);
handlerTypes.add(EventConstants.SCORE_ERROR_EVENT);
handlerTypes.add(EventConstants.SCORE_FAILURE_EVENT);
handlerTypes.add(SLANG_EXECUTION_EXCEPTION);
handlerTypes.add(EVENT_EXECUTION_FINISHED);
handlerTypes.add(EVENT_INPUT_END);
handlerTypes.add(EVENT_OUTPUT_END);
SyncTriggerEventListener scoreEventListener = new SyncTriggerEventListener();
slang.subscribeOnEvents(scoreEventListener, handlerTypes);
Long executionId = trigger(compilationArtifact, inputs, systemProperties);
while(!scoreEventListener.isFlowFinished()){
try {
Thread.sleep(200);
} catch (InterruptedException ignore) {}
}
slang.unSubscribeOnEvents(scoreEventListener);
return executionId;
}
private class SyncTriggerEventListener implements ScoreEventListener{
private AtomicBoolean flowFinished = new AtomicBoolean(false);
public boolean isFlowFinished() {
return flowFinished.get();
}
@Override
public synchronized void onEvent(ScoreEvent scoreEvent) throws InterruptedException {
@SuppressWarnings("unchecked") Map<String,Serializable> data = (Map<String,Serializable>)scoreEvent.getData();
switch (scoreEvent.getEventType()){
case EventConstants.SCORE_FINISHED_EVENT :
flowFinished.set(true);
break;
case EventConstants.SCORE_ERROR_EVENT :
printWithColor(Ansi.Color.RED, SCORE_ERROR_EVENT_MSG + data.get(EventConstants.SCORE_ERROR_LOG_MSG) + " , " +
data.get(EventConstants.SCORE_ERROR_MSG));
break;
case EventConstants.SCORE_FAILURE_EVENT :
printWithColor(Ansi.Color.RED,FLOW_FINISHED_WITH_FAILURE_MSG);
flowFinished.set(true);
break;
case ScoreLangConstants.SLANG_EXECUTION_EXCEPTION:
printWithColor(Ansi.Color.RED,SLANG_STEP_ERROR_MSG + data.get(EXCEPTION));
break;
case ScoreLangConstants.EVENT_INPUT_END:
String taskName = (String)data.get(LanguageEventData.levelName.TASK_NAME.name());
if(StringUtils.isNotEmpty(taskName)){
String prefix = getPrefix(data);
printWithColor(Ansi.Color.YELLOW, prefix + taskName);
}
break;
case ScoreLangConstants.EVENT_OUTPUT_END:
printOutputs(data);
break;
case EVENT_EXECUTION_FINISHED :
printFinishEvent(data);
break;
}
}
private void printOutputs(Map<String, Serializable> data) {
if(data.containsKey(LanguageEventData.OUTPUTS) && data.containsKey(LanguageEventData.PATH) && data.get(LanguageEventData.PATH).equals(EXEC_START_PATH)) {
@SuppressWarnings("unchecked") Map<String, String> outputs = (Map<String, String>) data.get(LanguageEventData.OUTPUTS);
Map<String, String> modifiableOutputs = new HashMap<>();
modifiableOutputs.putAll(outputs);
if (MapUtils.isNotEmpty(outputs)) {
for (String key : outputs.keySet()) {
String outputValue = modifiableOutputs.get(key).replace("\n", " ");
modifiableOutputs.put(key, StringUtils.abbreviate(outputValue, 0, OUTPUT_VALUE_LIMIT));
if (StringUtils.isEmpty(outputValue)) {
modifiableOutputs.put(key, "(empty)");
}
printWithColor(Ansi.Color.WHITE, "- " + key + " = " + modifiableOutputs.get(key));
}
}
}
}
private String getPrefix(Map<String, Serializable> data) {
String path = (String) data.get(LanguageEventData.PATH);
int matches = StringUtils.countMatches(path, ExecutionPath.PATH_SEPARATOR);
return StringUtils.repeat(TASK_PATH_PREFIX, matches);
}
private void printFinishEvent(Map<String, Serializable> data) {
String flowResult = (String)data.get(RESULT);
String flowName = (String)data.get(LanguageEventData.levelName.EXECUTABLE_NAME.toString());
printWithColor(Ansi.Color.CYAN,"Flow : " + flowName + " finished with result : " + flowResult);
}
private void printWithColor(Ansi.Color color, String msg){
AnsiConsole.out().print(ansi().fg(color).a(msg).newline());
AnsiConsole.out().print(ansi().fg(Ansi.Color.WHITE));
}
}
}
| - Removed replacing \n with space
- Skipping empty outputs
- Code Refactor
Signed-off-by: Lesan Tudor <[email protected]>
| score-lang-cli/src/main/java/org/openscore/lang/cli/services/ScoreServicesImpl.java | - Removed replacing \n with space - Skipping empty outputs - Code Refactor |
|
Java | apache-2.0 | bc8dcd6095d9db35360fc2c3fbdc3599399db048 | 0 | strapdata/elassandra,vroyer/elassandra,strapdata/elassandra,strapdata/elassandra,vroyer/elassandra,strapdata/elassandra,strapdata/elassandra,vroyer/elassandra | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.index.engine;
import java.nio.file.Path;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.core.internal.io.IOUtils;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.VersionType;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.mapper.ParsedDocument;
import org.elasticsearch.index.store.Store;
import org.elasticsearch.index.translog.SnapshotMatchers;
import org.elasticsearch.index.translog.Translog;
import org.elasticsearch.test.IndexSettingsModule;
import org.junit.Before;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
public class LuceneChangesSnapshotTests extends EngineTestCase {
private MapperService mapperService;
@Before
public void createMapper() throws Exception {
mapperService = createMapperService("test");
}
@Override
protected Settings indexSettings() {
return Settings.builder().put(super.indexSettings())
.put(IndexSettings.INDEX_SOFT_DELETES_SETTING.getKey(), true) // always enable soft-deletes
.build();
}
public void testBasics() throws Exception {
long fromSeqNo = randomNonNegativeLong();
long toSeqNo = randomLongBetween(fromSeqNo, Long.MAX_VALUE);
// Empty engine
try (Translog.Snapshot snapshot = engine.newChangesSnapshot("test", mapperService, fromSeqNo, toSeqNo, true)) {
IllegalStateException error = expectThrows(IllegalStateException.class, () -> drainAll(snapshot));
assertThat(error.getMessage(),
containsString("Not all operations between from_seqno [" + fromSeqNo + "] and to_seqno [" + toSeqNo + "] found"));
}
try (Translog.Snapshot snapshot = engine.newChangesSnapshot("test", mapperService, fromSeqNo, toSeqNo, false)) {
assertThat(snapshot, SnapshotMatchers.size(0));
}
int numOps = between(1, 100);
int refreshedSeqNo = -1;
for (int i = 0; i < numOps; i++) {
String id = Integer.toString(randomIntBetween(i, i + 5));
ParsedDocument doc = createParsedDoc(id, null, randomBoolean());
if (randomBoolean()) {
engine.index(indexForDoc(doc));
} else {
engine.delete(new Engine.Delete(doc.type(), doc.id(), newUid(doc.id()), primaryTerm.get()));
}
if (rarely()) {
if (randomBoolean()) {
engine.flush();
} else {
engine.refresh("test");
}
refreshedSeqNo = i;
}
}
if (refreshedSeqNo == -1) {
fromSeqNo = between(0, numOps);
toSeqNo = randomLongBetween(fromSeqNo, numOps * 2);
Engine.Searcher searcher = engine.acquireSearcher("test", Engine.SearcherScope.INTERNAL);
try (Translog.Snapshot snapshot = new LuceneChangesSnapshot(
searcher, mapperService, between(1, LuceneChangesSnapshot.DEFAULT_BATCH_SIZE), fromSeqNo, toSeqNo, false)) {
searcher = null;
assertThat(snapshot, SnapshotMatchers.size(0));
} finally {
IOUtils.close(searcher);
}
searcher = engine.acquireSearcher("test", Engine.SearcherScope.INTERNAL);
try (Translog.Snapshot snapshot = new LuceneChangesSnapshot(
searcher, mapperService, between(1, LuceneChangesSnapshot.DEFAULT_BATCH_SIZE), fromSeqNo, toSeqNo, true)) {
searcher = null;
IllegalStateException error = expectThrows(IllegalStateException.class, () -> drainAll(snapshot));
assertThat(error.getMessage(),
containsString("Not all operations between from_seqno [" + fromSeqNo + "] and to_seqno [" + toSeqNo + "] found"));
}finally {
IOUtils.close(searcher);
}
} else {
fromSeqNo = randomLongBetween(0, refreshedSeqNo);
toSeqNo = randomLongBetween(refreshedSeqNo + 1, numOps * 2);
Engine.Searcher searcher = engine.acquireSearcher("test", Engine.SearcherScope.INTERNAL);
try (Translog.Snapshot snapshot = new LuceneChangesSnapshot(
searcher, mapperService, between(1, LuceneChangesSnapshot.DEFAULT_BATCH_SIZE), fromSeqNo, toSeqNo, false)) {
searcher = null;
assertThat(snapshot, SnapshotMatchers.containsSeqNoRange(fromSeqNo, refreshedSeqNo));
} finally {
IOUtils.close(searcher);
}
searcher = engine.acquireSearcher("test", Engine.SearcherScope.INTERNAL);
try (Translog.Snapshot snapshot = new LuceneChangesSnapshot(
searcher, mapperService, between(1, LuceneChangesSnapshot.DEFAULT_BATCH_SIZE), fromSeqNo, toSeqNo, true)) {
searcher = null;
IllegalStateException error = expectThrows(IllegalStateException.class, () -> drainAll(snapshot));
assertThat(error.getMessage(),
containsString("Not all operations between from_seqno [" + fromSeqNo + "] and to_seqno [" + toSeqNo + "] found"));
}finally {
IOUtils.close(searcher);
}
toSeqNo = randomLongBetween(fromSeqNo, refreshedSeqNo);
searcher = engine.acquireSearcher("test", Engine.SearcherScope.INTERNAL);
try (Translog.Snapshot snapshot = new LuceneChangesSnapshot(
searcher, mapperService, between(1, LuceneChangesSnapshot.DEFAULT_BATCH_SIZE), fromSeqNo, toSeqNo, true)) {
searcher = null;
assertThat(snapshot, SnapshotMatchers.containsSeqNoRange(fromSeqNo, toSeqNo));
} finally {
IOUtils.close(searcher);
}
}
// Get snapshot via engine will auto refresh
fromSeqNo = randomLongBetween(0, numOps - 1);
toSeqNo = randomLongBetween(fromSeqNo, numOps - 1);
try (Translog.Snapshot snapshot = engine.newChangesSnapshot("test", mapperService, fromSeqNo, toSeqNo, randomBoolean())) {
assertThat(snapshot, SnapshotMatchers.containsSeqNoRange(fromSeqNo, toSeqNo));
}
}
public void testDedupByPrimaryTerm() throws Exception {
Map<Long, Long> latestOperations = new HashMap<>();
List<Integer> terms = Arrays.asList(between(1, 1000), between(1000, 2000));
int totalOps = 0;
for (long term : terms) {
final List<Engine.Operation> ops = generateSingleDocHistory(true,
randomFrom(VersionType.INTERNAL, VersionType.EXTERNAL, VersionType.EXTERNAL_GTE), false, term, 2, 20, "1");
primaryTerm.set(Math.max(primaryTerm.get(), term));
engine.rollTranslogGeneration();
for (Engine.Operation op : ops) {
// We need to simulate a rollback here as only ops after local checkpoint get into the engine
if (op.seqNo() <= engine.getLocalCheckpointTracker().getCheckpoint()) {
engine.getLocalCheckpointTracker().resetCheckpoint(randomLongBetween(-1, op.seqNo() - 1));
engine.rollTranslogGeneration();
}
if (op instanceof Engine.Index) {
engine.index((Engine.Index) op);
} else if (op instanceof Engine.Delete) {
engine.delete((Engine.Delete) op);
}
latestOperations.put(op.seqNo(), op.primaryTerm());
if (rarely()) {
engine.refresh("test");
}
if (rarely()) {
engine.flush();
}
totalOps++;
}
}
long maxSeqNo = engine.getLocalCheckpointTracker().getMaxSeqNo();
try (Translog.Snapshot snapshot = engine.newChangesSnapshot("test", mapperService, 0, maxSeqNo, false)) {
Translog.Operation op;
while ((op = snapshot.next()) != null) {
assertThat(op.toString(), op.primaryTerm(), equalTo(latestOperations.get(op.seqNo())));
}
assertThat(snapshot.skippedOperations(), equalTo(totalOps - latestOperations.size()));
}
}
public void testUpdateAndReadChangesConcurrently() throws Exception {
Follower[] followers = new Follower[between(1, 3)];
CountDownLatch readyLatch = new CountDownLatch(followers.length + 1);
AtomicBoolean isDone = new AtomicBoolean();
for (int i = 0; i < followers.length; i++) {
followers[i] = new Follower(engine, isDone, readyLatch, createTempDir());
followers[i].start();
}
boolean onPrimary = randomBoolean();
List<Engine.Operation> operations = new ArrayList<>();
int numOps = scaledRandomIntBetween(1, 1000);
for (int i = 0; i < numOps; i++) {
String id = Integer.toString(randomIntBetween(1, 10));
ParsedDocument doc = createParsedDoc(id, randomAlphaOfLengthBetween(1, 5), randomBoolean());
final Engine.Operation op;
if (onPrimary) {
if (randomBoolean()) {
op = new Engine.Index(newUid(doc), primaryTerm.get(), doc);
} else {
op = new Engine.Delete(doc.type(), doc.id(), newUid(doc.id()), primaryTerm.get());
}
} else {
if (randomBoolean()) {
op = replicaIndexForDoc(doc, randomNonNegativeLong(), i, randomBoolean());
} else {
op = replicaDeleteForDoc(doc.id(), randomNonNegativeLong(), i, randomNonNegativeLong());
}
}
operations.add(op);
}
readyLatch.countDown();
concurrentlyApplyOps(operations, engine);
assertThat(engine.getLocalCheckpointTracker().getCheckpoint(), equalTo(operations.size() - 1L));
isDone.set(true);
for (Follower follower : followers) {
follower.join();
}
}
class Follower extends Thread {
private final Engine leader;
private final TranslogHandler translogHandler;
private final AtomicBoolean isDone;
private final CountDownLatch readLatch;
private final Path translogPath;
Follower(Engine leader, AtomicBoolean isDone, CountDownLatch readLatch, Path translogPath) {
this.leader = leader;
this.isDone = isDone;
this.readLatch = readLatch;
this.translogHandler = new TranslogHandler(xContentRegistry(), IndexSettingsModule.newIndexSettings(shardId.getIndexName(),
engine.engineConfig.getIndexSettings().getSettings()));
this.translogPath = translogPath;
}
void pullOperations(Engine follower) throws IOException {
long leaderCheckpoint = leader.getLocalCheckpoint();
long followerCheckpoint = follower.getLocalCheckpoint();
if (followerCheckpoint < leaderCheckpoint) {
long fromSeqNo = followerCheckpoint + 1;
long batchSize = randomLongBetween(0, 100);
long toSeqNo = Math.min(fromSeqNo + batchSize, leaderCheckpoint);
try (Translog.Snapshot snapshot = leader.newChangesSnapshot("test", mapperService, fromSeqNo, toSeqNo, true)) {
translogHandler.run(follower, snapshot);
}
}
}
@Override
public void run() {
try (Store store = createStore();
InternalEngine follower = createEngine(store, translogPath)) {
readLatch.countDown();
readLatch.await();
while (isDone.get() == false ||
follower.getLocalCheckpointTracker().getCheckpoint() < leader.getLocalCheckpoint()) {
pullOperations(follower);
}
assertConsistentHistoryBetweenTranslogAndLuceneIndex(follower, mapperService);
assertThat(getDocIds(follower, true), equalTo(getDocIds(leader, true)));
} catch (Exception ex) {
throw new AssertionError(ex);
}
}
}
private List<Translog.Operation> drainAll(Translog.Snapshot snapshot) throws IOException {
List<Translog.Operation> operations = new ArrayList<>();
Translog.Operation op;
while ((op = snapshot.next()) != null) {
final Translog.Operation newOp = op;
logger.error("Reading [{}]", op);
assert operations.stream().allMatch(o -> o.seqNo() < newOp.seqNo()) : "Operations [" + operations + "], op [" + op + "]";
operations.add(newOp);
}
return operations;
}
}
| server/src/test/java/org/elasticsearch/index/engine/LuceneChangesSnapshotTests.java | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.index.engine;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.core.internal.io.IOUtils;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.VersionType;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.mapper.ParsedDocument;
import org.elasticsearch.index.store.Store;
import org.elasticsearch.index.translog.SnapshotMatchers;
import org.elasticsearch.index.translog.Translog;
import org.elasticsearch.test.IndexSettingsModule;
import org.junit.Before;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
public class LuceneChangesSnapshotTests extends EngineTestCase {
private MapperService mapperService;
@Before
public void createMapper() throws Exception {
mapperService = createMapperService("test");
}
@Override
protected Settings indexSettings() {
return Settings.builder().put(super.indexSettings())
.put(IndexSettings.INDEX_SOFT_DELETES_SETTING.getKey(), true) // always enable soft-deletes
.build();
}
public void testBasics() throws Exception {
long fromSeqNo = randomNonNegativeLong();
long toSeqNo = randomLongBetween(fromSeqNo, Long.MAX_VALUE);
// Empty engine
try (Translog.Snapshot snapshot = engine.newChangesSnapshot("test", mapperService, fromSeqNo, toSeqNo, true)) {
IllegalStateException error = expectThrows(IllegalStateException.class, () -> drainAll(snapshot));
assertThat(error.getMessage(),
containsString("Not all operations between from_seqno [" + fromSeqNo + "] and to_seqno [" + toSeqNo + "] found"));
}
try (Translog.Snapshot snapshot = engine.newChangesSnapshot("test", mapperService, fromSeqNo, toSeqNo, false)) {
assertThat(snapshot, SnapshotMatchers.size(0));
}
int numOps = between(1, 100);
int refreshedSeqNo = -1;
for (int i = 0; i < numOps; i++) {
String id = Integer.toString(randomIntBetween(i, i + 5));
ParsedDocument doc = createParsedDoc(id, null, randomBoolean());
if (randomBoolean()) {
engine.index(indexForDoc(doc));
} else {
engine.delete(new Engine.Delete(doc.type(), doc.id(), newUid(doc.id()), primaryTerm.get()));
}
if (rarely()) {
if (randomBoolean()) {
engine.flush();
} else {
engine.refresh("test");
}
refreshedSeqNo = i;
}
}
if (refreshedSeqNo == -1) {
fromSeqNo = between(0, numOps);
toSeqNo = randomLongBetween(fromSeqNo, numOps * 2);
Engine.Searcher searcher = engine.acquireSearcher("test", Engine.SearcherScope.INTERNAL);
try (Translog.Snapshot snapshot = new LuceneChangesSnapshot(
searcher, mapperService, between(1, LuceneChangesSnapshot.DEFAULT_BATCH_SIZE), fromSeqNo, toSeqNo, false)) {
searcher = null;
assertThat(snapshot, SnapshotMatchers.size(0));
} finally {
IOUtils.close(searcher);
}
searcher = engine.acquireSearcher("test", Engine.SearcherScope.INTERNAL);
try (Translog.Snapshot snapshot = new LuceneChangesSnapshot(
searcher, mapperService, between(1, LuceneChangesSnapshot.DEFAULT_BATCH_SIZE), fromSeqNo, toSeqNo, true)) {
searcher = null;
IllegalStateException error = expectThrows(IllegalStateException.class, () -> drainAll(snapshot));
assertThat(error.getMessage(),
containsString("Not all operations between from_seqno [" + fromSeqNo + "] and to_seqno [" + toSeqNo + "] found"));
}finally {
IOUtils.close(searcher);
}
} else {
fromSeqNo = randomLongBetween(0, refreshedSeqNo);
toSeqNo = randomLongBetween(refreshedSeqNo + 1, numOps * 2);
Engine.Searcher searcher = engine.acquireSearcher("test", Engine.SearcherScope.INTERNAL);
try (Translog.Snapshot snapshot = new LuceneChangesSnapshot(
searcher, mapperService, between(1, LuceneChangesSnapshot.DEFAULT_BATCH_SIZE), fromSeqNo, toSeqNo, false)) {
searcher = null;
assertThat(snapshot, SnapshotMatchers.containsSeqNoRange(fromSeqNo, refreshedSeqNo));
} finally {
IOUtils.close(searcher);
}
searcher = engine.acquireSearcher("test", Engine.SearcherScope.INTERNAL);
try (Translog.Snapshot snapshot = new LuceneChangesSnapshot(
searcher, mapperService, between(1, LuceneChangesSnapshot.DEFAULT_BATCH_SIZE), fromSeqNo, toSeqNo, true)) {
searcher = null;
IllegalStateException error = expectThrows(IllegalStateException.class, () -> drainAll(snapshot));
assertThat(error.getMessage(),
containsString("Not all operations between from_seqno [" + fromSeqNo + "] and to_seqno [" + toSeqNo + "] found"));
}finally {
IOUtils.close(searcher);
}
toSeqNo = randomLongBetween(fromSeqNo, refreshedSeqNo);
searcher = engine.acquireSearcher("test", Engine.SearcherScope.INTERNAL);
try (Translog.Snapshot snapshot = new LuceneChangesSnapshot(
searcher, mapperService, between(1, LuceneChangesSnapshot.DEFAULT_BATCH_SIZE), fromSeqNo, toSeqNo, true)) {
searcher = null;
assertThat(snapshot, SnapshotMatchers.containsSeqNoRange(fromSeqNo, toSeqNo));
} finally {
IOUtils.close(searcher);
}
}
// Get snapshot via engine will auto refresh
fromSeqNo = randomLongBetween(0, numOps - 1);
toSeqNo = randomLongBetween(fromSeqNo, numOps - 1);
try (Translog.Snapshot snapshot = engine.newChangesSnapshot("test", mapperService, fromSeqNo, toSeqNo, randomBoolean())) {
assertThat(snapshot, SnapshotMatchers.containsSeqNoRange(fromSeqNo, toSeqNo));
}
}
public void testDedupByPrimaryTerm() throws Exception {
Map<Long, Long> latestOperations = new HashMap<>();
List<Integer> terms = Arrays.asList(between(1, 1000), between(1000, 2000));
int totalOps = 0;
for (long term : terms) {
final List<Engine.Operation> ops = generateSingleDocHistory(true,
randomFrom(VersionType.INTERNAL, VersionType.EXTERNAL, VersionType.EXTERNAL_GTE), false, term, 2, 20, "1");
primaryTerm.set(Math.max(primaryTerm.get(), term));
engine.rollTranslogGeneration();
for (Engine.Operation op : ops) {
// We need to simulate a rollback here as only ops after local checkpoint get into the engine
if (op.seqNo() <= engine.getLocalCheckpointTracker().getCheckpoint()) {
engine.getLocalCheckpointTracker().resetCheckpoint(randomLongBetween(-1, op.seqNo() - 1));
engine.rollTranslogGeneration();
}
if (op instanceof Engine.Index) {
engine.index((Engine.Index) op);
} else if (op instanceof Engine.Delete) {
engine.delete((Engine.Delete) op);
}
latestOperations.put(op.seqNo(), op.primaryTerm());
if (rarely()) {
engine.refresh("test");
}
if (rarely()) {
engine.flush();
}
totalOps++;
}
}
long maxSeqNo = engine.getLocalCheckpointTracker().getMaxSeqNo();
try (Translog.Snapshot snapshot = engine.newChangesSnapshot("test", mapperService, 0, maxSeqNo, false)) {
Translog.Operation op;
while ((op = snapshot.next()) != null) {
assertThat(op.toString(), op.primaryTerm(), equalTo(latestOperations.get(op.seqNo())));
}
assertThat(snapshot.skippedOperations(), equalTo(totalOps - latestOperations.size()));
}
}
@AwaitsFix(bugUrl = "https://github.com/elastic/elasticsearch/issues/33344")
public void testUpdateAndReadChangesConcurrently() throws Exception {
Follower[] followers = new Follower[between(1, 3)];
CountDownLatch readyLatch = new CountDownLatch(followers.length + 1);
AtomicBoolean isDone = new AtomicBoolean();
for (int i = 0; i < followers.length; i++) {
followers[i] = new Follower(engine, isDone, readyLatch);
followers[i].start();
}
boolean onPrimary = randomBoolean();
List<Engine.Operation> operations = new ArrayList<>();
int numOps = scaledRandomIntBetween(1, 1000);
for (int i = 0; i < numOps; i++) {
String id = Integer.toString(randomIntBetween(1, 10));
ParsedDocument doc = createParsedDoc(id, randomAlphaOfLengthBetween(1, 5), randomBoolean());
final Engine.Operation op;
if (onPrimary) {
if (randomBoolean()) {
op = new Engine.Index(newUid(doc), primaryTerm.get(), doc);
} else {
op = new Engine.Delete(doc.type(), doc.id(), newUid(doc.id()), primaryTerm.get());
}
} else {
if (randomBoolean()) {
op = replicaIndexForDoc(doc, randomNonNegativeLong(), i, randomBoolean());
} else {
op = replicaDeleteForDoc(doc.id(), randomNonNegativeLong(), i, randomNonNegativeLong());
}
}
operations.add(op);
}
readyLatch.countDown();
concurrentlyApplyOps(operations, engine);
assertThat(engine.getLocalCheckpointTracker().getCheckpoint(), equalTo(operations.size() - 1L));
isDone.set(true);
for (Follower follower : followers) {
follower.join();
}
}
class Follower extends Thread {
private final Engine leader;
private final TranslogHandler translogHandler;
private final AtomicBoolean isDone;
private final CountDownLatch readLatch;
Follower(Engine leader, AtomicBoolean isDone, CountDownLatch readLatch) {
this.leader = leader;
this.isDone = isDone;
this.readLatch = readLatch;
this.translogHandler = new TranslogHandler(xContentRegistry(), IndexSettingsModule.newIndexSettings(shardId.getIndexName(),
engine.engineConfig.getIndexSettings().getSettings()));
}
void pullOperations(Engine follower) throws IOException {
long leaderCheckpoint = leader.getLocalCheckpoint();
long followerCheckpoint = follower.getLocalCheckpoint();
if (followerCheckpoint < leaderCheckpoint) {
long fromSeqNo = followerCheckpoint + 1;
long batchSize = randomLongBetween(0, 100);
long toSeqNo = Math.min(fromSeqNo + batchSize, leaderCheckpoint);
try (Translog.Snapshot snapshot = leader.newChangesSnapshot("test", mapperService, fromSeqNo, toSeqNo, true)) {
translogHandler.run(follower, snapshot);
}
}
}
@Override
public void run() {
try (Store store = createStore();
InternalEngine follower = createEngine(store, createTempDir())) {
readLatch.countDown();
readLatch.await();
while (isDone.get() == false ||
follower.getLocalCheckpointTracker().getCheckpoint() < leader.getLocalCheckpoint()) {
pullOperations(follower);
}
assertConsistentHistoryBetweenTranslogAndLuceneIndex(follower, mapperService);
assertThat(getDocIds(follower, true), equalTo(getDocIds(leader, true)));
} catch (Exception ex) {
throw new AssertionError(ex);
}
}
}
private List<Translog.Operation> drainAll(Translog.Snapshot snapshot) throws IOException {
List<Translog.Operation> operations = new ArrayList<>();
Translog.Operation op;
while ((op = snapshot.next()) != null) {
final Translog.Operation newOp = op;
logger.error("Reading [{}]", op);
assert operations.stream().allMatch(o -> o.seqNo() < newOp.seqNo()) : "Operations [" + operations + "], op [" + op + "]";
operations.add(newOp);
}
return operations;
}
}
| TESTS: Fix Race Condition in Temp Path Creation (#33352) (#33370)
* TESTS: Fix Race Condition in Temp Path Creation
* Calling `createTempDir` concurrently here in
the `Follower`s causes collisions at times
which lead to `createEngine` throwing because
of unexpected files in the newly created temp
dir
* Fixed by creating all temp dirs in the main test thread
* closes #33344 | server/src/test/java/org/elasticsearch/index/engine/LuceneChangesSnapshotTests.java | TESTS: Fix Race Condition in Temp Path Creation (#33352) (#33370) |
|
Java | apache-2.0 | 88cab927e13c451fa3d019e91867f3663e61c6ac | 0 | grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation | package com.navigation.reactnative;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.view.ViewGroup;
import android.view.ViewParent;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.uimanager.events.RCTEventEmitter;
import java.util.ArrayList;
import java.util.List;
public class TabBarView extends ViewPager {
private List<TabBarItemView> tabs = new ArrayList<>();
public TabBarView(Context context) {
super(context);
addOnPageChangeListener(new TabChangeListener());
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
Activity activity = ((ReactContext) getContext()).getCurrentActivity();
setAdapter(new Adapter(getFragmentManager(activity)));
for(int i = 0; i < tabs.size(); i++) {
addTab(tabs.get(i), i);
}
this.requestLayout();
post(measureAndLayout);
getTabLayout().setupWithViewPager(this);
}
private TabLayoutView getTabLayout() {
return (TabLayoutView) ((ViewGroup) getParent()).getChildAt(0);
}
private FragmentManager getFragmentManager(Activity activity) {
ViewParent parent = this;
Fragment fragment = null;
while (parent != null) {
if (parent instanceof NavigationBoundary) {
fragment = ((NavigationBoundary) parent).getFragment();
break;
}
parent = parent.getParent();
}
return fragment == null? ((FragmentActivity) activity).getSupportFragmentManager(): fragment.getChildFragmentManager();
}
private final Runnable measureAndLayout = new Runnable() {
@Override
public void run() {
measure(
MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.EXACTLY));
layout(getLeft(), getTop(), getRight(), getBottom());
}
};
@Nullable
@Override
public Adapter getAdapter() {
return (Adapter) super.getAdapter();
}
void addTab(TabBarItemView tab, int index) {
if (getAdapter() != null)
getAdapter().addTab(tab, index);
else
tabs.add(index, tab);
}
private class Adapter extends FragmentPagerAdapter {
private List<TabFragment> tabFragments = new ArrayList<>();
Adapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
void addTab(TabBarItemView tab, int index) {
tabFragments.add(index, new TabFragment(tab));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
tab.setElevation(-1 * index);
notifyDataSetChanged();
if (getTabLayout() != null)
getTabLayout().redraw();
setOffscreenPageLimit(tabFragments.size() == 1 ? 2 : 1);
}
@Override
public int getCount() {
return tabFragments.size();
}
@Override
public Fragment getItem(int position) {
return tabFragments.get(position);
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return tabFragments.get(position).tabBarItem.title;
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
post(measureAndLayout);
return super.instantiateItem(container, position);
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
}
}
private class TabChangeListener implements ViewPager.OnPageChangeListener {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
WritableMap event = Arguments.createMap();
event.putInt("tab", position);
ReactContext reactContext = (ReactContext) getContext();
reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(getId(),"onTabSelected", event);
}
@Override
public void onPageScrollStateChanged(int state) {
}
}
}
| NavigationReactNative/src/android/app/src/main/java/com/navigation/reactnative/TabBarView.java | package com.navigation.reactnative;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.view.ViewGroup;
import android.view.ViewParent;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.uimanager.events.RCTEventEmitter;
import java.util.ArrayList;
import java.util.List;
public class TabBarView extends ViewPager {
private List<TabBarItemView> tabs = new ArrayList<>();
public TabBarView(Context context) {
super(context);
addOnPageChangeListener(new TabChangeListener());
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
Activity activity = ((ReactContext) getContext()).getCurrentActivity();
setAdapter(new Adapter(getFragmentManager(activity)));
for(int i = 0; i < tabs.size(); i++) {
addTab(tabs.get(i), i);
}
this.requestLayout();
post(measureAndLayout);
getTabLayout().setupWithViewPager(this);
}
private TabLayoutView getTabLayout() {
return (TabLayoutView) ((ViewGroup) getParent()).getChildAt(0);
}
private FragmentManager getFragmentManager(Activity activity) {
ViewParent parent = this;
Fragment fragment = null;
while (parent != null) {
if (parent instanceof NavigationBoundary) {
fragment = ((NavigationBoundary) parent).getFragment();
break;
}
parent = parent.getParent();
}
return fragment == null? ((FragmentActivity) activity).getSupportFragmentManager(): fragment.getChildFragmentManager();
}
private final Runnable measureAndLayout = new Runnable() {
@Override
public void run() {
measure(
MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.EXACTLY));
layout(getLeft(), getTop(), getRight(), getBottom());
}
};
@Nullable
@Override
public Adapter getAdapter() {
return (Adapter) super.getAdapter();
}
void addTab(TabBarItemView tab, int index) {
if (getAdapter() != null)
getAdapter().addTab(tab, index);
else
tabs.add(index, tab);
}
private class Adapter extends FragmentPagerAdapter {
private List<TabFragment> tabFragments = new ArrayList<>();
Adapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
void addTab(TabBarItemView tab, int index) {
tabFragments.add(index, new TabFragment(tab));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
tab.setElevation(-1 * index);
notifyDataSetChanged();
if (getTabLayout() != null) {
getTabLayout().redraw();
}
setOffscreenPageLimit(tabFragments.size() == 1 ? 2 : 1);
}
@Override
public int getCount() {
return tabFragments.size();
}
@Override
public Fragment getItem(int position) {
return tabFragments.get(position);
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return tabFragments.get(position).tabBarItem.title;
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
post(measureAndLayout);
return super.instantiateItem(container, position);
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
}
}
private class TabChangeListener implements ViewPager.OnPageChangeListener {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
WritableMap event = Arguments.createMap();
event.putInt("tab", position);
ReactContext reactContext = (ReactContext) getContext();
reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(getId(),"onTabSelected", event);
}
@Override
public void onPageScrollStateChanged(int state) {
}
}
}
| Tweaked format
| NavigationReactNative/src/android/app/src/main/java/com/navigation/reactnative/TabBarView.java | Tweaked format |
|
Java | apache-2.0 | b00fa230c3f0a137c39f5de4c186acc1e2706481 | 0 | watson-developer-cloud/java-sdk,watson-developer-cloud/java-sdk,watson-developer-cloud/java-sdk,watson-developer-cloud/java-sdk | /*
* (C) Copyright IBM Corp. 2020.
*
* 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.ibm.watson.assistant.v2;
import com.google.gson.JsonObject;
import com.ibm.cloud.sdk.core.http.RequestBuilder;
import com.ibm.cloud.sdk.core.http.ResponseConverter;
import com.ibm.cloud.sdk.core.http.ServiceCall;
import com.ibm.cloud.sdk.core.security.Authenticator;
import com.ibm.cloud.sdk.core.security.ConfigBasedAuthenticatorFactory;
import com.ibm.cloud.sdk.core.service.BaseService;
import com.ibm.cloud.sdk.core.util.ResponseConverterUtils;
import com.ibm.watson.assistant.v2.model.CreateSessionOptions;
import com.ibm.watson.assistant.v2.model.DeleteSessionOptions;
import com.ibm.watson.assistant.v2.model.MessageOptions;
import com.ibm.watson.assistant.v2.model.MessageResponse;
import com.ibm.watson.assistant.v2.model.SessionResponse;
import com.ibm.watson.common.SdkCommon;
import java.util.Map;
import java.util.Map.Entry;
/**
* The IBM Watson™ Assistant service combines machine learning, natural language understanding, and an integrated
* dialog editor to create conversation flows between your apps and your users.
*
* The Assistant v2 API provides runtime methods your client application can use to send user input to an assistant and
* receive a response.
*
* @version v2
* @see <a href="https://cloud.ibm.com/docs/services/assistant/">Assistant</a>
*/
public class Assistant extends BaseService {
private static final String DEFAULT_SERVICE_NAME = "assistant";
private static final String DEFAULT_SERVICE_URL = "https://gateway.watsonplatform.net/assistant/api";
private String versionDate;
/**
* Constructs a new `Assistant` client using the DEFAULT_SERVICE_NAME.
*
* @param versionDate The version date (yyyy-MM-dd) of the REST API to use. Specifying this value will keep your API
* calls from failing when the service introduces breaking changes.
*/
public Assistant(String versionDate) {
this(versionDate, DEFAULT_SERVICE_NAME, ConfigBasedAuthenticatorFactory.getAuthenticator(DEFAULT_SERVICE_NAME));
}
/**
* Constructs a new `Assistant` client with the DEFAULT_SERVICE_NAME
* and the specified Authenticator.
*
* @param versionDate The version date (yyyy-MM-dd) of the REST API to use. Specifying this value will keep your API
* calls from failing when the service introduces breaking changes.
* @param authenticator the Authenticator instance to be configured for this service
*/
public Assistant(String versionDate, Authenticator authenticator) {
this(versionDate, DEFAULT_SERVICE_NAME, authenticator);
}
/**
* Constructs a new `Assistant` client with the specified serviceName.
*
* @param versionDate The version date (yyyy-MM-dd) of the REST API to use. Specifying this value will keep your API
* calls from failing when the service introduces breaking changes.
* @param serviceName The name of the service to configure.
*/
public Assistant(String versionDate, String serviceName) {
this(versionDate, serviceName, ConfigBasedAuthenticatorFactory.getAuthenticator(serviceName));
}
/**
* Constructs a new `Assistant` client with the specified Authenticator
* and serviceName.
*
* @param versionDate The version date (yyyy-MM-dd) of the REST API to use. Specifying this value will keep your API
* calls from failing when the service introduces breaking changes.
* @param serviceName The name of the service to configure.
* @param authenticator the Authenticator instance to be configured for this service
*/
public Assistant(String versionDate, String serviceName, Authenticator authenticator) {
super(serviceName, authenticator);
setServiceUrl(DEFAULT_SERVICE_URL);
com.ibm.cloud.sdk.core.util.Validator.isTrue((versionDate != null) && !versionDate.isEmpty(),
"version cannot be null.");
this.versionDate = versionDate;
this.configureService(serviceName);
}
/**
* Create a session.
*
* Create a new session. A session is used to send user input to a skill and receive responses. It also maintains the
* state of the conversation. A session persists until it is deleted, or until it times out because of inactivity.
* (For more information, see the
* [documentation](https://cloud.ibm.com/docs/services/assistant?topic=assistant-assistant-settings).
*
* @param createSessionOptions the {@link CreateSessionOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of {@link SessionResponse}
*/
public ServiceCall<SessionResponse> createSession(CreateSessionOptions createSessionOptions) {
com.ibm.cloud.sdk.core.util.Validator.notNull(createSessionOptions,
"createSessionOptions cannot be null");
String[] pathSegments = { "v2/assistants", "sessions" };
String[] pathParameters = { createSessionOptions.assistantId() };
RequestBuilder builder = RequestBuilder.post(RequestBuilder.constructHttpUrl(getServiceUrl(), pathSegments,
pathParameters));
builder.query("version", versionDate);
Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("conversation", "v2", "createSession");
for (Entry<String, String> header : sdkHeaders.entrySet()) {
builder.header(header.getKey(), header.getValue());
}
builder.header("Accept", "application/json");
ResponseConverter<SessionResponse> responseConverter = ResponseConverterUtils.getValue(
new com.google.gson.reflect.TypeToken<SessionResponse>() {
}.getType());
return createServiceCall(builder.build(), responseConverter);
}
/**
* Delete session.
*
* Deletes a session explicitly before it times out. (For more information about the session inactivity timeout, see
* the [documentation](https://cloud.ibm.com/docs/services/assistant?topic=assistant-assistant-settings)).
*
* @param deleteSessionOptions the {@link DeleteSessionOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of Void
*/
public ServiceCall<Void> deleteSession(DeleteSessionOptions deleteSessionOptions) {
com.ibm.cloud.sdk.core.util.Validator.notNull(deleteSessionOptions,
"deleteSessionOptions cannot be null");
String[] pathSegments = { "v2/assistants", "sessions" };
String[] pathParameters = { deleteSessionOptions.assistantId(), deleteSessionOptions.sessionId() };
RequestBuilder builder = RequestBuilder.delete(RequestBuilder.constructHttpUrl(getServiceUrl(), pathSegments,
pathParameters));
builder.query("version", versionDate);
Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("conversation", "v2", "deleteSession");
for (Entry<String, String> header : sdkHeaders.entrySet()) {
builder.header(header.getKey(), header.getValue());
}
builder.header("Accept", "application/json");
ResponseConverter<Void> responseConverter = ResponseConverterUtils.getVoid();
return createServiceCall(builder.build(), responseConverter);
}
/**
* Send user input to assistant.
*
* Send user input to an assistant and receive a response.
*
* There is no rate limit for this operation.
*
* @param messageOptions the {@link MessageOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of {@link MessageResponse}
*/
public ServiceCall<MessageResponse> message(MessageOptions messageOptions) {
com.ibm.cloud.sdk.core.util.Validator.notNull(messageOptions,
"messageOptions cannot be null");
String[] pathSegments = { "v2/assistants", "sessions", "message" };
String[] pathParameters = { messageOptions.assistantId(), messageOptions.sessionId() };
RequestBuilder builder = RequestBuilder.post(RequestBuilder.constructHttpUrl(getServiceUrl(), pathSegments,
pathParameters));
builder.query("version", versionDate);
Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("conversation", "v2", "message");
for (Entry<String, String> header : sdkHeaders.entrySet()) {
builder.header(header.getKey(), header.getValue());
}
builder.header("Accept", "application/json");
final JsonObject contentJson = new JsonObject();
if (messageOptions.input() != null) {
contentJson.add("input", com.ibm.cloud.sdk.core.util.GsonSingleton.getGson().toJsonTree(messageOptions.input()));
}
if (messageOptions.context() != null) {
contentJson.add("context", com.ibm.cloud.sdk.core.util.GsonSingleton.getGson().toJsonTree(messageOptions
.context()));
}
builder.bodyJson(contentJson);
ResponseConverter<MessageResponse> responseConverter = ResponseConverterUtils.getValue(
new com.google.gson.reflect.TypeToken<MessageResponse>() {
}.getType());
return createServiceCall(builder.build(), responseConverter);
}
}
| assistant/src/main/java/com/ibm/watson/assistant/v2/Assistant.java | /*
* (C) Copyright IBM Corp. 2020.
*
* 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.ibm.watson.assistant.v2;
import com.google.gson.JsonObject;
import com.ibm.cloud.sdk.core.http.RequestBuilder;
import com.ibm.cloud.sdk.core.http.ResponseConverter;
import com.ibm.cloud.sdk.core.http.ServiceCall;
import com.ibm.cloud.sdk.core.security.Authenticator;
import com.ibm.cloud.sdk.core.security.ConfigBasedAuthenticatorFactory;
import com.ibm.cloud.sdk.core.service.BaseService;
import com.ibm.cloud.sdk.core.util.ResponseConverterUtils;
import com.ibm.watson.assistant.v2.model.CreateSessionOptions;
import com.ibm.watson.assistant.v2.model.DeleteSessionOptions;
import com.ibm.watson.assistant.v2.model.MessageOptions;
import com.ibm.watson.assistant.v2.model.MessageResponse;
import com.ibm.watson.assistant.v2.model.SessionResponse;
import com.ibm.watson.common.SdkCommon;
import java.util.Map;
import java.util.Map.Entry;
/**
* The IBM Watson™ Assistant service combines machine learning, natural language understanding, and an integrated
* dialog editor to create conversation flows between your apps and your users.
*
* The Assistant v2 API provides runtime methods your client application can use to send user input to an assistant and
* receive a response.
*
* @version v2
* @see <a href="https://cloud.ibm.com/docs/services/assistant/">Assistant</a>
*/
public class Assistant extends BaseService {
private static final String DEFAULT_SERVICE_NAME = "conversation";
private static final String DEFAULT_SERVICE_URL = "https://gateway.watsonplatform.net/assistant/api";
private String versionDate;
/**
* Constructs a new `Assistant` client using the DEFAULT_SERVICE_NAME.
*
* @param versionDate The version date (yyyy-MM-dd) of the REST API to use. Specifying this value will keep your API
* calls from failing when the service introduces breaking changes.
*/
public Assistant(String versionDate) {
this(versionDate, DEFAULT_SERVICE_NAME, ConfigBasedAuthenticatorFactory.getAuthenticator(DEFAULT_SERVICE_NAME));
}
/**
* Constructs a new `Assistant` client with the DEFAULT_SERVICE_NAME
* and the specified Authenticator.
*
* @param versionDate The version date (yyyy-MM-dd) of the REST API to use. Specifying this value will keep your API
* calls from failing when the service introduces breaking changes.
* @param authenticator the Authenticator instance to be configured for this service
*/
public Assistant(String versionDate, Authenticator authenticator) {
this(versionDate, DEFAULT_SERVICE_NAME, authenticator);
}
/**
* Constructs a new `Assistant` client with the specified serviceName.
*
* @param versionDate The version date (yyyy-MM-dd) of the REST API to use. Specifying this value will keep your API
* calls from failing when the service introduces breaking changes.
* @param serviceName The name of the service to configure.
*/
public Assistant(String versionDate, String serviceName) {
this(versionDate, serviceName, ConfigBasedAuthenticatorFactory.getAuthenticator(serviceName));
}
/**
* Constructs a new `Assistant` client with the specified Authenticator
* and serviceName.
*
* @param versionDate The version date (yyyy-MM-dd) of the REST API to use. Specifying this value will keep your API
* calls from failing when the service introduces breaking changes.
* @param serviceName The name of the service to configure.
* @param authenticator the Authenticator instance to be configured for this service
*/
public Assistant(String versionDate, String serviceName, Authenticator authenticator) {
super(serviceName, authenticator);
setServiceUrl(DEFAULT_SERVICE_URL);
com.ibm.cloud.sdk.core.util.Validator.isTrue((versionDate != null) && !versionDate.isEmpty(),
"version cannot be null.");
this.versionDate = versionDate;
this.configureService(serviceName);
}
/**
* Create a session.
*
* Create a new session. A session is used to send user input to a skill and receive responses. It also maintains the
* state of the conversation. A session persists until it is deleted, or until it times out because of inactivity.
* (For more information, see the
* [documentation](https://cloud.ibm.com/docs/services/assistant?topic=assistant-assistant-settings).
*
* @param createSessionOptions the {@link CreateSessionOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of {@link SessionResponse}
*/
public ServiceCall<SessionResponse> createSession(CreateSessionOptions createSessionOptions) {
com.ibm.cloud.sdk.core.util.Validator.notNull(createSessionOptions,
"createSessionOptions cannot be null");
String[] pathSegments = { "v2/assistants", "sessions" };
String[] pathParameters = { createSessionOptions.assistantId() };
RequestBuilder builder = RequestBuilder.post(RequestBuilder.constructHttpUrl(getServiceUrl(), pathSegments,
pathParameters));
builder.query("version", versionDate);
Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("conversation", "v2", "createSession");
for (Entry<String, String> header : sdkHeaders.entrySet()) {
builder.header(header.getKey(), header.getValue());
}
builder.header("Accept", "application/json");
ResponseConverter<SessionResponse> responseConverter = ResponseConverterUtils.getValue(
new com.google.gson.reflect.TypeToken<SessionResponse>() {
}.getType());
return createServiceCall(builder.build(), responseConverter);
}
/**
* Delete session.
*
* Deletes a session explicitly before it times out. (For more information about the session inactivity timeout, see
* the [documentation](https://cloud.ibm.com/docs/services/assistant?topic=assistant-assistant-settings)).
*
* @param deleteSessionOptions the {@link DeleteSessionOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of Void
*/
public ServiceCall<Void> deleteSession(DeleteSessionOptions deleteSessionOptions) {
com.ibm.cloud.sdk.core.util.Validator.notNull(deleteSessionOptions,
"deleteSessionOptions cannot be null");
String[] pathSegments = { "v2/assistants", "sessions" };
String[] pathParameters = { deleteSessionOptions.assistantId(), deleteSessionOptions.sessionId() };
RequestBuilder builder = RequestBuilder.delete(RequestBuilder.constructHttpUrl(getServiceUrl(), pathSegments,
pathParameters));
builder.query("version", versionDate);
Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("conversation", "v2", "deleteSession");
for (Entry<String, String> header : sdkHeaders.entrySet()) {
builder.header(header.getKey(), header.getValue());
}
builder.header("Accept", "application/json");
ResponseConverter<Void> responseConverter = ResponseConverterUtils.getVoid();
return createServiceCall(builder.build(), responseConverter);
}
/**
* Send user input to assistant.
*
* Send user input to an assistant and receive a response.
*
* There is no rate limit for this operation.
*
* @param messageOptions the {@link MessageOptions} containing the options for the call
* @return a {@link ServiceCall} with a response type of {@link MessageResponse}
*/
public ServiceCall<MessageResponse> message(MessageOptions messageOptions) {
com.ibm.cloud.sdk.core.util.Validator.notNull(messageOptions,
"messageOptions cannot be null");
String[] pathSegments = { "v2/assistants", "sessions", "message" };
String[] pathParameters = { messageOptions.assistantId(), messageOptions.sessionId() };
RequestBuilder builder = RequestBuilder.post(RequestBuilder.constructHttpUrl(getServiceUrl(), pathSegments,
pathParameters));
builder.query("version", versionDate);
Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("conversation", "v2", "message");
for (Entry<String, String> header : sdkHeaders.entrySet()) {
builder.header(header.getKey(), header.getValue());
}
builder.header("Accept", "application/json");
final JsonObject contentJson = new JsonObject();
if (messageOptions.input() != null) {
contentJson.add("input", com.ibm.cloud.sdk.core.util.GsonSingleton.getGson().toJsonTree(messageOptions.input()));
}
if (messageOptions.context() != null) {
contentJson.add("context", com.ibm.cloud.sdk.core.util.GsonSingleton.getGson().toJsonTree(messageOptions
.context()));
}
builder.bodyJson(contentJson);
ResponseConverter<MessageResponse> responseConverter = ResponseConverterUtils.getValue(
new com.google.gson.reflect.TypeToken<MessageResponse>() {
}.getType());
return createServiceCall(builder.build(), responseConverter);
}
}
| chore(Assistant v2): Apply manual changes
| assistant/src/main/java/com/ibm/watson/assistant/v2/Assistant.java | chore(Assistant v2): Apply manual changes |
|
Java | apache-2.0 | 8f1cc3391cd63eb10469217bdb6377f8595b46d2 | 0 | JuniorsJava/itevents,JuniorsJava/itevents,JuniorsJava/itevents,JuniorsJava/itevents | package org.itevents.service.transactional;
import org.itevents.dao.EventDao;
import org.itevents.dao.exception.EntityNotFoundDaoException;
import org.itevents.dao.model.Event;
import org.itevents.dao.model.Filter;
import org.itevents.dao.model.User;
import org.itevents.dao.model.VisitLog;
import org.itevents.dao.model.builder.VisitLogBuilder;
import org.itevents.service.EventService;
import org.itevents.service.UserService;
import org.itevents.service.VisitLogService;
import org.itevents.service.exception.EntityNotFoundServiceException;
import org.itevents.service.exception.TimeCollisionServiceException;
import org.itevents.test_utils.BuilderUtil;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.inject.Inject;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.*;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/applicationContext.xml"})
public class MyBatisEventServiceTest {
@InjectMocks
@Inject
private EventService eventService;
@Mock
private EventDao eventDao;
@Mock
private UserService userService;
@Mock
private VisitLogService visitLogService;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void shouldFindEventById() {
int ID_1 = 1;
eventService.getEvent(ID_1);
verify(eventDao).getEvent(ID_1);
}
@Test(expected = EntityNotFoundServiceException.class)
public void shouldThrowEventNotFoundServiceException() throws Exception {
int absentId = 0;
when(eventDao.getEvent(absentId)).thenThrow(EntityNotFoundDaoException.class);
eventService.getEvent(absentId);
}
@Test
public void shouldAddEvent() throws ParseException {
Event testEvent = BuilderUtil.buildEventRuby();
eventService.addEvent(testEvent);
verify(eventDao).addEvent(testEvent);
verify(eventDao).addEventTechnology(testEvent);
}
@Test
public void shouldGetAllEvents() {
eventService.getAllEvents();
verify(eventDao).getAllEvents();
}
@Test
public void shouldFindEventsByParameter() throws Exception {
List<Event> expectedEvents = new ArrayList<>();
expectedEvents.add(BuilderUtil.buildEventJava());
Filter filter = new Filter();
when(eventDao.getFilteredEvents(filter)).thenReturn(expectedEvents);
List<Event> returnedEvents = eventService.getFilteredEvents(filter);
verify(eventDao).getFilteredEvents(filter);
assertEquals(expectedEvents, returnedEvents);
}
@Test
public void shouldNotFindEventsByParameter() throws Exception {
List<Event> expectedEvents = new ArrayList<>();
Filter filter = new Filter();
when(eventDao.getFilteredEvents(filter)).thenReturn(new ArrayList<>());
List<Event> returnedEvents = eventService.getFilteredEvents(filter);
verify(eventDao).getFilteredEvents(filter);
assertEquals(expectedEvents, returnedEvents);
}
@Test
public void shouldReturnEventsByUser() throws Exception {
User user = BuilderUtil.buildUserAnakin();
eventService.getEventsByUser(user);
verify(eventDao).getEventsByUser(user);
}
@Test
public void shouldAssignToEvent() throws Exception {
User user = BuilderUtil.buildUserAnakin();
Event event = BuilderUtil.buildEventRuby();
when(eventService.getEvent(event.getId())).thenReturn(event);
when(userService.getAuthorizedUser()).thenReturn(user);
eventService.assignAuthorizedUserToEvent(event.getId());
verify(eventDao).assignUserToEvent(user, event);
}
/* @TODO:
*https://github.com/JuniorsJava/itevents/issues/203
* Remove any(Date.class) and other matchers
*/
@Test
public void shouldUnassignUserFromEvent() throws Exception {
User user = BuilderUtil.buildUserAnakin();
Event event = BuilderUtil.buildEventJs();
String unassignReason = "test";
List events = new ArrayList<>();
events.add(event);
when(eventDao.getEvent(event.getId())).thenReturn(event);
when(eventDao.getEventsByUser(user)).thenReturn(events);
when(userService.getAuthorizedUser()).thenReturn(user);
eventService.unassignAuthorizedUserFromEvent(event.getId(), unassignReason);
verify(eventDao).unassignUserFromEvent(eq(user), eq(event), any(Date.class), eq(unassignReason));
}
@Test
public void shouldFindFutureEvent() throws Exception {
Event expectedEvent = BuilderUtil.buildEventJava();
when(eventDao.getEvent(expectedEvent.getId())).thenReturn(expectedEvent);
Event returnedEvent = eventService.getFutureEvent(expectedEvent.getId());
assertEquals(expectedEvent, returnedEvent);
}
@Test(expected = TimeCollisionServiceException.class)
public void shouldThrowTimeCollisionServiceExceptionWhenTryFindPastEventAsFutureEvent() throws Exception {
Event event = BuilderUtil.buildEventJava();
int yesterday = -1;
event.setEventDate(getDateInPast(yesterday));
when(eventDao.getEvent(event.getId())).thenReturn(event);
eventService.getFutureEvent(event.getId());
}
private Date getDateInPast(int daysCount) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, daysCount);
return calendar.getTime();
}
@Test
public void shouldReturnLinkToEventSite() throws Exception {
Event event = BuilderUtil.buildEventJava();
User userGuest = BuilderUtil.buildUserGuest();
VisitLog visitLog = VisitLogBuilder.aVisitLog().event(event).user(userGuest).build();
String expectedLink = event.getRegLink();
when(eventService.getEvent(event.getId())).thenReturn(event);
when(userService.getAuthorizedUser()).thenReturn(userGuest);
doNothing().when(visitLogService).addVisitLog(visitLog);
String returnedlLink = eventService.redirectToEventSite(event.getId());
assertEquals(expectedLink, returnedlLink);
}
} | restservice/src/test/java/org/itevents/service/transactional/MyBatisEventServiceTest.java | package org.itevents.service.transactional;
import org.itevents.dao.EventDao;
import org.itevents.dao.exception.EntityNotFoundDaoException;
import org.itevents.dao.model.Event;
import org.itevents.dao.model.Filter;
import org.itevents.dao.model.User;
import org.itevents.dao.model.VisitLog;
import org.itevents.dao.model.builder.VisitLogBuilder;
import org.itevents.service.EventService;
import org.itevents.service.UserService;
import org.itevents.service.VisitLogService;
import org.itevents.service.exception.EntityNotFoundServiceException;
import org.itevents.service.exception.TimeCollisionServiceException;
import org.itevents.test_utils.BuilderUtil;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.inject.Inject;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.*;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/applicationContext.xml"})
public class MyBatisEventServiceTest {
@InjectMocks
@Inject
private EventService eventService;
@Mock
private EventDao eventDao;
@Mock
private UserService userService;
@Mock
private VisitLogService visitLogService;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void shouldFindEventById() {
int ID_1 = 1;
eventService.getEvent(ID_1);
verify(eventDao).getEvent(ID_1);
}
@Test(expected = EntityNotFoundServiceException.class)
public void shouldThrowEventNotFoundServiceException() throws Exception {
int absentId = 0;
when(eventDao.getEvent(absentId)).thenThrow(EntityNotFoundDaoException.class);
eventService.getEvent(absentId);
}
@Test
public void shouldAddEvent() throws ParseException {
Event testEvent = BuilderUtil.buildEventRuby();
eventService.addEvent(testEvent);
verify(eventDao).addEvent(testEvent);
verify(eventDao).addEventTechnology(testEvent);
}
@Test
public void shouldGetAllEvents() {
eventService.getAllEvents();
verify(eventDao).getAllEvents();
}
@Test
public void shouldFindEventsByParameter() throws Exception {
List<Event> expectedEvents = new ArrayList<>();
expectedEvents.add(BuilderUtil.buildEventJava());
Filter filter = new Filter();
when(eventDao.getFilteredEvents(filter)).thenReturn(expectedEvents);
List<Event> returnedEvents = eventService.getFilteredEvents(filter);
verify(eventDao).getFilteredEvents(filter);
assertEquals(expectedEvents, returnedEvents);
}
@Test
public void shouldNotFindEventsByParameter() throws Exception {
List<Event> expectedEvents = new ArrayList<>();
Filter filter = new Filter();
when(eventDao.getFilteredEvents(filter)).thenReturn(new ArrayList<>());
List<Event> returnedEvents = eventService.getFilteredEvents(filter);
verify(eventDao).getFilteredEvents(filter);
assertEquals(expectedEvents, returnedEvents);
}
@Test
public void shouldReturnEventsByUser() throws Exception {
User user = BuilderUtil.buildUserAnakin();
eventService.getEventsByUser(user);
verify(eventDao).getEventsByUser(user);
}
@Test
public void shouldAssignToEvent() throws Exception {
User user = BuilderUtil.buildUserAnakin();
Event event = BuilderUtil.buildEventRuby();
when(eventService.getEvent(event.getId())).thenReturn(event);
when(userService.getAuthorizedUser()).thenReturn(user);
eventService.assignAuthorizedUserToEvent(event.getId());
verify(eventDao).assignUserToEvent(user, event);
}
/* @TODO:
*https://github.com/JuniorsJava/itevents/issues/203
* Remove any(Date.class) and other matchers
*/
@Test
public void shouldUnassignUserFromEvent() throws Exception {
User user = BuilderUtil.buildUserAnakin();
Event event = BuilderUtil.buildEventJs();
String unassignReason = "test";
List events = new ArrayList<>();
events.add(event);
when(eventService.getEvent(event.getId())).thenReturn(event);
when(userService.getAuthorizedUser()).thenReturn(user);
when(eventService.getEventsByUser(user)).thenReturn(events);
eventService.unassignAuthorizedUserFromEvent(event.getId(), unassignReason);
verify(eventDao).unassignUserFromEvent(eq(user), eq(event), any(Date.class), eq(unassignReason));
}
@Test
public void shouldFindFutureEvent() throws Exception {
Event expectedEvent = BuilderUtil.buildEventJava();
when(eventDao.getEvent(expectedEvent.getId())).thenReturn(expectedEvent);
Event returnedEvent = eventService.getFutureEvent(expectedEvent.getId());
assertEquals(expectedEvent, returnedEvent);
}
@Test(expected = TimeCollisionServiceException.class)
public void shouldThrowTimeCollisionServiceExceptionWhenTryFindPastEventAsFutureEvent() throws Exception {
Event event = BuilderUtil.buildEventJava();
int yesterday = -1;
event.setEventDate(getDateInPast(yesterday));
when(eventDao.getEvent(event.getId())).thenReturn(event);
eventService.getFutureEvent(event.getId());
}
private Date getDateInPast(int daysCount) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, daysCount);
return calendar.getTime();
}
@Test
public void shouldReturnLinkToEventSite() throws Exception {
Event event = BuilderUtil.buildEventJava();
User userGuest = BuilderUtil.buildUserGuest();
VisitLog visitLog = VisitLogBuilder.aVisitLog().event(event).user(userGuest).build();
String expectedLink = event.getRegLink();
when(eventService.getEvent(event.getId())).thenReturn(event);
when(userService.getAuthorizedUser()).thenReturn(userGuest);
doNothing().when(visitLogService).addVisitLog(visitLog);
String returnedlLink = eventService.redirectToEventSite(event.getId());
assertEquals(expectedLink, returnedlLink);
}
} | #186: MyBatisEventServiceTest.shouldUnassignUserFromEvent refactored
| restservice/src/test/java/org/itevents/service/transactional/MyBatisEventServiceTest.java | #186: MyBatisEventServiceTest.shouldUnassignUserFromEvent refactored |
|
Java | apache-2.0 | 0612eca3b049e510737e72bde7a3650285046d41 | 0 | yukuku/androidbible,yukuku/androidbible,infojulio/androidbible,infojulio/androidbible,yukuku/androidbible,yukuku/androidbible,infojulio/androidbible,infojulio/androidbible,infojulio/androidbible,infojulio/androidbible,yukuku/androidbible,infojulio/androidbible,yukuku/androidbible,infojulio/androidbible,yukuku/androidbible,yukuku/androidbible | package yuku.alkitab.base.widget;
import android.content.Context;
import android.content.res.Configuration;
import android.support.v4.view.MotionEventCompat;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.Button;
import yuku.alkitab.debug.R;
public class GotoButton extends Button {
public static final String TAG = GotoButton.class.getSimpleName();
public interface FloaterDragListener {
void onFloaterDragStart(float screenX, float screenY);
void onFloaterDragMove(float screenX, float screenY);
void onFloaterDragComplete(float screenX, float screenY);
}
int[] screenLocation = {0, 0};
boolean inFloaterDrag;
boolean inLongClicked;
int untouchableSideWidth = Integer.MIN_VALUE;
FloaterDragListener floaterDragListener;
public GotoButton(final Context context) {
super(context);
}
public GotoButton(final Context context, final AttributeSet attrs) {
super(context, attrs);
}
public GotoButton(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onConfigurationChanged(final Configuration newConfig) {
super.onConfigurationChanged(newConfig);
untouchableSideWidth = Integer.MIN_VALUE;
}
@Override
public boolean onTouchEvent(final MotionEvent event) {
final int action = MotionEventCompat.getActionMasked(event);
float x = event.getX();
float y = event.getY();
if (untouchableSideWidth == Integer.MIN_VALUE) {
untouchableSideWidth = getResources().getDimensionPixelSize(R.dimen.nav_prevnext_width) - getResources().getDimensionPixelSize(R.dimen.nav_goto_side_margin);
}
if (x >= 0 && x < untouchableSideWidth || x < getWidth() && x >= getWidth() - untouchableSideWidth) {
return false;
}
getLocationOnScreen(screenLocation);
float screenX = x + screenLocation[0];
float screenY = y + screenLocation[1];
if (action == MotionEvent.ACTION_DOWN) { // reset long-clicked status
inLongClicked = false;
}
if (!inLongClicked) { // do not continue if finger is still down but it's because long click is in progress
if (!inFloaterDrag) {
if (action == MotionEvent.ACTION_MOVE) {
if (x < 0 || y < 0 || x > getWidth() || y > getHeight()) {
cancelLongPress();
inFloaterDrag = true;
floaterDragListener.onFloaterDragStart(screenX, screenY);
}
}
}
// do not use "else"!
if (inFloaterDrag) {
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
inFloaterDrag = false;
floaterDragListener.onFloaterDragComplete(screenX, screenY);
} else {
floaterDragListener.onFloaterDragMove(screenX, screenY);
}
}
}
return super.onTouchEvent(event);
}
public void setFloaterDragListener(final FloaterDragListener floaterDragListener) {
this.floaterDragListener = floaterDragListener;
}
@Override
public boolean performLongClick() {
inLongClicked = true;
return super.performLongClick();
}
}
| Alkitab/src/main/java/yuku/alkitab/base/widget/GotoButton.java | package yuku.alkitab.base.widget;
import android.content.Context;
import android.support.v4.view.MotionEventCompat;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.Button;
public class GotoButton extends Button {
public static final String TAG = GotoButton.class.getSimpleName();
public interface FloaterDragListener {
void onFloaterDragStart(float screenX, float screenY);
void onFloaterDragMove(float screenX, float screenY);
void onFloaterDragComplete(float screenX, float screenY);
}
int[] screenLocation = {0, 0};
boolean inFloaterDrag;
boolean inLongClicked;
FloaterDragListener floaterDragListener;
public GotoButton(final Context context) {
super(context);
}
public GotoButton(final Context context, final AttributeSet attrs) {
super(context, attrs);
}
public GotoButton(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
}
@Override
public boolean onTouchEvent(final MotionEvent event) {
final int action = MotionEventCompat.getActionMasked(event);
float x = event.getX();
float y = event.getY();
getLocationOnScreen(screenLocation);
float screenX = x + screenLocation[0];
float screenY = y + screenLocation[1];
if (action == MotionEvent.ACTION_DOWN) { // reset long-clicked status
inLongClicked = false;
}
if (!inLongClicked) { // do not continue if finger is still down but it's because long click is in progress
if (!inFloaterDrag) {
if (action == MotionEvent.ACTION_MOVE) {
if (x < 0 || y < 0 || x > getWidth() || y > getHeight()) {
cancelLongPress();
inFloaterDrag = true;
floaterDragListener.onFloaterDragStart(screenX, screenY);
}
}
}
// do not use "else"!
if (inFloaterDrag) {
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
inFloaterDrag = false;
floaterDragListener.onFloaterDragComplete(screenX, screenY);
} else {
floaterDragListener.onFloaterDragMove(screenX, screenY);
}
}
}
return super.onTouchEvent(event);
}
public void setFloaterDragListener(final FloaterDragListener floaterDragListener) {
this.floaterDragListener = floaterDragListener;
}
@Override
public boolean performLongClick() {
inLongClicked = true;
return super.performLongClick();
}
}
| Fix bug where left/right verse navigation buttons were very hard to click
| Alkitab/src/main/java/yuku/alkitab/base/widget/GotoButton.java | Fix bug where left/right verse navigation buttons were very hard to click |
|
Java | apache-2.0 | 1b0607d3e4b278b6bc58596b1530e8911c875ef4 | 0 | cushon/error-prone,google/error-prone,cushon/error-prone,cushon/error-prone,cushon/error-prone,google/error-prone | /*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.inject.dagger;
import static org.junit.Assume.assumeTrue;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import dagger.Module;
import dagger.Provides;
import dagger.producers.ProducerModule;
import dagger.producers.Produces;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
/** Tests for {@link UseBinds}. */
@RunWith(Parameterized.class)
public class UseBindsTest {
@Parameters(name = "{0}")
public static Collection<Object[]> data() {
return Arrays.asList(
new Object[][] {
{Provides.class.getCanonicalName(), Module.class.getCanonicalName()},
{Produces.class.getCanonicalName(), ProducerModule.class.getCanonicalName()}
});
}
private final String bindingMethodAnnotation;
private final String moduleAnnotation;
private BugCheckerRefactoringTestHelper testHelper;
public UseBindsTest(String bindingMethodAnnotation, String moduleAnnotation) {
this.bindingMethodAnnotation = bindingMethodAnnotation;
this.moduleAnnotation = moduleAnnotation;
}
@Before
public void setUp() {
testHelper = BugCheckerRefactoringTestHelper.newInstance(new UseBinds(), getClass());
}
@Test
public void staticProvidesMethod() throws IOException {
testHelper
.addInputLines(
"in/Test.java",
"import java.security.SecureRandom;",
"import java.util.Random;",
"@" + moduleAnnotation,
"class Test {",
" @" + bindingMethodAnnotation,
" static Random provideRandom(SecureRandom impl) {",
" return impl;",
" }",
"}")
.addOutputLines(
"out/Test.java",
"import dagger.Binds;",
"import java.security.SecureRandom;",
"import java.util.Random;",
"@" + moduleAnnotation,
"abstract class Test {",
" @Binds abstract Random provideRandom(SecureRandom impl);",
"}")
.doTest();
}
@Test
public void intoSetMethod() throws IOException {
testHelper
.addInputLines(
"in/Test.java",
"import dagger.multibindings.IntoSet;",
"import java.security.SecureRandom;",
"import java.util.Random;",
"@" + moduleAnnotation,
"class Test {",
" @" + bindingMethodAnnotation,
" @IntoSet static Random provideRandom(SecureRandom impl) {",
" return impl;",
" }",
"}")
.addOutputLines(
"out/Test.java",
"import dagger.Binds;",
"import dagger.multibindings.IntoSet;",
"import java.security.SecureRandom;",
"import java.util.Random;",
"@" + moduleAnnotation,
"abstract class Test {",
" @Binds @IntoSet abstract Random provideRandom(SecureRandom impl);",
"}")
.doTest();
}
@Test
public void typeEqualsSetMethod() throws IOException {
// Don't check @Produces.type -- it has been removed
assumeTrue(!bindingMethodAnnotation.equals(Produces.class.getCanonicalName()));
testHelper
.addInputLines(
"in/Test.java",
"import static dagger.Provides.Type.SET;",
"import java.security.SecureRandom;",
"import java.util.Random;",
"@" + moduleAnnotation,
"class Test {",
" @" + bindingMethodAnnotation + "(type = " + bindingMethodAnnotation + ".Type.SET)",
" static Random provideRandom(SecureRandom impl) {",
" return impl;",
" }",
"}")
.addOutputLines(
"out/Test.java",
"import static dagger.Provides.Type.SET;",
"import dagger.Binds;",
"import dagger.multibindings.IntoSet;",
"import java.security.SecureRandom;",
"import java.util.Random;",
"@" + moduleAnnotation,
"abstract class Test {",
" @Binds @IntoSet abstract Random provideRandom(SecureRandom impl);",
"}")
.doTest();
}
@Test
public void instanceProvidesMethod() throws IOException {
testHelper
.addInputLines(
"in/Test.java",
"import java.security.SecureRandom;",
"import java.util.Random;",
"@" + moduleAnnotation,
"class Test {",
" @" + bindingMethodAnnotation,
" Random provideRandom(SecureRandom impl) {",
" return impl;",
" }",
"}")
.addOutputLines(
"out/Test.java",
"import dagger.Binds;",
"import java.security.SecureRandom;",
"import java.util.Random;",
"@" + moduleAnnotation,
"abstract class Test {",
" @Binds abstract Random provideRandom(SecureRandom impl);",
"}")
.doTest();
}
@Test
public void multipleBindsMethods() throws IOException {
testHelper
.addInputLines(
"in/Test.java",
"import java.security.SecureRandom;",
"import java.util.Random;",
"@" + moduleAnnotation,
"class Test {",
" @" + bindingMethodAnnotation,
" Random provideRandom(SecureRandom impl) {",
" return impl;",
" }",
" @" + bindingMethodAnnotation,
" Object provideRandomObject(SecureRandom impl) {",
" return impl;",
" }",
"}")
.addOutputLines(
"out/Test.java",
"import dagger.Binds;",
"import java.security.SecureRandom;",
"import java.util.Random;",
"@" + moduleAnnotation,
"abstract class Test {",
" @Binds abstract Random provideRandom(SecureRandom impl);",
" @Binds abstract Object provideRandomObject(SecureRandom impl);",
"}")
.doTest();
}
@Test
public void instanceProvidesMethodWithInstanceSibling() throws IOException {
testHelper
.addInputLines(
"in/Test.java",
"import java.security.SecureRandom;",
"import java.util.Random;",
"@" + moduleAnnotation,
"class Test {",
" @" + bindingMethodAnnotation,
" Random provideRandom(SecureRandom impl) {",
" return impl;",
" }",
" @" + bindingMethodAnnotation,
" SecureRandom provideSecureRandom() {",
" return new SecureRandom();",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void instanceProvidesMethodWithStaticSibling() throws IOException {
testHelper
.addInputLines(
"in/Test.java",
"import java.security.SecureRandom;",
"import java.util.Random;",
"@" + moduleAnnotation,
"class Test {",
" @" + bindingMethodAnnotation,
" Random provideRandom(SecureRandom impl) {",
" return impl;",
" }",
" @" + bindingMethodAnnotation,
" static SecureRandom provideRandom() {",
" return new SecureRandom();",
" }",
"}")
.addOutputLines(
"out/Test.java",
"import dagger.Binds;",
"import java.security.SecureRandom;",
"import java.util.Random;",
"@" + moduleAnnotation,
"abstract class Test {",
" @Binds abstract Random provideRandom(SecureRandom impl);",
" @" + bindingMethodAnnotation,
" static SecureRandom provideRandom() {",
" return new SecureRandom();",
" }",
"}")
.doTest();
}
@Test
public void notABindsMethod() throws IOException {
testHelper
.addInputLines(
"in/Test.java",
"import java.util.Random;",
"@" + moduleAnnotation,
"class Test {",
" @" + bindingMethodAnnotation,
" Random provideRandom() {",
" return new Random();",
" }",
"}")
.expectUnchanged()
.doTest();
}
}
| core/src/test/java/com/google/errorprone/bugpatterns/inject/dagger/UseBindsTest.java | /*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone.bugpatterns.inject.dagger;
import com.google.errorprone.BugCheckerRefactoringTestHelper;
import dagger.Module;
import dagger.Provides;
import dagger.producers.ProducerModule;
import dagger.producers.Produces;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
/** Tests for {@link UseBinds}. */
@RunWith(Parameterized.class)
public class UseBindsTest {
@Parameters(name = "{0}")
public static Collection<Object[]> data() {
return Arrays.asList(
new Object[][] {
{Provides.class.getCanonicalName(), Module.class.getCanonicalName()},
{Produces.class.getCanonicalName(), ProducerModule.class.getCanonicalName()}
});
}
private final String bindingMethodAnnotation;
private final String moduleAnnotation;
private BugCheckerRefactoringTestHelper testHelper;
public UseBindsTest(String bindingMethodAnnotation, String moduleAnnotation) {
this.bindingMethodAnnotation = bindingMethodAnnotation;
this.moduleAnnotation = moduleAnnotation;
}
@Before
public void setUp() {
testHelper = BugCheckerRefactoringTestHelper.newInstance(new UseBinds(), getClass());
}
@Test
public void staticProvidesMethod() throws IOException {
testHelper
.addInputLines(
"in/Test.java",
"import java.security.SecureRandom;",
"import java.util.Random;",
"@" + moduleAnnotation,
"class Test {",
" @" + bindingMethodAnnotation,
" static Random provideRandom(SecureRandom impl) {",
" return impl;",
" }",
"}")
.addOutputLines(
"out/Test.java",
"import dagger.Binds;",
"import java.security.SecureRandom;",
"import java.util.Random;",
"@" + moduleAnnotation,
"abstract class Test {",
" @Binds abstract Random provideRandom(SecureRandom impl);",
"}")
.doTest();
}
@Test
public void intoSetMethod() throws IOException {
testHelper
.addInputLines(
"in/Test.java",
"import dagger.multibindings.IntoSet;",
"import java.security.SecureRandom;",
"import java.util.Random;",
"@" + moduleAnnotation,
"class Test {",
" @" + bindingMethodAnnotation,
" @IntoSet static Random provideRandom(SecureRandom impl) {",
" return impl;",
" }",
"}")
.addOutputLines(
"out/Test.java",
"import dagger.Binds;",
"import dagger.multibindings.IntoSet;",
"import java.security.SecureRandom;",
"import java.util.Random;",
"@" + moduleAnnotation,
"abstract class Test {",
" @Binds @IntoSet abstract Random provideRandom(SecureRandom impl);",
"}")
.doTest();
}
@Test
public void typeEqualsSetMethod() throws IOException {
testHelper
.addInputLines(
"in/Test.java",
"import static dagger.Provides.Type.SET;",
"import java.security.SecureRandom;",
"import java.util.Random;",
"@" + moduleAnnotation,
"class Test {",
" @" + bindingMethodAnnotation + "(type = " + bindingMethodAnnotation + ".Type.SET)",
" static Random provideRandom(SecureRandom impl) {",
" return impl;",
" }",
"}")
.addOutputLines(
"out/Test.java",
"import static dagger.Provides.Type.SET;",
"import dagger.Binds;",
"import dagger.multibindings.IntoSet;",
"import java.security.SecureRandom;",
"import java.util.Random;",
"@" + moduleAnnotation,
"abstract class Test {",
" @Binds @IntoSet abstract Random provideRandom(SecureRandom impl);",
"}")
.doTest();
}
@Test
public void instanceProvidesMethod() throws IOException {
testHelper
.addInputLines(
"in/Test.java",
"import java.security.SecureRandom;",
"import java.util.Random;",
"@" + moduleAnnotation,
"class Test {",
" @" + bindingMethodAnnotation,
" Random provideRandom(SecureRandom impl) {",
" return impl;",
" }",
"}")
.addOutputLines(
"out/Test.java",
"import dagger.Binds;",
"import java.security.SecureRandom;",
"import java.util.Random;",
"@" + moduleAnnotation,
"abstract class Test {",
" @Binds abstract Random provideRandom(SecureRandom impl);",
"}")
.doTest();
}
@Test
public void multipleBindsMethods() throws IOException {
testHelper
.addInputLines(
"in/Test.java",
"import java.security.SecureRandom;",
"import java.util.Random;",
"@" + moduleAnnotation,
"class Test {",
" @" + bindingMethodAnnotation,
" Random provideRandom(SecureRandom impl) {",
" return impl;",
" }",
" @" + bindingMethodAnnotation,
" Object provideRandomObject(SecureRandom impl) {",
" return impl;",
" }",
"}")
.addOutputLines(
"out/Test.java",
"import dagger.Binds;",
"import java.security.SecureRandom;",
"import java.util.Random;",
"@" + moduleAnnotation,
"abstract class Test {",
" @Binds abstract Random provideRandom(SecureRandom impl);",
" @Binds abstract Object provideRandomObject(SecureRandom impl);",
"}")
.doTest();
}
@Test
public void instanceProvidesMethodWithInstanceSibling() throws IOException {
testHelper
.addInputLines(
"in/Test.java",
"import java.security.SecureRandom;",
"import java.util.Random;",
"@" + moduleAnnotation,
"class Test {",
" @" + bindingMethodAnnotation,
" Random provideRandom(SecureRandom impl) {",
" return impl;",
" }",
" @" + bindingMethodAnnotation,
" SecureRandom provideSecureRandom() {",
" return new SecureRandom();",
" }",
"}")
.expectUnchanged()
.doTest();
}
@Test
public void instanceProvidesMethodWithStaticSibling() throws IOException {
testHelper
.addInputLines(
"in/Test.java",
"import java.security.SecureRandom;",
"import java.util.Random;",
"@" + moduleAnnotation,
"class Test {",
" @" + bindingMethodAnnotation,
" Random provideRandom(SecureRandom impl) {",
" return impl;",
" }",
" @" + bindingMethodAnnotation,
" static SecureRandom provideRandom() {",
" return new SecureRandom();",
" }",
"}")
.addOutputLines(
"out/Test.java",
"import dagger.Binds;",
"import java.security.SecureRandom;",
"import java.util.Random;",
"@" + moduleAnnotation,
"abstract class Test {",
" @Binds abstract Random provideRandom(SecureRandom impl);",
" @" + bindingMethodAnnotation,
" static SecureRandom provideRandom() {",
" return new SecureRandom();",
" }",
"}")
.doTest();
}
@Test
public void notABindsMethod() throws IOException {
testHelper
.addInputLines(
"in/Test.java",
"import java.util.Random;",
"@" + moduleAnnotation,
"class Test {",
" @" + bindingMethodAnnotation,
" Random provideRandom() {",
" return new Random();",
" }",
"}")
.expectUnchanged()
.doTest();
}
}
| Fix the UseBindsTest to no longer test for @Produces.type -- it has been removed.
MOE_MIGRATED_REVID=143606226
| core/src/test/java/com/google/errorprone/bugpatterns/inject/dagger/UseBindsTest.java | Fix the UseBindsTest to no longer test for @Produces.type -- it has been removed. |
|
Java | apache-2.0 | ad581bedc004e942be77bab68d36fcd43a1edb99 | 0 | r4-keisuke/guava,baratali/guava,xasx/guava,Ranjodh-Singh/ranjodh87-guavalib,KengoTODA/guava-libraries,fengshao0907/guava,jsnchen/guava,kingland/guava,0359xiaodong/guava,npvincent/guava,lgscofield/guava,okaywit/guava-libraries,yigubigu/guava,mgalushka/guava,Overruler/guava-libraries,dnrajugade/guava-libraries,ignaciotcrespo/guava,abel-von/guava,kgislsompo/guava-libraries,manolama/guava,aditya-chaturvedi/guava,rcpoison/guava,monokurobo/guava,eidehua/guava,VikingDen/guava,yf0994/guava-libraries,Ranjodh-Singh/ranjodh87-guavalib,1yvT0s/guava,DavesMan/guava,BollyCheng/guava,weihungliu/guava,disc99/guava,xasx/guava,aiyanbo/guava,HarveyTvT/guava,KengoTODA/guava,okaywit/guava-libraries,disc99/guava,dpursehouse/guava,Akshay77/guava,0359xiaodong/guava,yanyongshan/guava,dubu/guava-libraries,zcwease/guava-libraries,1yvT0s/guava,KengoTODA/guava,GitHub4Lgfei/guava,XiWenRen/guava,jayhetee/guava,anigeorge/guava,HarveyTvT/guava,elijah513/guava,mgedigian/guava-bloom-filter,dmi3aleks/guava,Ariloum/guava,levenhdu/guava,leogong/guava,jayhetee/guava,Haus1/guava-libraries,mway08/guava,renchunxiao/guava,licheng-xd/guava,kingland/guava,rob3ns/guava,scr/guava,sunbeansoft/guava,baratali/guava,fengshao0907/guava-libraries,njucslqq/guava,mohanaraosv/guava,google/guava,cogitate/guava-libraries,jedyang/guava,huangsihuan/guava,EdwardLee03/guava,clcron/guava-libraries,sensui/guava-libraries,ningg/guava,RoliMG/guava,tobecrazy/guava,yuan232007/guava,janus-project/guava.janusproject.io,montycheese/guava,cklsoft/guava,abel-von/guava,jamesbrowder/guava-libraries,mway08/guava,dushmis/guava,5A68656E67/guava,berndhopp/guava,leesir/guava,mohanaraosv/guava,lisb/guava,qingsong-xu/guava,codershamo/guava,yf0994/guava-libraries,m3n78am/guava,mbarbero/guava-libraries,sebadiaz/guava,jankill/guava,leogong/guava,sander120786/guava-libraries,google/guava,allalizaki/guava-libraries,paplorinc/guava,kgislsompo/guava-libraries,taoguan/guava,rcpoison/guava,liyazhou/guava,monokurobo/guava,anigeorge/guava,tunzao/guava,tli2/guava,dnrajugade/guava-libraries,rgoldberg/guava,flowbywind/guava,SyllaJay/guava,binhvu7/guava,mengdiwang/guava-libraries,kucci/guava-libraries,dubu/guava-libraries,Haus1/guava-libraries,npvincent/guava,easyfmxu/guava,Yijtx/guava,Yijtx/guava,hannespernpeintner/guava,weihungliu/guava,lijunhuayc/guava,dpursehouse/guava,tli2/guava,tailorlala/guava-libraries,typetools/guava,danielnorberg/guava-libraries,lisb/guava,rgoldberg/guava,gvikei/guava-libraries,taoguan/guava,gmaes/guava,m3n78am/guava,Balzanka/guava-libraries,eidehua/guava,thinker-fang/guava,xueyin87/guava-libraries,yuan232007/guava,janus-project/guava.janusproject.io,njucslqq/guava,thinker-fang/guava,kaoudis/guava,nulakasatish/guava-libraries,mosoft521/guava,SyllaJay/guava,pwz3n0/guava,GabrielNicolasAvellaneda/guava,witekcc/guava,Balzanka/guava-libraries,DaveAKing/guava-libraries,gvikei/guava-libraries,typetools/guava,SaintBacchus/guava,montycheese/guava,yigubigu/guava,chen870647924/guava-libraries,pwz3n0/guava,BollyCheng/guava,aditya-chaturvedi/guava,cgdecker/guava,Ariloum/guava,RoliMG/guava,Kevin2030/guava,tailorlala/guava-libraries,google/guava,allenprogram/guava,lgscofield/guava,mkodekar/guava-libraries,cklsoft/guava,maidh91/guava-libraries,jackyglony/guava,gmaes/guava,GitHub4Lgfei/guava,jiteshmohan/guava,renchunxiao/guava,jiteshmohan/guava,mgalushka/guava,10045125/guava,ChengLong/guava,5A68656E67/guava,kaoudis/guava,scr/guava,berndhopp/guava,marstianna/guava,mengdiwang/guava-libraries,tunzao/guava,yangxu998/guava-libraries,cogitate/guava-libraries,jedyang/guava,lijunhuayc/guava,flowbywind/guava,seanli310/guava,AnselQiao/guava,Xaerxess/guava,Xaerxess/guava,mosoft521/guava,sensui/guava-libraries,EdwardLee03/guava,juneJuly/guava,licheng-xd/guava,juneJuly/guava,kucci/guava-libraries,uschindler/guava,yanyongshan/guava,qingsong-xu/guava,norru/guava,manolama/guava,mbarbero/guava-libraries,sunbeansoft/guava,sander120786/guava-libraries,ningg/guava,codershamo/guava,Kevin2030/guava,VikingDen/guava,levenhdu/guava,AnselQiao/guava,hannespernpeintner/guava,marstianna/guava,paddx01/guava-src,DavesMan/guava,allalizaki/guava-libraries,sebadiaz/guava,SaintBacchus/guava,tobecrazy/guava,ben-manes/guava,XiWenRen/guava,GabrielNicolasAvellaneda/guava,aiyanbo/guava,DucQuang1/guava,rob3ns/guava,jakubmalek/guava,chen870647924/guava-libraries,ceosilvajr/guava,huangsihuan/guava,DaveAKing/guava-libraries,xueyin87/guava-libraries,paplorinc/guava,jackyglony/guava,Overruler/guava-libraries,sarvex/guava,ignaciotcrespo/guava,zcwease/guava-libraries,liyazhou/guava,yangxu998/guava-libraries,KengoTODA/guava-libraries,maidh91/guava-libraries,fengshao0907/guava,elijah513/guava,mosoft521/guava,jakubmalek/guava,nulakasatish/guava-libraries,jsnchen/guava,witekcc/guava,Akshay77/guava,allenprogram/guava,jamesbrowder/guava-libraries,easyfmxu/guava,norru/guava,jankill/guava,r4-keisuke/guava,fengshao0907/guava-libraries,paddx01/guava-src,ChengLong/guava,mkodekar/guava-libraries,dushmis/guava,leesir/guava,DucQuang1/guava,seanli310/guava,clcron/guava-libraries | /*
* Copyright (C) 2007 The Guava 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 com.google.common.util.concurrent;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RejectedExecutionException;
/**
* A {@link Future} that accepts completion listeners. Each listener has an
* associated executor, and it is invoked using this executor once the future's
* computation is {@linkplain Future#isDone() complete}. If the computation has
* already completed when the listener is added, the listener will execute
* immediately.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/ListenableFutureExplained">
* {@code ListenableFuture}</a>.
*
* <h3>Purpose</h3>
*
* Most commonly, {@code ListenableFuture} is used as an input to another
* derived {@code Future}, as in {@link Futures#allAsList(Iterable)
* Futures.allAsList}. Many such methods are impossible to implement efficiently
* without listener support.
*
* <p>It is possible to call {@link #addListener addListener} directly, but this
* is uncommon because the {@code Runnable} interface does not provide direct
* access to the {@code Future} result. (Users who want such access may prefer
* {@link Futures#addCallback Futures.addCallback}.) Still, direct {@code
* addListener} calls are occasionally useful:<pre> {@code
* final String name = ...;
* inFlight.add(name);
* ListenableFuture<Result> future = service.query(name);
* future.addListener(new Runnable() {
* public void run() {
* processedCount.incrementAndGet();
* inFlight.remove(name);
* lastProcessed.set(name);
* logger.info("Done with {0}", name);
* }
* }, executor);}</pre>
*
* <h3>How to get an instance</h3>
*
* Developers are encouraged to return {@code ListenableFuture} from their
* methods so that users can take advantages of the utilities built atop the
* class. The way that they will create {@code ListenableFuture} instances
* depends on how they currently create {@code Future} instances:
* <ul>
* <li>If they are returned from an {@code ExecutorService}, convert that
* service to a {@link ListeningExecutorService}, usually by calling {@link
* MoreExecutors#listeningDecorator(ExecutorService)
* MoreExecutors.listeningDecorator}. (Custom executors may find it more
* convenient to use {@link ListenableFutureTask} directly.)
* <li>If they are manually filled in by a call to {@link FutureTask#set} or a
* similar method, create a {@link SettableFuture} instead. (Users with more
* complex needs may prefer {@link AbstractFuture}.)
* </ul>
*
* Occasionally, an API will return a plain {@code Future} and it will be
* impossible to change the return type. For this case, we provide a more
* expensive workaround in {@code JdkFutureAdapters}. However, when possible, it
* is more efficient and reliable to create a {@code ListenableFuture} directly.
*
* @author Sven Mawson
* @author Nishant Thakkar
* @since 1.0
*/
public interface ListenableFuture<V> extends Future<V> {
/**
* Registers a listener to be {@linkplain Executor#execute(Runnable) run} on
* the given executor. The listener will run when the {@code Future}'s
* computation is {@linkplain Future#isDone() complete} or, if the computation
* is already complete, immediately.
*
* <p>There is no guaranteed ordering of execution of listeners, but any
* listener added through this method is guaranteed to be called once the
* computation is complete.
*
* <p>Exceptions thrown by a listener will be propagated up to the executor.
* Any exception thrown during {@code Executor.execute} (e.g., a {@code
* RejectedExecutionException} or an exception thrown by {@linkplain
* MoreExecutors#sameThreadExecutor inline execution}) will be caught and
* logged.
*
* <p>Note: For fast, lightweight listeners that would be safe to execute in
* any thread, consider {@link MoreExecutors#sameThreadExecutor}. For heavier
* listeners, {@code sameThreadExecutor()} carries some caveats. For
* example, the listener may run on an unpredictable or undesirable thread:
*
* <ul>
* <li>If the input {@code Future} is done at the time {@code addListener} is
* called, {@code addListener} will execute the listener inline.
* <li>If the input {@code Future} is not yet done, {@code addListener} will
* schedule the listener to be run by the thread that completes the input
* {@code Future}, which may be an internal system thread such as an RPC
* network thread.
* </ul>
*
* Also note that, regardless of which thread executes the
* {@code sameThreadExecutor()} listener, all other registered but unexecuted
* listeners are prevented from running during its execution, even if those
* listeners are to run in other executors.
*
* <p>This is the most general listener interface. For common operations
* performed using listeners, see {@link
* com.google.common.util.concurrent.Futures}. For a simplified but general
* listener interface, see {@link
* com.google.common.util.concurrent.Futures#addCallback addCallback()}.
*
* @param listener the listener to run when the computation is complete
* @param executor the executor to run the listener in
* @throws NullPointerException if the executor or listener was null
* @throws RejectedExecutionException if we tried to execute the listener
* immediately but the executor rejected it.
*/
void addListener(Runnable listener, Executor executor);
}
| guava/src/com/google/common/util/concurrent/ListenableFuture.java | /*
* Copyright (C) 2007 The Guava 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 com.google.common.util.concurrent;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RejectedExecutionException;
/**
* A {@link Future} that accepts completion listeners. Each listener has an
* associated executor, and it is invoked using this executor once the future's
* computation is {@linkplain Future#isDone() complete}. If the computation has
* already completed when the listener is added, the listener will execute
* immediately.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/ListenableFutureExplained">
* {@code ListenableFuture}</a>.
*
* <h3>Purpose</h3>
*
* Most commonly, {@code ListenableFuture} is used as an input to another
* derived {@code Future}, as in {@link Futures#allAsList(Iterable)
* Futures.allAsList}. Many such methods are impossible to implement efficiently
* without listener support.
*
* <p>It is possible to call {@link #addListener addListener} directly, but this
* is uncommon because the {@code Runnable} interface does not provide direct
* access to the {@code Future} result. (Users who want such access may prefer
* {@link Futures#addCallback Futures.addCallback}.) Still, direct {@code
* addListener} calls are occasionally useful:<pre> {@code
* final String name = ...;
* inFlight.add(name);
* ListenableFuture<Result> future = service.query(name);
* future.addListener(new Runnable() {
* public void run() {
* processedCount.incrementAndGet();
* inFlight.remove(name);
* lastProcessed.set(name);
* logger.info("Done with {0}", name);
* }
* }, executor);}</pre>
*
* <h3>How to get an instance</h3>
*
* Developers are encouraged to return {@code ListenableFuture} from their
* methods so that users can take advantages of the utilities built atop the
* class. The way that they will create {@code ListenableFuture} instances
* depends on how they currently create {@code Future} instances:
* <ul>
* <li>If they are returned from an {@code ExecutorService}, convert that
* service to a {@link ListeningExecutorService}, usually by calling {@link
* MoreExecutors#listeningDecorator(ExecutorService)
* MoreExecutors.listeningDecorator}. (Custom executors may find it more
* convenient to use {@link ListenableFutureTask} directly.)
* <li>If they are manually filled in by a call to {@link FutureTask#set} or a
* similar method, create a {@link SettableFuture} instead. (Users with more
* complex needs may prefer {@link AbstractFuture}.)
* </ul>
*
* Occasionally, an API will return a plain {@code Future} and it will be
* impossible to change the return type. For this case, we provide a more
* expensive workaround in {@code JdkFutureAdapters}. However, when possible, it
* is more efficient and reliable to create a {@code ListenableFuture} directly.
*
* @author Sven Mawson
* @author Nishant Thakkar
* @since 1.0
*/
public interface ListenableFuture<V> extends Future<V> {
/**
* Registers a listener to be {@linkplain Executor#execute(Runnable) run} on
* the given executor. The listener will run when the {@code Future}'s
* computation is {@linkplain Future#isDone() complete} or, if the computation
* is already complete, immediately.
*
* <p>There is no guaranteed ordering of execution of listeners, but any
* listener added through this method is guaranteed to be called once the
* computation is complete.
*
* <p>Exceptions thrown by a listener will be propagated up to the executor.
* Any exception thrown during {@code Executor.execute} (e.g., a {@code
* RejectedExecutionException} or an exception thrown by {@linkplain
* MoreExecutors#sameThreadExecutor inline execution}) will be caught and
* logged.
*
* <p>Note: For fast, lightweight listeners that would be safe to execute in
* any thread, consider {@link MoreExecutors#sameThreadExecutor}. For heavier
* listeners, {@code sameThreadExecutor()} carries some caveats. For
* example, the listener may run on an unpredictable or undesirable thread:
*
* <ul>
* <li>If the input {@code Future} is done at the time {@code addListener} is
* called, {@code addListener} will execute the listener inline.
* <li>If the input {@code Future} is not yet done, {@code addListener} will
* schedule the listener to be run by the thread that completes the input
* {@code Future}, which may be an internal system thread such as an RPC
* network thread.
* </ul>
*
* Also note that, regardless of which thread executes the listener, all
* other registered but unexecuted listeners are prevented from running
* during its execution, even if those listeners are to run in other
* executors.
*
* <p>This is the most general listener interface. For common operations
* performed using listeners, see {@link
* com.google.common.util.concurrent.Futures}. For a simplified but general
* listener interface, see {@link
* com.google.common.util.concurrent.Futures#addCallback addCallback()}.
*
* @param listener the listener to run when the computation is complete
* @param executor the executor to run the listener in
* @throws NullPointerException if the executor or listener was null
* @throws RejectedExecutionException if we tried to execute the listener
* immediately but the executor rejected it.
*/
void addListener(Runnable listener, Executor executor);
}
| Clarify statement in addListener documentation.
-------------
Created by MOE: http://code.google.com/p/moe-java
MOE_MIGRATED_REVID=47862236
| guava/src/com/google/common/util/concurrent/ListenableFuture.java | Clarify statement in addListener documentation. ------------- Created by MOE: http://code.google.com/p/moe-java MOE_MIGRATED_REVID=47862236 |
|
Java | apache-2.0 | 5db2eee7f1c2c9448fc677b13b0654c2f4b827d6 | 0 | ontop/ontop,ontop/ontop,ontop/ontop,ontop/ontop,ontop/ontop | package it.unibz.inf.ontop.si;
import com.google.common.collect.ImmutableMap;
import it.unibz.inf.ontop.exception.DuplicateMappingException;
import it.unibz.inf.ontop.injection.MappingFactory;
import it.unibz.inf.ontop.injection.OntopMappingConfiguration;
import it.unibz.inf.ontop.injection.QuestConfiguration;
import it.unibz.inf.ontop.io.PrefixManager;
import it.unibz.inf.ontop.model.OBDAModel;
import it.unibz.inf.ontop.model.impl.OBDAModelImpl;
import it.unibz.inf.ontop.ontology.Assertion;
import it.unibz.inf.ontop.ontology.ImmutableOntologyVocabulary;
import it.unibz.inf.ontop.ontology.Ontology;
import it.unibz.inf.ontop.owlapi.OWLAPIABoxIterator;
import it.unibz.inf.ontop.owlapi.OWLAPITranslatorUtility;
import it.unibz.inf.ontop.owlrefplatform.core.abox.QuestMaterializer;
import it.unibz.inf.ontop.owlrefplatform.core.abox.RDBMSSIRepositoryManager;
import it.unibz.inf.ontop.owlrefplatform.core.dagjgrapht.TBoxReasoner;
import it.unibz.inf.ontop.owlrefplatform.core.dagjgrapht.TBoxReasonerImpl;
import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import org.semanticweb.owlapi.model.OWLOntologyManager;
import org.semanticweb.owlapi.model.parameters.Imports;
import org.semanticweb.owlapi.model.parameters.OntologyCopy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
/**
* TODO: find a better name
*/
public class OntopSemanticIndexLoaderImpl implements OntopSemanticIndexLoader {
private static final Logger log = LoggerFactory.getLogger(OntopSemanticIndexLoaderImpl.class);
private static final String DEFAULT_USER = "sa";
private static final String DEFAULT_PASSWORD = "";
private static final boolean OPTIMIZE_EQUIVALENCES = true;;
private final QuestConfiguration configuration;
private final Connection connection;
private static class RepositoryInit {
final RDBMSSIRepositoryManager dataRepository;
final Set<OWLOntology> ontologyClosure;
final String jdbcUrl;
final ImmutableOntologyVocabulary vocabulary;
final Connection localConnection;
private RepositoryInit(RDBMSSIRepositoryManager dataRepository, Set<OWLOntology> ontologyClosure, String jdbcUrl,
ImmutableOntologyVocabulary vocabulary, Connection localConnection) {
this.dataRepository = dataRepository;
this.ontologyClosure = ontologyClosure;
this.jdbcUrl = jdbcUrl;
this.vocabulary = vocabulary;
this.localConnection = localConnection;
}
}
private OntopSemanticIndexLoaderImpl(QuestConfiguration configuration, Connection connection) {
this.configuration = configuration;
this.connection = connection;
}
@Override
public QuestConfiguration getConfiguration() {
return configuration;
}
@Override
public void close() {
try {
if (connection != null && (!connection.isClosed())) {
connection.close();
}
} catch (SQLException e) {
log.error("Error while closing the DB: " + e.getMessage());
}
}
public static OntopSemanticIndexLoader loadOntologyIndividuals(String owlFile, Properties properties)
throws SemanticIndexException {
try {
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
OWLOntology ontology = manager.loadOntologyFromOntologyDocument(new File(owlFile));
return loadOntologyIndividuals(ontology, properties);
} catch (OWLOntologyCreationException e) {
throw new SemanticIndexException(e.getMessage());
}
}
public static OntopSemanticIndexLoader loadOntologyIndividuals(OWLOntology owlOntology, Properties properties)
throws SemanticIndexException {
RepositoryInit init = createRepository(owlOntology);
try {
/*
Loads the data
*/
OWLAPIABoxIterator aBoxIter = new OWLAPIABoxIterator(init.ontologyClosure, init.vocabulary);
int count = init.dataRepository.insertData(init.localConnection, aBoxIter, 5000, 500);
log.debug("Inserted {} triples from the ontology.", count);
/*
Creates the configuration and the loader object
*/
QuestConfiguration configuration = createConfiguration(init.dataRepository, owlOntology, init.jdbcUrl, properties);
return new OntopSemanticIndexLoaderImpl(configuration, init.localConnection);
} catch (SQLException e) {
throw new SemanticIndexException(e.getMessage());
}
}
/**
* TODO: do want to use a different ontology for the materialization and the output OBDA system?
*/
public static OntopSemanticIndexLoader loadVirtualAbox(QuestConfiguration obdaConfiguration, Properties properties)
throws SemanticIndexException {
try {
OWLOntology inputOntology = obdaConfiguration.loadInputOntology()
.orElseThrow(() -> new IllegalArgumentException("The configuration must provide an ontology"));
RepositoryInit init = createRepository(inputOntology);
QuestMaterializer materializer = new QuestMaterializer(obdaConfiguration, true);
Iterator<Assertion> assertionIterator = materializer.getAssertionIterator();
int count = init.dataRepository.insertData(init.localConnection, assertionIterator, 5000, 500);
materializer.disconnect();
log.debug("Inserted {} triples from the mappings.", count);
/*
Creates the configuration and the loader object
*/
QuestConfiguration configuration = createConfiguration(init.dataRepository, inputOntology, init.jdbcUrl, properties);
return new OntopSemanticIndexLoaderImpl(configuration, init.localConnection);
} catch (Exception e) {
throw new SemanticIndexException(e.getMessage());
}
}
private static RepositoryInit createRepository(OWLOntology owlOntology) throws SemanticIndexException {
Set<OWLOntology> ontologyClosure = owlOntology.getOWLOntologyManager().getImportsClosure(owlOntology);
Ontology ontology = OWLAPITranslatorUtility.mergeTranslateOntologies(ontologyClosure);
ImmutableOntologyVocabulary vocabulary = ontology.getVocabulary();
final TBoxReasoner reformulationReasoner = TBoxReasonerImpl.create(ontology, OPTIMIZE_EQUIVALENCES);
RDBMSSIRepositoryManager dataRepository = new RDBMSSIRepositoryManager(reformulationReasoner, vocabulary);
log.warn("Semantic index mode initializing: \nString operation over URI are not supported in this mode ");
// we work in memory (with H2), the database is clean and
// Quest will insert new Abox assertions into the database.
dataRepository.generateMetadata();
String jdbcUrl = buildNewJdbcUrl();
try {
Connection localConnection = DriverManager.getConnection(jdbcUrl, DEFAULT_USER, DEFAULT_PASSWORD);
// Creating the ABox repository
dataRepository.createDBSchemaAndInsertMetadata(localConnection);
return new RepositoryInit(dataRepository, ontologyClosure, jdbcUrl, vocabulary, localConnection);
} catch (SQLException e) {
throw new SemanticIndexException(e.getMessage());
}
}
private static QuestConfiguration createConfiguration(RDBMSSIRepositoryManager dataRepository, OWLOntology owlOntology,
String jdbcUrl, Properties properties) throws SemanticIndexException {
OBDAModel ppMapping = createPPMapping(dataRepository);
/**
* Tbox: ontology without the ABox axioms (are in the DB now).
*/
OWLOntologyManager newManager = OWLManager.createOWLOntologyManager();
OWLOntology tbox;
try {
tbox = newManager.copyOntology(owlOntology, OntologyCopy.SHALLOW);
} catch (OWLOntologyCreationException e) {
throw new SemanticIndexException(e.getMessage());
}
newManager.removeAxioms(tbox, tbox.getABoxAxioms(Imports.EXCLUDED));
return QuestConfiguration.defaultBuilder()
.obdaModel(ppMapping)
.ontology(tbox)
.properties(properties)
.jdbcUrl(jdbcUrl)
.jdbcUser(DEFAULT_USER)
.jdbcPassword(DEFAULT_PASSWORD)
.iriDictionary(dataRepository.getUriMap())
.build();
}
private static OBDAModel createPPMapping(RDBMSSIRepositoryManager dataRepository) {
OntopMappingConfiguration defaultConfiguration = OntopMappingConfiguration.defaultBuilder()
.build();
MappingFactory mappingFactory = defaultConfiguration.getInjector().getInstance(MappingFactory.class);
PrefixManager prefixManager = mappingFactory.create(ImmutableMap.of());
try {
return new OBDAModelImpl(dataRepository.getMappings(),
mappingFactory.create(prefixManager));
} catch (DuplicateMappingException e) {
throw new IllegalStateException(e.getMessage());
}
}
private static String buildNewJdbcUrl() {
return "jdbc:h2:mem:questrepository:" + System.currentTimeMillis() + ";LOG=0;CACHE_SIZE=65536;LOCK_MODE=0;UNDO_LOG=0";
}
}
| ontop-semantic-index/src/main/java/it/unibz/inf/ontop/si/OntopSemanticIndexLoaderImpl.java | package it.unibz.inf.ontop.si;
import com.google.common.collect.ImmutableMap;
import it.unibz.inf.ontop.exception.DuplicateMappingException;
import it.unibz.inf.ontop.injection.MappingFactory;
import it.unibz.inf.ontop.injection.OntopMappingConfiguration;
import it.unibz.inf.ontop.injection.QuestConfiguration;
import it.unibz.inf.ontop.io.PrefixManager;
import it.unibz.inf.ontop.model.OBDAModel;
import it.unibz.inf.ontop.model.impl.OBDAModelImpl;
import it.unibz.inf.ontop.ontology.ImmutableOntologyVocabulary;
import it.unibz.inf.ontop.ontology.Ontology;
import it.unibz.inf.ontop.owlapi.OWLAPIABoxIterator;
import it.unibz.inf.ontop.owlapi.OWLAPITranslatorUtility;
import it.unibz.inf.ontop.owlrefplatform.core.abox.RDBMSSIRepositoryManager;
import it.unibz.inf.ontop.owlrefplatform.core.dagjgrapht.TBoxReasoner;
import it.unibz.inf.ontop.owlrefplatform.core.dagjgrapht.TBoxReasonerImpl;
import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import org.semanticweb.owlapi.model.OWLOntologyManager;
import org.semanticweb.owlapi.model.parameters.Imports;
import org.semanticweb.owlapi.model.parameters.OntologyCopy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import java.util.Set;
/**
* TODO: find a better name
*/
public class OntopSemanticIndexLoaderImpl implements OntopSemanticIndexLoader {
private static final Logger log = LoggerFactory.getLogger(OntopSemanticIndexLoaderImpl.class);
private static final String DEFAULT_USER = "sa";
private static final String DEFAULT_PASSWORD = "";
private static final boolean OPTIMIZE_EQUIVALENCES = true;;
private final QuestConfiguration configuration;
private final Connection connection;
private OntopSemanticIndexLoaderImpl(QuestConfiguration configuration, Connection connection) {
this.configuration = configuration;
this.connection = connection;
}
@Override
public QuestConfiguration getConfiguration() {
return configuration;
}
@Override
public void close() {
try {
if (connection != null && (!connection.isClosed())) {
connection.close();
}
} catch (SQLException e) {
log.error("Error while closing the DB: " + e.getMessage());
}
}
public static OntopSemanticIndexLoader loadOntologyIndividuals(String owlFile, Properties properties)
throws SemanticIndexException {
try {
OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
OWLOntology ontology = manager.loadOntologyFromOntologyDocument(new File(owlFile));
return loadOntologyIndividuals(ontology, properties);
} catch (OWLOntologyCreationException e) {
throw new SemanticIndexException(e.getMessage());
}
}
/**
* TODO: find a better name
*/
public static OntopSemanticIndexLoader loadOntologyIndividuals(OWLOntology owlOntology, Properties properties)
throws SemanticIndexException {
Set<OWLOntology> ontologyClosure = owlOntology.getOWLOntologyManager().getImportsClosure(owlOntology);
Ontology ontology = OWLAPITranslatorUtility.mergeTranslateOntologies(ontologyClosure);
ImmutableOntologyVocabulary vocabulary = ontology.getVocabulary();
final TBoxReasoner reformulationReasoner = TBoxReasonerImpl.create(ontology, OPTIMIZE_EQUIVALENCES);
RDBMSSIRepositoryManager dataRepository = new RDBMSSIRepositoryManager(reformulationReasoner, vocabulary);
log.warn("Semantic index mode initializing: \nString operation over URI are not supported in this mode ");
// we work in memory (with H2), the database is clean and
// Quest will insert new Abox assertions into the database.
dataRepository.generateMetadata();
String jdbcUrl = buildNewJdbcUrl();
try {
Connection localConnection = DriverManager.getConnection(jdbcUrl, DEFAULT_USER, DEFAULT_PASSWORD);
// Creating the ABox repository
dataRepository.createDBSchemaAndInsertMetadata(localConnection);
OWLAPIABoxIterator aBoxIter = new OWLAPIABoxIterator(ontologyClosure, vocabulary);
int count = dataRepository.insertData(localConnection, aBoxIter, 5000, 500);
log.debug("Inserted {} triples from the ontology.", count);
QuestConfiguration configuration = createConfiguration(dataRepository, owlOntology, jdbcUrl, properties);
return new OntopSemanticIndexLoaderImpl(configuration, localConnection);
} catch (SQLException e) {
throw new SemanticIndexException(e.getMessage());
}
}
private static QuestConfiguration createConfiguration(RDBMSSIRepositoryManager dataRepository, OWLOntology owlOntology,
String jdbcUrl, Properties properties) throws SemanticIndexException {
OBDAModel ppMapping = createPPMapping(dataRepository);
/**
* Tbox: ontology without the ABox axioms (are in the DB now).
*/
OWLOntologyManager newManager = OWLManager.createOWLOntologyManager();
OWLOntology tbox;
try {
tbox = newManager.copyOntology(owlOntology, OntologyCopy.SHALLOW);
} catch (OWLOntologyCreationException e) {
throw new SemanticIndexException(e.getMessage());
}
newManager.removeAxioms(tbox, tbox.getABoxAxioms(Imports.EXCLUDED));
return QuestConfiguration.defaultBuilder()
.obdaModel(ppMapping)
.ontology(tbox)
.properties(properties)
.jdbcUrl(jdbcUrl)
.jdbcUser(DEFAULT_USER)
.jdbcPassword(DEFAULT_PASSWORD)
.iriDictionary(dataRepository.getUriMap())
.build();
}
private static OBDAModel createPPMapping(RDBMSSIRepositoryManager dataRepository) {
OntopMappingConfiguration defaultConfiguration = OntopMappingConfiguration.defaultBuilder()
.build();
MappingFactory mappingFactory = defaultConfiguration.getInjector().getInstance(MappingFactory.class);
PrefixManager prefixManager = mappingFactory.create(ImmutableMap.of());
try {
return new OBDAModelImpl(dataRepository.getMappings(),
mappingFactory.create(prefixManager));
} catch (DuplicateMappingException e) {
throw new IllegalStateException(e.getMessage());
}
}
private static String buildNewJdbcUrl() {
return "jdbc:h2:mem:questrepository:" + System.currentTimeMillis() + ";LOG=0;CACHE_SIZE=65536;LOCK_MODE=0;UNDO_LOG=0";
}
public static OntopSemanticIndexLoader loadVirtualAbox(QuestConfiguration obdaConfiguration, Properties properties)
throws SemanticIndexException {
throw new RuntimeException("TODO: implement loadVirtualAbox");
}
}
| OntopSemanticIndexLoaderImpl.loadVirtualAbox() implemented.
| ontop-semantic-index/src/main/java/it/unibz/inf/ontop/si/OntopSemanticIndexLoaderImpl.java | OntopSemanticIndexLoaderImpl.loadVirtualAbox() implemented. |
|
Java | apache-2.0 | 057bdf7eb33aebb38ac7eb20de87a3488663e4fd | 0 | atlasapi/atlas-deer,atlasapi/atlas-deer | package org.atlasapi.content;
import static com.google.common.base.Preconditions.checkNotNull;
import java.io.IOException;
import java.util.Optional;
import org.atlasapi.channel.ChannelGroupResolver;
import org.atlasapi.criteria.AttributeQuerySet;
import org.atlasapi.entity.Id;
import org.atlasapi.media.entity.Publisher;
import org.atlasapi.util.ElasticsearchIndexCreator;
import org.atlasapi.util.EsQueryBuilder;
import org.atlasapi.util.FiltersBuilder;
import org.atlasapi.util.FutureSettingActionListener;
import org.atlasapi.util.SecondaryIndex;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.BoolFilterBuilder;
import org.elasticsearch.index.query.FilterBuilder;
import org.elasticsearch.index.query.FilterBuilders;
import org.elasticsearch.index.query.FilteredQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.collect.FluentIterable;
import com.google.common.util.concurrent.AbstractIdleService;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import com.metabroadcast.common.query.Selection;
public class EsUnequivalentContentIndex extends AbstractIdleService implements ContentIndex {
private static final Function<SearchHit, Id> HIT_TO_CANONICAL_ID = hit -> {
if (hit == null || hit.field(EsContent.CANONICAL_ID) == null) {
return null;
}
Long id = hit.field(EsContent.CANONICAL_ID).<Number>value().longValue();
return Id.valueOf(id);
};
public static final Function<SearchHit, Id> SEARCH_HIT_ID_FUNCTION = hit ->
Id.valueOf(hit.field(EsContent.ID).<Number>value().longValue());
public static final Function<SearchHit, Id> HIT_TO_ID = SEARCH_HIT_ID_FUNCTION;
private final Logger log = LoggerFactory.getLogger(EsUnequivalentContentIndex.class);
private static final int DEFAULT_LIMIT = 50;
private final Client esClient;
private final String index;
private final ChannelGroupResolver channelGroupResolver;
private final EsQueryBuilder queryBuilderFactory = new EsQueryBuilder();
private final SecondaryIndex equivIdIndex;
private final EsUnequivalentContentIndexer indexer;
public EsUnequivalentContentIndex(
Client esClient,
String indexName,
ContentResolver resolver,
ChannelGroupResolver channelGroupResolver,
SecondaryIndex equivIdIndex,
Integer requestTimeout
) {
this.esClient = checkNotNull(esClient);
this.index = checkNotNull(indexName);
this.channelGroupResolver = checkNotNull(channelGroupResolver);
this.equivIdIndex = checkNotNull(equivIdIndex);
EsContentTranslator translator = new EsContentTranslator(
indexName,
esClient,
equivIdIndex,
requestTimeout.longValue(),
resolver
);
this.indexer = new EsUnequivalentContentIndexer(
esClient,
resolver,
indexName,
requestTimeout,
channelGroupResolver,
equivIdIndex,
translator
);
}
@Override
protected void startUp() throws IOException {
if (ElasticsearchIndexCreator.createContentIndex(esClient, index)) {
ElasticsearchIndexCreator.putTypeMapping(esClient, index);
}
log.info("Staring ElasticsearchUnequivalentContentIndex");
}
@Override
protected void shutDown() throws Exception {
log.info("Shutting down ElasticsearchUnequivalentContentIndex");
}
@Override
public void index(Content content) throws IndexException {
indexer.index(content);
}
@Override
public ListenableFuture<IndexQueryResult> query(AttributeQuerySet query,
Iterable<Publisher> publishers, Selection selection, Optional<IndexQueryParams> queryParams) {
SettableFuture<SearchResponse> response = SettableFuture.create();
QueryBuilder queryBuilder = this.queryBuilderFactory.buildQuery(query);
/* matchAllFilter as a bool filter with less than 1 clause is invalid */
BoolFilterBuilder filterBuilder = FilterBuilders.boolFilter()
.must(FilterBuilders.matchAllFilter());
SearchRequestBuilder reqBuilder = esClient
.prepareSearch(index)
.setTypes(EsContent.CHILD_ITEM, EsContent.TOP_LEVEL_CONTAINER, EsContent.TOP_LEVEL_ITEM)
.addField(EsContent.CANONICAL_ID)
.addField(EsContent.ID)
.setPostFilter(FiltersBuilder.buildForPublishers(EsContent.SOURCE, publishers))
.setFrom(selection.getOffset())
.setSize(Objects.firstNonNull(selection.getLimit(), DEFAULT_LIMIT));
if (queryParams.isPresent()) {
addOrdering(queryParams, reqBuilder);
queryBuilder = addFuzzyQuery(queryParams, queryBuilder, reqBuilder);
addBrandId(queryParams, filterBuilder);
addSeriesId(queryParams, filterBuilder);
addTopicFilter(queryParams, filterBuilder);
addActionableFilter(queryParams, filterBuilder);
}
reqBuilder.addSort(EsContent.ID, SortOrder.ASC);
FilteredQueryBuilder finalQuery = QueryBuilders.filteredQuery(queryBuilder, filterBuilder);
reqBuilder.setQuery(finalQuery);
log.debug(reqBuilder.internalBuilder().toString());
reqBuilder.execute(FutureSettingActionListener.setting(response));
/* TODO
* if selection.offset + selection.limit < totalHits
* then we have more: return for use with response.
*/
return Futures.transform(response, (SearchResponse input) -> {
return new IndexQueryResult(
FluentIterable.from(input.getHits()).transform(HIT_TO_ID),
FluentIterable.from(input.getHits()).transform(HIT_TO_CANONICAL_ID),
input.getHits().getTotalHits()
);
});
}
private void addOrdering(Optional<IndexQueryParams> queryParams,
SearchRequestBuilder reqBuilder) {
if (queryParams.get().getOrdering().isPresent()) {
addSortOrder(queryParams.get().getOrdering(), reqBuilder);
}
}
private QueryBuilder addFuzzyQuery(Optional<IndexQueryParams> queryParams,
QueryBuilder queryBuilder, SearchRequestBuilder reqBuilder) {
if (queryParams.get().getFuzzyQueryParams().isPresent()) {
queryBuilder = addTitleQuery(queryParams, queryBuilder);
if (queryParams.isPresent() && queryParams.get().getBroadcastWeighting().isPresent()) {
queryBuilder = BroadcastQueryBuilder.build(
queryBuilder,
queryParams.get().getBroadcastWeighting().get()
);
} else {
queryBuilder = BroadcastQueryBuilder.build(queryBuilder, 5f);
}
reqBuilder.addSort(SortBuilders.scoreSort().order(SortOrder.DESC));
}
return queryBuilder;
}
private void addBrandId(Optional<IndexQueryParams> queryParams,
BoolFilterBuilder filterBuilder) {
if (queryParams.get().getBrandId().isPresent()) {
filterBuilder.must(
FiltersBuilder.getBrandIdFilter(
queryParams.get().getBrandId().get(),
equivIdIndex
)
);
}
}
private void addSeriesId(Optional<IndexQueryParams> queryParams,
BoolFilterBuilder filterBuilder) {
if (queryParams.get().getSeriesId().isPresent()) {
filterBuilder.must(
FiltersBuilder.getSeriesIdFilter(
queryParams.get().getSeriesId().get(), equivIdIndex
)
);
}
}
private void addTopicFilter(Optional<IndexQueryParams> queryParams,
BoolFilterBuilder filterBuilder) {
if (queryParams.get().getTopicFilterIds().isPresent()) {
filterBuilder.must(
FiltersBuilder.buildTopicIdFilter(queryParams.get().getTopicFilterIds().get())
);
}
}
private void addActionableFilter(Optional<IndexQueryParams> queryParams,
BoolFilterBuilder filterBuilder) {
if (queryParams.get().getActionableFilterParams().isPresent()) {
Optional<Id> maybeRegionId = queryParams.get().getRegionId();
FilterBuilder actionableFilter = FiltersBuilder.buildActionableFilter(
queryParams.get().getActionableFilterParams().get(),
maybeRegionId,
channelGroupResolver
);
filterBuilder.must(actionableFilter);
}
}
private void addSortOrder(Optional<QueryOrdering> ordering, SearchRequestBuilder reqBuilder) {
QueryOrdering order = ordering.get();
if ("relevance".equalsIgnoreCase(order.getPath())) {
reqBuilder.addSort(SortBuilders.scoreSort().order(SortOrder.DESC));
} else {
reqBuilder.addSort(
SortBuilders
.fieldSort(translateOrderField(order.getPath()))
.order(order.isAscending() ? SortOrder.ASC : SortOrder.DESC)
);
}
}
private String translateOrderField(String orderField) {
if ("title".equalsIgnoreCase(orderField)) {
return "flattenedTitle";
}
return orderField;
}
private QueryBuilder addTitleQuery(Optional<IndexQueryParams> queryParams, QueryBuilder queryBuilder) {
FuzzyQueryParams searchParams = queryParams.get().getFuzzyQueryParams().get();
queryBuilder = QueryBuilders.boolQuery()
.must(queryBuilder)
.must(TitleQueryBuilder.build(searchParams.getSearchTerm(), searchParams.getBoost().orElse(5F)));
return queryBuilder;
}
} | atlas-elasticsearch/src/main/java/org/atlasapi/content/EsUnequivalentContentIndex.java | package org.atlasapi.content;
import static com.google.common.base.Preconditions.checkNotNull;
import java.io.IOException;
import java.util.Optional;
import org.atlasapi.channel.ChannelGroupResolver;
import org.atlasapi.criteria.AttributeQuerySet;
import org.atlasapi.entity.Id;
import org.atlasapi.media.entity.Publisher;
import org.atlasapi.util.ElasticsearchIndexCreator;
import org.atlasapi.util.EsQueryBuilder;
import org.atlasapi.util.FiltersBuilder;
import org.atlasapi.util.FutureSettingActionListener;
import org.atlasapi.util.SecondaryIndex;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.BoolFilterBuilder;
import org.elasticsearch.index.query.FilterBuilder;
import org.elasticsearch.index.query.FilterBuilders;
import org.elasticsearch.index.query.FilteredQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.collect.FluentIterable;
import com.google.common.util.concurrent.AbstractIdleService;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import com.metabroadcast.common.query.Selection;
public class EsUnequivalentContentIndex extends AbstractIdleService implements ContentIndex {
private static final Function<SearchHit, Id> HIT_TO_CANONICAL_ID = hit -> {
if (hit == null || hit.field(EsContent.CANONICAL_ID) == null) {
return null;
}
Long id = hit.field(EsContent.CANONICAL_ID).<Number>value().longValue();
return Id.valueOf(id);
};
public static final Function<SearchHit, Id> SEARCH_HIT_ID_FUNCTION = hit ->
Id.valueOf(hit.field(EsContent.ID).<Number>value().longValue());
public static final Function<SearchHit, Id> HIT_TO_ID = SEARCH_HIT_ID_FUNCTION;
private final Logger log = LoggerFactory.getLogger(EsUnequivalentContentIndex.class);
private static final int DEFAULT_LIMIT = 50;
private final Client esClient;
private final String index;
private final ChannelGroupResolver channelGroupResolver;
private final EsQueryBuilder queryBuilderFactory = new EsQueryBuilder();
private final SecondaryIndex equivIdIndex;
private final EsUnequivalentContentIndexer indexer;
public EsUnequivalentContentIndex(
Client esClient,
String indexName,
ContentResolver resolver,
ChannelGroupResolver channelGroupResolver,
SecondaryIndex equivIdIndex,
Integer requestTimeout
) {
this.esClient = checkNotNull(esClient);
this.index = checkNotNull(indexName);
this.channelGroupResolver = checkNotNull(channelGroupResolver);
this.equivIdIndex = checkNotNull(equivIdIndex);
EsContentTranslator translator = new EsContentTranslator(
indexName,
esClient,
equivIdIndex,
requestTimeout.longValue(),
resolver
);
this.indexer = new EsUnequivalentContentIndexer(
esClient,
resolver,
indexName,
requestTimeout,
channelGroupResolver,
equivIdIndex,
translator
);
}
@Override
protected void startUp() throws IOException {
if (ElasticsearchIndexCreator.createContentIndex(esClient, index)) {
ElasticsearchIndexCreator.putTypeMapping(esClient, index);
}
log.info("Staring ElasticsearchUnequivalentContentIndex");
}
@Override
protected void shutDown() throws Exception {
log.info("Shutting down ElasticsearchUnequivalentContentIndex");
}
@Override
public void index(Content content) throws IndexException {
indexer.index(content);
}
@Override
public ListenableFuture<IndexQueryResult> query(AttributeQuerySet query,
Iterable<Publisher> publishers, Selection selection, Optional<IndexQueryParams> queryParams) {
SettableFuture<SearchResponse> response = SettableFuture.create();
QueryBuilder queryBuilder = this.queryBuilderFactory.buildQuery(query);
/* matchAllFilter as a bool filter with less than 1 clause is invalid */
BoolFilterBuilder filterBuilder = FilterBuilders.boolFilter()
.must(FilterBuilders.matchAllFilter());
SearchRequestBuilder reqBuilder = esClient
.prepareSearch(index)
.setTypes(EsContent.CHILD_ITEM, EsContent.TOP_LEVEL_CONTAINER, EsContent.TOP_LEVEL_ITEM)
.addField(EsContent.CANONICAL_ID)
.addField(EsContent.ID)
.setPostFilter(FiltersBuilder.buildForPublishers(EsContent.SOURCE, publishers))
.setFrom(selection.getOffset())
.setSize(Objects.firstNonNull(selection.getLimit(), DEFAULT_LIMIT));
if (queryParams.isPresent()) {
if (queryParams.get().getOrdering().isPresent()) {
addSortOrder(queryParams, reqBuilder);
}
if (queryParams.get().getFuzzyQueryParams().isPresent()) {
queryBuilder = addTitleQuery(queryParams, queryBuilder);
if (queryParams.isPresent() && queryParams.get().getBroadcastWeighting().isPresent()) {
queryBuilder = BroadcastQueryBuilder.build(
queryBuilder,
queryParams.get().getBroadcastWeighting().get()
);
} else {
queryBuilder = BroadcastQueryBuilder.build(queryBuilder, 5f);
}
reqBuilder.addSort(SortBuilders.scoreSort().order(SortOrder.DESC));
}
if (queryParams.get().getBrandId().isPresent()) {
filterBuilder.must(
FiltersBuilder.getBrandIdFilter(
queryParams.get().getBrandId().get(),
equivIdIndex
)
);
}
if (queryParams.get().getSeriesId().isPresent()) {
filterBuilder.must(
FiltersBuilder.getSeriesIdFilter(
queryParams.get().getSeriesId().get(), equivIdIndex
)
);
}
if (queryParams.get().getTopicFilterIds().isPresent()) {
filterBuilder.must(
FiltersBuilder.buildTopicIdFilter(queryParams.get().getTopicFilterIds().get())
);
}
if (queryParams.get().getActionableFilterParams().isPresent()) {
Optional<Id> maybeRegionId = queryParams.get().getRegionId();
FilterBuilder actionableFilter = FiltersBuilder.buildActionableFilter(
queryParams.get().getActionableFilterParams().get(), maybeRegionId, channelGroupResolver
);
filterBuilder.must(actionableFilter);
}
}
reqBuilder.addSort(EsContent.ID, SortOrder.ASC);
FilteredQueryBuilder finalQuery = QueryBuilders.filteredQuery(queryBuilder, filterBuilder);
reqBuilder.setQuery(finalQuery);
log.debug(reqBuilder.internalBuilder().toString());
reqBuilder.execute(FutureSettingActionListener.setting(response));
/* TODO
* if selection.offset + selection.limit < totalHits
* then we have more: return for use with response.
*/
return Futures.transform(response, (SearchResponse input) -> {
return new IndexQueryResult(
FluentIterable.from(input.getHits()).transform(HIT_TO_ID),
FluentIterable.from(input.getHits()).transform(HIT_TO_CANONICAL_ID),
input.getHits().getTotalHits()
);
});
}
private void addSortOrder(Optional<IndexQueryParams> queryParams, SearchRequestBuilder reqBuilder) {
QueryOrdering order = queryParams.get().getOrdering().get();
if ("relevance".equalsIgnoreCase(order.getPath())) {
reqBuilder.addSort(SortBuilders.scoreSort().order(SortOrder.DESC));
} else {
reqBuilder.addSort(
SortBuilders
.fieldSort(translateOrderField(order.getPath()))
.order(order.isAscending() ? SortOrder.ASC : SortOrder.DESC)
);
}
}
private String translateOrderField(String orderField) {
if ("title".equalsIgnoreCase(orderField)) {
return "flattenedTitle";
}
return orderField;
}
private QueryBuilder addTitleQuery(Optional<IndexQueryParams> queryParams, QueryBuilder queryBuilder) {
FuzzyQueryParams searchParams = queryParams.get().getFuzzyQueryParams().get();
queryBuilder = QueryBuilders.boolQuery()
.must(queryBuilder)
.must(TitleQueryBuilder.build(searchParams.getSearchTerm(), searchParams.getBoost().orElse(5F)));
return queryBuilder;
}
} | Extracted logic into separate methods for readability
| atlas-elasticsearch/src/main/java/org/atlasapi/content/EsUnequivalentContentIndex.java | Extracted logic into separate methods for readability |
|
Java | apache-2.0 | a4114f43d63e5ed6589a4c7dca156ccf4fcb906f | 0 | factoryfx/factoryfx,factoryfx/factoryfx,factoryfx/factoryfx,factoryfx/factoryfx | package de.factoryfx.javafx.editor.attribute;
import java.math.BigDecimal;
import java.net.URI;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.function.Function;
import de.factoryfx.data.Data;
import de.factoryfx.data.attribute.Attribute;
import de.factoryfx.data.attribute.AttributeMetadata;
import de.factoryfx.data.attribute.ReferenceAttribute;
import de.factoryfx.data.attribute.ReferenceListAttribute;
import de.factoryfx.data.attribute.types.BigDecimalAttribute;
import de.factoryfx.data.attribute.types.DoubleAttribute;
import de.factoryfx.data.attribute.types.IntegerAttribute;
import de.factoryfx.data.attribute.types.LongAttribute;
import de.factoryfx.data.attribute.types.StringAttribute;
import de.factoryfx.data.attribute.types.TableAttribute;
import de.factoryfx.data.attribute.types.URIAttribute;
import de.factoryfx.javafx.editor.attribute.visualisation.BigDecimalAttributeVisualisation;
import de.factoryfx.javafx.editor.attribute.visualisation.BooleanAttributeVisualisation;
import de.factoryfx.javafx.editor.attribute.visualisation.ColorAttributeVisualisation;
import de.factoryfx.javafx.editor.attribute.visualisation.DoubleAttributeVisualisation;
import de.factoryfx.javafx.editor.attribute.visualisation.EnumAttributeVisualisation;
import de.factoryfx.javafx.editor.attribute.visualisation.IntegerAttributeVisualisation;
import de.factoryfx.javafx.editor.attribute.visualisation.ListAttributeVisualisation;
import de.factoryfx.javafx.editor.attribute.visualisation.LocalDateAttributeVisualisation;
import de.factoryfx.javafx.editor.attribute.visualisation.LocaleAttributeVisualisation;
import de.factoryfx.javafx.editor.attribute.visualisation.LongAttributeVisualisation;
import de.factoryfx.javafx.editor.attribute.visualisation.ReferenceAttributeVisualisation;
import de.factoryfx.javafx.editor.attribute.visualisation.ReferenceListAttributeVisualisation;
import de.factoryfx.javafx.editor.attribute.visualisation.StringAttributeVisualisation;
import de.factoryfx.javafx.editor.attribute.visualisation.TableAttributeVisualisation;
import de.factoryfx.javafx.editor.attribute.visualisation.URIAttributeVisualisation;
import de.factoryfx.javafx.editor.data.DataEditor;
import de.factoryfx.javafx.util.UniformDesign;
import javafx.collections.ObservableList;
import javafx.scene.paint.Color;
public class AttributeEditorFactory {
private final UniformDesign uniformDesign;
private final Data root;
public AttributeEditorFactory(UniformDesign uniformDesign, Data root) {
this.uniformDesign = uniformDesign;
this.root = root;
}
List<Function<Attribute<?>,Optional<AttributeEditor<?>>>> editorAssociations=new ArrayList<>();
public void addEditorAssociation(Function<Attribute<?>,Optional<AttributeEditor<?>>> editorAssociation){
editorAssociations.add(editorAssociation);
}
public Optional<AttributeEditor<?>> getAttributeEditor(Attribute<?> attribute, DataEditor dataEditor){
for (Function<Attribute<?>,Optional<AttributeEditor<?>>> editorAssociation: editorAssociations) {
Optional<AttributeEditor<?>> attributeEditor = editorAssociation.apply(attribute);
if (attributeEditor.isPresent()) {
return attributeEditor;
}
}
Optional<AttributeEditor<?>> enumAttribute = getAttributeEditorSimpleType(attribute);
if (enumAttribute.isPresent()) return enumAttribute;
Optional<AttributeEditor<?>> detailAttribute = getAttributeEditorList(attribute, dataEditor);
if (detailAttribute.isPresent()) return detailAttribute;
Optional<AttributeEditor<?>> referenceAttribute = getAttributeEditorReference(attribute, dataEditor);
if (referenceAttribute.isPresent()) return referenceAttribute;
return Optional.empty();
}
@SuppressWarnings("unchecked")
private Optional<AttributeEditor<?>> getAttributeEditorReference(Attribute<?> attribute, DataEditor dataEditor) {
if (attribute.getAttributeType().dataType == null)
return Optional.empty();
if (Data.class==attribute.getAttributeType().dataType){
ReferenceAttribute<?> referenceAttribute = (ReferenceAttribute<?>) attribute;
return Optional.of(new AttributeEditor<>((Attribute<Data>)attribute,new ReferenceAttributeVisualisation(uniformDesign,dataEditor,()->referenceAttribute.addNewFactory(root),()->(List<Data>)referenceAttribute.possibleValues(root))));
}
if (ObservableList.class.isAssignableFrom(attribute.getAttributeType().dataType) && Data.class.isAssignableFrom(attribute.getAttributeType().listItemType)){
ReferenceListAttribute<?> referenceListAttribute = (ReferenceListAttribute<?>) attribute;
return Optional.of(new AttributeEditor<>((Attribute<ObservableList<Data>>)attribute,new ReferenceListAttributeVisualisation(uniformDesign, dataEditor, () -> referenceListAttribute.addNewFactory(root), ()->(List<Data>)referenceListAttribute.possibleValues(root))));
}
return Optional.empty();
}
@SuppressWarnings("unchecked")
private Optional<AttributeEditor<?>> getAttributeEditorList(Attribute<?> attribute, DataEditor dataEditor) {
if (attribute.getAttributeType().dataType == null)
return Optional.empty();
if (ObservableList.class.isAssignableFrom(attribute.getAttributeType().dataType) && String.class==attribute.getAttributeType().listItemType){
StringAttribute detailAttribute = new StringAttribute(new AttributeMetadata().de("Wert").en("Value"));
AttributeEditor<String> attributeEditor = (AttributeEditor<String>) getAttributeEditor(detailAttribute,dataEditor).get();
return Optional.of(new AttributeEditor<>((Attribute<ObservableList<String>>)attribute,new ListAttributeVisualisation<>(uniformDesign, detailAttribute, attributeEditor)));
}
if (ObservableList.class.isAssignableFrom(attribute.getAttributeType().dataType) && Integer.class==attribute.getAttributeType().listItemType){
IntegerAttribute detailAttribute = new IntegerAttribute(new AttributeMetadata().de("Wert").en("Value"));
AttributeEditor<Integer> attributeEditor = (AttributeEditor<Integer>) getAttributeEditor(detailAttribute,dataEditor).get();
return Optional.of(new AttributeEditor<>((Attribute<ObservableList<Integer>>)attribute,new ListAttributeVisualisation<>(uniformDesign, detailAttribute, attributeEditor)));
}
if (ObservableList.class.isAssignableFrom(attribute.getAttributeType().dataType) && Long.class==attribute.getAttributeType().listItemType){
LongAttribute detailAttribute = new LongAttribute(new AttributeMetadata().de("Wert").en("Value"));
AttributeEditor<Long> attributeEditor = (AttributeEditor<Long>) getAttributeEditor(detailAttribute,dataEditor).get();
return Optional.of(new AttributeEditor<>((Attribute<ObservableList<Long>>)attribute,new ListAttributeVisualisation<>(uniformDesign, detailAttribute, attributeEditor)));
}
if (ObservableList.class.isAssignableFrom(attribute.getAttributeType().dataType) && BigDecimal.class==attribute.getAttributeType().listItemType){
BigDecimalAttribute detailAttribute = new BigDecimalAttribute(new AttributeMetadata().de("Wert").en("Value"));
AttributeEditor<BigDecimal> attributeEditor = (AttributeEditor<BigDecimal>) getAttributeEditor(detailAttribute,dataEditor).get();
return Optional.of(new AttributeEditor<>((Attribute<ObservableList<BigDecimal>>)attribute,new ListAttributeVisualisation<>(uniformDesign, detailAttribute, attributeEditor)));
}
if (ObservableList.class.isAssignableFrom(attribute.getAttributeType().dataType) && Double.class==attribute.getAttributeType().listItemType){
DoubleAttribute detailAttribute = new DoubleAttribute(new AttributeMetadata().de("Wert").en("Value"));
AttributeEditor<Double> attributeEditor = (AttributeEditor<Double>) getAttributeEditor(detailAttribute,dataEditor).get();
return Optional.of(new AttributeEditor<>((Attribute<ObservableList<Double>>)attribute,new ListAttributeVisualisation<>(uniformDesign, detailAttribute, attributeEditor)));
}
if (ObservableList.class.isAssignableFrom(attribute.getAttributeType().dataType) && URI.class==attribute.getAttributeType().listItemType){
URIAttribute detailAttribute = new URIAttribute(new AttributeMetadata().de("URI").en("URI"));
AttributeEditor<URI> attributeEditor = (AttributeEditor<URI>) getAttributeEditor(detailAttribute,dataEditor).get();
return Optional.of(new AttributeEditor<>((Attribute<ObservableList<URI>>)attribute,new ListAttributeVisualisation<>(uniformDesign, detailAttribute, attributeEditor)));
}
return Optional.empty();
}
@SuppressWarnings("unchecked")
private Optional<AttributeEditor<?>> getAttributeEditorSimpleType(Attribute<?> attribute) {
if (attribute.getAttributeType().dataType == null)
return Optional.empty();
if (String.class==attribute.getAttributeType().dataType){
return Optional.of(new AttributeEditor<>((Attribute<String>)attribute,new StringAttributeVisualisation()));
}
if (Integer.class==attribute.getAttributeType().dataType){
return Optional.of(new AttributeEditor<>((Attribute<Integer>)attribute,new IntegerAttributeVisualisation()));
}
if (Boolean.class==attribute.getAttributeType().dataType){
return Optional.of(new AttributeEditor<>((Attribute<Boolean>)attribute,new BooleanAttributeVisualisation()));
}
if (Enum.class.isAssignableFrom(attribute.getAttributeType().dataType)){
Attribute<Enum> enumAttribute = (Attribute<Enum>) attribute;
List<Enum> enumConstants = Arrays.asList((Enum[]) enumAttribute.getAttributeType().dataType.getEnumConstants());
return Optional.of(new AttributeEditor<>(enumAttribute,new EnumAttributeVisualisation(enumConstants)));
}
if (Long.class==attribute.getAttributeType().dataType){
return Optional.of(new AttributeEditor<>((Attribute<Long>)attribute,new LongAttributeVisualisation()));
}
if (BigDecimal.class==attribute.getAttributeType().dataType){
return Optional.of(new AttributeEditor<>((Attribute<BigDecimal>)attribute,new BigDecimalAttributeVisualisation()));
}
if (Double.class==attribute.getAttributeType().dataType){
return Optional.of(new AttributeEditor<>((Attribute<Double>)attribute,new DoubleAttributeVisualisation()));
}
if (URI.class.isAssignableFrom(attribute.getAttributeType().dataType)) {
return Optional.of(new AttributeEditor<>((Attribute<URI>)attribute,new URIAttributeVisualisation()));
}
if (LocalDate.class.isAssignableFrom(attribute.getAttributeType().dataType)) {
return Optional.of(new AttributeEditor<>((Attribute<LocalDate>)attribute,new LocalDateAttributeVisualisation()));
}
if (Color.class.isAssignableFrom(attribute.getAttributeType().dataType)) {
return Optional.of(new AttributeEditor<>((Attribute<Color>)attribute,new ColorAttributeVisualisation()));
}
if (Locale.class.isAssignableFrom(attribute.getAttributeType().dataType)) {
return Optional.of(new AttributeEditor<>((Attribute<Locale>)attribute,new LocaleAttributeVisualisation()));
}
if (TableAttribute.Table.class.isAssignableFrom(attribute.getAttributeType().dataType)) {
return Optional.of(new AttributeEditor<>((Attribute<TableAttribute.Table>)attribute,new TableAttributeVisualisation(uniformDesign)));
}
return Optional.empty();
}
}
| javafxDataEditing/src/main/java/de/factoryfx/javafx/editor/attribute/AttributeEditorFactory.java | package de.factoryfx.javafx.editor.attribute;
import java.math.BigDecimal;
import java.net.URI;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.function.Function;
import de.factoryfx.data.Data;
import de.factoryfx.data.attribute.Attribute;
import de.factoryfx.data.attribute.AttributeMetadata;
import de.factoryfx.data.attribute.ReferenceAttribute;
import de.factoryfx.data.attribute.ReferenceListAttribute;
import de.factoryfx.data.attribute.types.BigDecimalAttribute;
import de.factoryfx.data.attribute.types.DoubleAttribute;
import de.factoryfx.data.attribute.types.IntegerAttribute;
import de.factoryfx.data.attribute.types.LongAttribute;
import de.factoryfx.data.attribute.types.StringAttribute;
import de.factoryfx.data.attribute.types.TableAttribute;
import de.factoryfx.data.attribute.types.URIAttribute;
import de.factoryfx.javafx.editor.attribute.visualisation.BigDecimalAttributeVisualisation;
import de.factoryfx.javafx.editor.attribute.visualisation.BooleanAttributeVisualisation;
import de.factoryfx.javafx.editor.attribute.visualisation.ColorAttributeVisualisation;
import de.factoryfx.javafx.editor.attribute.visualisation.DoubleAttributeVisualisation;
import de.factoryfx.javafx.editor.attribute.visualisation.EnumAttributeVisualisation;
import de.factoryfx.javafx.editor.attribute.visualisation.IntegerAttributeVisualisation;
import de.factoryfx.javafx.editor.attribute.visualisation.ListAttributeVisualisation;
import de.factoryfx.javafx.editor.attribute.visualisation.LocalDateAttributeVisualisation;
import de.factoryfx.javafx.editor.attribute.visualisation.LocaleAttributeVisualisation;
import de.factoryfx.javafx.editor.attribute.visualisation.LongAttributeVisualisation;
import de.factoryfx.javafx.editor.attribute.visualisation.ReferenceAttributeVisualisation;
import de.factoryfx.javafx.editor.attribute.visualisation.ReferenceListAttributeVisualisation;
import de.factoryfx.javafx.editor.attribute.visualisation.StringAttributeVisualisation;
import de.factoryfx.javafx.editor.attribute.visualisation.TableAttributeVisualisation;
import de.factoryfx.javafx.editor.attribute.visualisation.URIAttributeVisualisation;
import de.factoryfx.javafx.editor.data.DataEditor;
import de.factoryfx.javafx.util.UniformDesign;
import javafx.collections.ObservableList;
import javafx.scene.paint.Color;
public class AttributeEditorFactory {
private final UniformDesign uniformDesign;
private final Data root;
public AttributeEditorFactory(UniformDesign uniformDesign, Data root) {
this.uniformDesign = uniformDesign;
this.root = root;
}
List<Function<Attribute<?>,Optional<AttributeEditor<?>>>> editorAssociations=new ArrayList<>();
public void addEditorAssociation(Function<Attribute<?>,Optional<AttributeEditor<?>>> editorAssociation){
editorAssociations.add(editorAssociation);
}
public Optional<AttributeEditor<?>> getAttributeEditor(Attribute<?> attribute, DataEditor dataEditor){
for (Function<Attribute<?>,Optional<AttributeEditor<?>>> editorAssociation: editorAssociations) {
Optional<AttributeEditor<?>> attributeEditor = editorAssociation.apply(attribute);
if (attributeEditor.isPresent()) {
return attributeEditor;
}
}
Optional<AttributeEditor<?>> enumAttribute = getAttributeEditorSimpleType(attribute);
if (enumAttribute.isPresent()) return enumAttribute;
Optional<AttributeEditor<?>> detailAttribute = getAttributeEditorList(attribute, dataEditor);
if (detailAttribute.isPresent()) return detailAttribute;
Optional<AttributeEditor<?>> referenceAttribute = getAttributeEditorReference(attribute, dataEditor);
if (referenceAttribute.isPresent()) return referenceAttribute;
return Optional.empty();
}
@SuppressWarnings("unchecked")
private Optional<AttributeEditor<?>> getAttributeEditorReference(Attribute<?> attribute, DataEditor dataEditor) {
if (Data.class==attribute.getAttributeType().dataType){
ReferenceAttribute<?> referenceAttribute = (ReferenceAttribute<?>) attribute;
return Optional.of(new AttributeEditor<>((Attribute<Data>)attribute,new ReferenceAttributeVisualisation(uniformDesign,dataEditor,()->referenceAttribute.addNewFactory(root),()->(List<Data>)referenceAttribute.possibleValues(root))));
}
if (ObservableList.class.isAssignableFrom(attribute.getAttributeType().dataType) && Data.class.isAssignableFrom(attribute.getAttributeType().listItemType)){
ReferenceListAttribute<?> referenceListAttribute = (ReferenceListAttribute<?>) attribute;
return Optional.of(new AttributeEditor<>((Attribute<ObservableList<Data>>)attribute,new ReferenceListAttributeVisualisation(uniformDesign, dataEditor, () -> referenceListAttribute.addNewFactory(root), ()->(List<Data>)referenceListAttribute.possibleValues(root))));
}
return Optional.empty();
}
@SuppressWarnings("unchecked")
private Optional<AttributeEditor<?>> getAttributeEditorList(Attribute<?> attribute, DataEditor dataEditor) {
if (ObservableList.class.isAssignableFrom(attribute.getAttributeType().dataType) && String.class==attribute.getAttributeType().listItemType){
StringAttribute detailAttribute = new StringAttribute(new AttributeMetadata().de("Wert").en("Value"));
AttributeEditor<String> attributeEditor = (AttributeEditor<String>) getAttributeEditor(detailAttribute,dataEditor).get();
return Optional.of(new AttributeEditor<>((Attribute<ObservableList<String>>)attribute,new ListAttributeVisualisation<>(uniformDesign, detailAttribute, attributeEditor)));
}
if (ObservableList.class.isAssignableFrom(attribute.getAttributeType().dataType) && Integer.class==attribute.getAttributeType().listItemType){
IntegerAttribute detailAttribute = new IntegerAttribute(new AttributeMetadata().de("Wert").en("Value"));
AttributeEditor<Integer> attributeEditor = (AttributeEditor<Integer>) getAttributeEditor(detailAttribute,dataEditor).get();
return Optional.of(new AttributeEditor<>((Attribute<ObservableList<Integer>>)attribute,new ListAttributeVisualisation<>(uniformDesign, detailAttribute, attributeEditor)));
}
if (ObservableList.class.isAssignableFrom(attribute.getAttributeType().dataType) && Long.class==attribute.getAttributeType().listItemType){
LongAttribute detailAttribute = new LongAttribute(new AttributeMetadata().de("Wert").en("Value"));
AttributeEditor<Long> attributeEditor = (AttributeEditor<Long>) getAttributeEditor(detailAttribute,dataEditor).get();
return Optional.of(new AttributeEditor<>((Attribute<ObservableList<Long>>)attribute,new ListAttributeVisualisation<>(uniformDesign, detailAttribute, attributeEditor)));
}
if (ObservableList.class.isAssignableFrom(attribute.getAttributeType().dataType) && BigDecimal.class==attribute.getAttributeType().listItemType){
BigDecimalAttribute detailAttribute = new BigDecimalAttribute(new AttributeMetadata().de("Wert").en("Value"));
AttributeEditor<BigDecimal> attributeEditor = (AttributeEditor<BigDecimal>) getAttributeEditor(detailAttribute,dataEditor).get();
return Optional.of(new AttributeEditor<>((Attribute<ObservableList<BigDecimal>>)attribute,new ListAttributeVisualisation<>(uniformDesign, detailAttribute, attributeEditor)));
}
if (ObservableList.class.isAssignableFrom(attribute.getAttributeType().dataType) && Double.class==attribute.getAttributeType().listItemType){
DoubleAttribute detailAttribute = new DoubleAttribute(new AttributeMetadata().de("Wert").en("Value"));
AttributeEditor<Double> attributeEditor = (AttributeEditor<Double>) getAttributeEditor(detailAttribute,dataEditor).get();
return Optional.of(new AttributeEditor<>((Attribute<ObservableList<Double>>)attribute,new ListAttributeVisualisation<>(uniformDesign, detailAttribute, attributeEditor)));
}
if (ObservableList.class.isAssignableFrom(attribute.getAttributeType().dataType) && URI.class==attribute.getAttributeType().listItemType){
URIAttribute detailAttribute = new URIAttribute(new AttributeMetadata().de("URI").en("URI"));
AttributeEditor<URI> attributeEditor = (AttributeEditor<URI>) getAttributeEditor(detailAttribute,dataEditor).get();
return Optional.of(new AttributeEditor<>((Attribute<ObservableList<URI>>)attribute,new ListAttributeVisualisation<>(uniformDesign, detailAttribute, attributeEditor)));
}
return Optional.empty();
}
@SuppressWarnings("unchecked")
private Optional<AttributeEditor<?>> getAttributeEditorSimpleType(Attribute<?> attribute) {
if (attribute.getAttributeType().dataType == null)
return Optional.empty();
if (String.class==attribute.getAttributeType().dataType){
return Optional.of(new AttributeEditor<>((Attribute<String>)attribute,new StringAttributeVisualisation()));
}
if (Integer.class==attribute.getAttributeType().dataType){
return Optional.of(new AttributeEditor<>((Attribute<Integer>)attribute,new IntegerAttributeVisualisation()));
}
if (Boolean.class==attribute.getAttributeType().dataType){
return Optional.of(new AttributeEditor<>((Attribute<Boolean>)attribute,new BooleanAttributeVisualisation()));
}
if (Enum.class.isAssignableFrom(attribute.getAttributeType().dataType)){
Attribute<Enum> enumAttribute = (Attribute<Enum>) attribute;
List<Enum> enumConstants = Arrays.asList((Enum[]) enumAttribute.getAttributeType().dataType.getEnumConstants());
return Optional.of(new AttributeEditor<>(enumAttribute,new EnumAttributeVisualisation(enumConstants)));
}
if (Long.class==attribute.getAttributeType().dataType){
return Optional.of(new AttributeEditor<>((Attribute<Long>)attribute,new LongAttributeVisualisation()));
}
if (BigDecimal.class==attribute.getAttributeType().dataType){
return Optional.of(new AttributeEditor<>((Attribute<BigDecimal>)attribute,new BigDecimalAttributeVisualisation()));
}
if (Double.class==attribute.getAttributeType().dataType){
return Optional.of(new AttributeEditor<>((Attribute<Double>)attribute,new DoubleAttributeVisualisation()));
}
if (URI.class.isAssignableFrom(attribute.getAttributeType().dataType)) {
return Optional.of(new AttributeEditor<>((Attribute<URI>)attribute,new URIAttributeVisualisation()));
}
if (LocalDate.class.isAssignableFrom(attribute.getAttributeType().dataType)) {
return Optional.of(new AttributeEditor<>((Attribute<LocalDate>)attribute,new LocalDateAttributeVisualisation()));
}
if (Color.class.isAssignableFrom(attribute.getAttributeType().dataType)) {
return Optional.of(new AttributeEditor<>((Attribute<Color>)attribute,new ColorAttributeVisualisation()));
}
if (Locale.class.isAssignableFrom(attribute.getAttributeType().dataType)) {
return Optional.of(new AttributeEditor<>((Attribute<Locale>)attribute,new LocaleAttributeVisualisation()));
}
if (TableAttribute.Table.class.isAssignableFrom(attribute.getAttributeType().dataType)) {
return Optional.of(new AttributeEditor<>((Attribute<TableAttribute.Table>)attribute,new TableAttributeVisualisation(uniformDesign)));
}
return Optional.empty();
}
}
| fix npe
| javafxDataEditing/src/main/java/de/factoryfx/javafx/editor/attribute/AttributeEditorFactory.java | fix npe |
|
Java | apache-2.0 | 9dbc0bd94d1305ee673fd4d3d69e613741f67b5c | 0 | philliphsu/BottomSheetPickers | /*
* 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.philliphsu.bottomsheetpickers.date;
import android.app.Activity;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.ColorInt;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.philliphsu.bottomsheetpickers.HapticFeedbackController;
import com.philliphsu.bottomsheetpickers.R;
import com.philliphsu.bottomsheetpickers.Utils;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale;
import static com.philliphsu.bottomsheetpickers.date.DateFormatHelper.formatDate;
import static com.philliphsu.bottomsheetpickers.date.PagingDayPickerView.DAY_PICKER_INDEX;
/**
* Dialog allowing users to select a date.
*/
public class BottomSheetDatePickerDialog extends DatePickerDialog implements
OnClickListener, DatePickerController, OnTouchListener, OnScrollListener {
private static final String TAG = "DatePickerDialog";
private static final int UNINITIALIZED = -1;
private static final int MONTH_AND_DAY_VIEW = 0;
private static final int YEAR_VIEW = 1;
private static final String KEY_SELECTED_YEAR = "year";
private static final String KEY_SELECTED_MONTH = "month";
private static final String KEY_SELECTED_DAY = "day";
private static final String KEY_LIST_POSITION = "list_position";
private static final String KEY_WEEK_START = "week_start";
private static final String KEY_YEAR_START = "year_start";
private static final String KEY_YEAR_END = "year_end";
private static final String KEY_CURRENT_VIEW = "current_view";
private static final String KEY_LIST_POSITION_OFFSET = "list_position_offset";
private static final String KEY_DAY_PICKER_CURRENT_INDEX = "day_picker_current_index";
private static final String KEY_MIN_DATE_MILLIS = "min_date_millis";
private static final String KEY_MAX_DATE_MILLIS = "max_date_millis";
private static final String KEY_HEADER_TEXT_COLOR_SELECTED = "header_text_color_selected";
private static final String KEY_HEADER_TEXT_COLOR_UNSELECTED = "header_text_color_unselected";
private static final String KEY_DAY_OF_WEEK_HEADER_TEXT_COLOR = "day_of_week_header_text_color";
private static final int DEFAULT_START_YEAR = 1900;
private static final int DEFAULT_END_YEAR = 2100;
private static final int ANIMATION_DURATION = 300;
private static final int ANIMATION_DELAY = 500;
private static SimpleDateFormat YEAR_FORMAT = new SimpleDateFormat("yyyy", Locale.getDefault());
private static SimpleDateFormat DAY_FORMAT = new SimpleDateFormat("dd", Locale.getDefault());
private final Calendar mCalendar = Calendar.getInstance();
private OnDateSetListener mCallBack;
private HashSet<OnDateChangedListener> mListeners = new HashSet<OnDateChangedListener>();
private AccessibleDateAnimator mAnimator;
private TextView mDayOfWeekView;
private LinearLayout mMonthDayYearView;
private TextView mFirstTextView;
private TextView mSecondTextView;
private PagingDayPickerView mDayPickerView;
private YearPickerView mYearPickerView;
private Button mDoneButton;
private Button mCancelButton;
private int mCurrentView = UNINITIALIZED;
private int mWeekStart = mCalendar.getFirstDayOfWeek();
private int mMinYear = DEFAULT_START_YEAR;
private int mMaxYear = DEFAULT_END_YEAR;
private @Nullable Calendar mMinDate;
private @Nullable Calendar mMaxDate;
private HapticFeedbackController mHapticFeedbackController;
private CalendarDay mSelectedDay;
private boolean mDelayAnimation = true;
// Accessibility strings.
private String mDayPickerDescription;
private String mSelectDay;
private String mYearPickerDescription;
private String mSelectYear;
// Relative positions of (MD) and Y in the locale's date formatting style.
private int mLocaleMonthDayIndex;
private int mLocaleYearIndex;
private int mHeaderTextColorSelected;
private int mHeaderTextColorUnselected;
private int mDayOfWeekHeaderTextColor;
public BottomSheetDatePickerDialog() {
// Empty constructor required for dialog fragment.
}
/**
* @param callBack How the parent is notified that the date is set.
* @param year The initial year of the dialog.
* @param monthOfYear The initial month of the dialog.
* @param dayOfMonth The initial day of the dialog.
*/
public static BottomSheetDatePickerDialog newInstance(OnDateSetListener callBack, int year,
int monthOfYear,
int dayOfMonth) {
BottomSheetDatePickerDialog ret = new BottomSheetDatePickerDialog();
ret.initialize(callBack, year, monthOfYear, dayOfMonth);
return ret;
}
public void initialize(OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) {
mCallBack = callBack;
mCalendar.set(Calendar.YEAR, year);
mCalendar.set(Calendar.MONTH, monthOfYear);
mCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Activity activity = getActivity();
activity.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
if (savedInstanceState != null) {
mCalendar.set(Calendar.YEAR, savedInstanceState.getInt(KEY_SELECTED_YEAR));
mCalendar.set(Calendar.MONTH, savedInstanceState.getInt(KEY_SELECTED_MONTH));
mCalendar.set(Calendar.DAY_OF_MONTH, savedInstanceState.getInt(KEY_SELECTED_DAY));
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(KEY_SELECTED_YEAR, mCalendar.get(Calendar.YEAR));
outState.putInt(KEY_SELECTED_MONTH, mCalendar.get(Calendar.MONTH));
outState.putInt(KEY_SELECTED_DAY, mCalendar.get(Calendar.DAY_OF_MONTH));
outState.putInt(KEY_WEEK_START, mWeekStart);
outState.putInt(KEY_YEAR_START, mMinYear);
outState.putInt(KEY_YEAR_END, mMaxYear);
outState.putInt(KEY_CURRENT_VIEW, mCurrentView);
int listPosition = -1;
if (mCurrentView == MONTH_AND_DAY_VIEW) {
listPosition = mDayPickerView.getPagerPosition();
outState.putInt(KEY_DAY_PICKER_CURRENT_INDEX, mDayPickerView.getCurrentView());
} else if (mCurrentView == YEAR_VIEW) {
listPosition = mYearPickerView.getFirstVisiblePosition();
outState.putInt(KEY_LIST_POSITION_OFFSET, mYearPickerView.getFirstPositionOffset());
}
outState.putInt(KEY_LIST_POSITION, listPosition);
if (mMinDate != null) {
outState.putLong(KEY_MIN_DATE_MILLIS, mMinDate.getTimeInMillis());
}
if (mMaxDate != null) {
outState.putLong(KEY_MAX_DATE_MILLIS, mMaxDate.getTimeInMillis());
}
outState.putInt(KEY_HEADER_TEXT_COLOR_SELECTED, mHeaderTextColorSelected);
outState.putInt(KEY_HEADER_TEXT_COLOR_UNSELECTED, mHeaderTextColorUnselected);
outState.putInt(KEY_DAY_OF_WEEK_HEADER_TEXT_COLOR, mDayOfWeekHeaderTextColor);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = super.onCreateView(inflater, container, savedInstanceState);
mDayOfWeekView = (TextView) view.findViewById(R.id.date_picker_header);
mDayOfWeekView.setTypeface(Utils.SANS_SERIF_LIGHT_BOLD);
mMonthDayYearView = (LinearLayout) view.findViewById(R.id.date_picker_month_day_year);
mFirstTextView = (TextView) view.findViewById(R.id.date_picker_first_textview);
mFirstTextView.setOnClickListener(this);
mFirstTextView.setTypeface(Utils.SANS_SERIF_LIGHT_BOLD);
mSecondTextView = (TextView) view.findViewById(R.id.date_picker_second_textview);
mSecondTextView.setOnClickListener(this);
mSecondTextView.setTypeface(Utils.SANS_SERIF_LIGHT_BOLD);
int listPosition = -1;
int listPositionOffset = 0;
int currentView = MONTH_AND_DAY_VIEW;
int dayPickerCurrentView = DAY_PICKER_INDEX;
if (savedInstanceState != null) {
mWeekStart = savedInstanceState.getInt(KEY_WEEK_START);
mMinYear = savedInstanceState.getInt(KEY_YEAR_START);
mMaxYear = savedInstanceState.getInt(KEY_YEAR_END);
currentView = savedInstanceState.getInt(KEY_CURRENT_VIEW);
listPosition = savedInstanceState.getInt(KEY_LIST_POSITION);
listPositionOffset = savedInstanceState.getInt(KEY_LIST_POSITION_OFFSET);
dayPickerCurrentView = savedInstanceState.getInt(KEY_DAY_PICKER_CURRENT_INDEX);
mHeaderTextColorSelected = savedInstanceState.getInt(KEY_HEADER_TEXT_COLOR_SELECTED);
mHeaderTextColorUnselected = savedInstanceState.getInt(KEY_HEADER_TEXT_COLOR_UNSELECTED);
mDayOfWeekHeaderTextColor = savedInstanceState.getInt(KEY_DAY_OF_WEEK_HEADER_TEXT_COLOR);
// Don't restore both in one block because it may well be that only one was set.
if (savedInstanceState.containsKey(KEY_MIN_DATE_MILLIS)) {
mMinDate = Calendar.getInstance();
mMinDate.setTimeInMillis(savedInstanceState.getLong(KEY_MIN_DATE_MILLIS));
}
if (savedInstanceState.containsKey(KEY_MAX_DATE_MILLIS)) {
mMaxDate = Calendar.getInstance();
mMaxDate.setTimeInMillis(savedInstanceState.getLong(KEY_MAX_DATE_MILLIS));
}
}
final Activity activity = getActivity();
mDayPickerView = new PagingDayPickerView(activity, this, mThemeDark, mAccentColor);
mYearPickerView = new YearPickerView(activity, this);
mYearPickerView.setTheme(activity, mThemeDark);
mYearPickerView.setAccentColor(mAccentColor);
// Listen for touches so that we can enable/disable the bottom sheet's cancelable
// state based on the location of the touch event.
//
// Both views MUST have the listener set. Why? Consider each call individually.
// If we only set the listener on the first call, touch events on the ListView would
// not be detected since it handles and consumes scroll events on its own.
// If we only set the listener on the second call, touch events would only be detected
// within the ListView and not in other views in our hierarchy.
view.setOnTouchListener(this);
mYearPickerView.setOnTouchListener(this);
// Listen for scroll end events, so that we can restore the cancelable state immediately.
mYearPickerView.setOnScrollListener(this);
Resources res = getResources();
mDayPickerDescription = res.getString(R.string.day_picker_description);
mSelectDay = res.getString(R.string.select_day);
mYearPickerDescription = res.getString(R.string.year_picker_description);
mSelectYear = res.getString(R.string.select_year);
mAnimator = (AccessibleDateAnimator) view.findViewById(R.id.animator);
mAnimator.addView(mDayPickerView);
mAnimator.addView(mYearPickerView);
mAnimator.setDateMillis(mCalendar.getTimeInMillis());
// TODO: Replace with animation decided upon by the design team.
Animation animation = new AlphaAnimation(0.0f, 1.0f);
animation.setDuration(ANIMATION_DURATION);
mAnimator.setInAnimation(animation);
// TODO: Replace with animation decided upon by the design team.
Animation animation2 = new AlphaAnimation(1.0f, 0.0f);
animation2.setDuration(ANIMATION_DURATION);
mAnimator.setOutAnimation(animation2);
mDoneButton = (Button) view.findViewById(R.id.done);
mDoneButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
tryVibrate();
if (mCallBack != null) {
mCallBack.onDateSet(BottomSheetDatePickerDialog.this, mCalendar.get(Calendar.YEAR),
mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH));
}
dismiss();
}
});
mCancelButton = (Button) view.findViewById(R.id.cancel);
mCancelButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
}
});
// Setup action button text colors.
mCancelButton.setTextColor(mAccentColor);
mDoneButton.setTextColor(mAccentColor);
final int backgroundColor = mBackgroundColorSetAtRuntime
? mBackgroundColor : (mThemeDark ? mDarkGray : mWhite);
final int headerColor = mHeaderColorSetAtRuntime
? mHeaderColor : (mThemeDark ? mLightGray : mAccentColor);
// This is so the margin gets colored as well.
view.setBackgroundColor(backgroundColor);
mAnimator.setBackgroundColor(backgroundColor);
mDayPickerView.setAccentColor(mAccentColor);
view.findViewById(R.id.day_picker_selected_date_layout).setBackgroundColor(headerColor);
if (mThemeDark) {
final int selectableItemBg = ContextCompat.getColor(activity,
R.color.selectable_item_background_dark);
Utils.setColorControlHighlight(mCancelButton, selectableItemBg);
Utils.setColorControlHighlight(mDoneButton, selectableItemBg);
}
// Before setting any custom header text colors, check if the dark header text theme was
// requested and apply it.
if (mHeaderTextColorSetAtRuntime && mHeaderTextDark) {
final ColorStateList colors = ContextCompat.getColorStateList(activity,
R.color.date_picker_selector_light);
mDayOfWeekView.setTextColor(colors.getDefaultColor() /* text_color_secondary_light */);
mFirstTextView.setTextColor(colors);
mSecondTextView.setTextColor(colors);
}
// Apply the custom colors for the header texts, if applicable.
if (mHeaderTextColorSelected != 0 || mHeaderTextColorUnselected != 0) {
final int[][] states = {
{android.R.attr.state_selected},
{-android.R.attr.state_selected},
{ /* default state */}
};
final int selectedColor = mHeaderTextColorSelected != 0 ? mHeaderTextColorSelected
: (mHeaderTextDark ? mBlackText : mWhite);
final int unselectedColor = mHeaderTextColorUnselected != 0 ? mHeaderTextColorUnselected
: (mHeaderTextDark ? mBlackTextDisabled : mWhiteTextDisabled);
final int[] colors = { selectedColor, unselectedColor, unselectedColor };
final ColorStateList stateColors = new ColorStateList(states, colors);
mFirstTextView.setTextColor(stateColors);
mSecondTextView.setTextColor(stateColors);
}
// Apply the custom color for the day-of-week header text, if applicable.
if (mDayOfWeekHeaderTextColor != 0) {
mDayOfWeekView.setTextColor(mDayOfWeekHeaderTextColor);
}
determineLocale_MD_Y_Indices();
updateDisplay(false);
setCurrentView(currentView);
if (listPosition != -1) {
if (currentView == MONTH_AND_DAY_VIEW) {
mDayPickerView.postSetSelection(listPosition, false);
} else if (currentView == YEAR_VIEW) {
mYearPickerView.postSetSelectionFromTop(listPosition, listPositionOffset);
}
}
mDayPickerView.postSetupCurrentView(dayPickerCurrentView, false);
mHapticFeedbackController = new HapticFeedbackController(activity);
return view;
}
@Override
public void onResume() {
super.onResume();
mHapticFeedbackController.start();
}
@Override
public void onPause() {
super.onPause();
mHapticFeedbackController.stop();
}
private void setCurrentView(final int viewIndex) {
long millis = mCalendar.getTimeInMillis();
switch (viewIndex) {
case MONTH_AND_DAY_VIEW:
mDayPickerView.onDateChanged();
setCancelable(true);
if (mCurrentView != viewIndex) {
updateHeaderSelectedView(MONTH_AND_DAY_VIEW);
mAnimator.setDisplayedChild(MONTH_AND_DAY_VIEW);
mCurrentView = viewIndex;
}
String dayString = formatDate(mCalendar, DateUtils.FORMAT_SHOW_DATE);
mAnimator.setContentDescription(mDayPickerDescription + ": " + dayString);
Utils.tryAccessibilityAnnounce(mAnimator, mSelectDay);
break;
case YEAR_VIEW:
mYearPickerView.onDateChanged();
if (mCurrentView != viewIndex) {
updateHeaderSelectedView(YEAR_VIEW);
mAnimator.setDisplayedChild(YEAR_VIEW);
mCurrentView = viewIndex;
}
CharSequence yearString = YEAR_FORMAT.format(millis);
mAnimator.setContentDescription(mYearPickerDescription + ": " + yearString);
Utils.tryAccessibilityAnnounce(mAnimator, mSelectYear);
break;
}
}
private void updateHeaderSelectedView(final int viewIndex) {
switch (viewIndex) {
case MONTH_AND_DAY_VIEW:
mFirstTextView.setSelected(mLocaleMonthDayIndex == 0);
mSecondTextView.setSelected(mLocaleMonthDayIndex != 0);
break;
case YEAR_VIEW:
mFirstTextView.setSelected(mLocaleYearIndex == 0);
mSecondTextView.setSelected(mLocaleYearIndex != 0);
break;
}
}
/**
* Determine the relative positions of (MD) and Y according to the formatting style
* of the current locale.
*/
private void determineLocale_MD_Y_Indices() {
String formattedDate = formatMonthDayYear(mCalendar);
// Get the (MD) and Y parts of the formatted date in the current locale,
// so that we can compare their relative positions.
//
// You may be wondering why we need this method at all.
// "Just split() the formattedDate string around the year delimiter
// to get the two parts in an array already positioned correctly!
// Then setText() on mFirstTextView and mSecondTextView with the contents of that array!"
// That is harder than it sounds.
// Different locales use different year delimiters, and some don't use one at all.
// For example, a fully formatted date in the French locale is "30 juin 2009".
String monthAndDay = formatMonthAndDay(mCalendar);
String year = extractYearFromFormattedDate(formattedDate, monthAndDay);
// All locales format the M and D together; which comes
// first is not a necessary consideration for the comparison.
if (formattedDate.indexOf(monthAndDay) < formattedDate.indexOf(year/*not null*/)) {
mLocaleMonthDayIndex = 0;
mLocaleYearIndex = 1;
} else {
mLocaleYearIndex = 0;
mLocaleMonthDayIndex = 1;
}
}
private static String formatMonthDayYear(Calendar calendar) {
int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_MONTH | DateUtils.FORMAT_SHOW_YEAR;
return formatDate(calendar, flags);
}
private static String formatMonthAndDay(Calendar calendar) {
int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_MONTH | DateUtils.FORMAT_NO_YEAR;
return formatDate(calendar, flags);
}
private String extractYearFromFormattedDate(String formattedDate, String monthAndDay) {
String[] parts = formattedDate.split(monthAndDay);
for (String part : parts) {
// If the locale's date format is (MD)Y, then split(MD) = {"", Y}.
// If it is Y(MD), then split(MD) = {Y}. "Trailing empty strings are
// [...] not included in the resulting array."
if (!part.isEmpty()) {
return part;
}
}
// We will NEVER reach here, as long as the parameters are valid strings.
// We don't want this because it is not localized.
return YEAR_FORMAT.format(mCalendar.getTime());
}
private void updateDisplay(boolean announce) {
if (mDayOfWeekView != null) {
mDayOfWeekView.setText(mCalendar.getDisplayName(Calendar.DAY_OF_WEEK,
Calendar.LONG, Locale.getDefault()));
}
String fullDate = formatMonthDayYear(mCalendar);
String monthAndDay = formatMonthAndDay(mCalendar);
String year = YEAR_FORMAT.format(mCalendar.getTime());
int yearStart = fullDate.indexOf(year);
int yearEnd = yearStart + year.length();
int monthDayStart = fullDate.indexOf(monthAndDay);
int monthDayEnd = monthDayStart + monthAndDay.length();
boolean processed = false;
if (monthDayStart != -1 && yearStart != -1) {
if (mLocaleMonthDayIndex < mLocaleYearIndex) {
if (yearStart - monthDayEnd <= 2) {
monthAndDay = fullDate.substring(monthDayStart, yearStart);
year = fullDate.substring(yearStart, fullDate.length());
processed = true;
}
} else {
if (monthDayStart - yearEnd <= 2) {
year = fullDate.substring(yearStart, monthDayStart);
monthAndDay = fullDate.substring(monthDayStart, fullDate.length());
processed = true;
}
}
} else {
// Some locales format the standalone month-day or standalone year differently
// than it appears in the full date. For instance, Turkey is one such locale.
// TODO: You may want to consider making localized string resources of the
// pattern strings used to format the (MD) and (Y) parts separately.
//
// We can't compare the relative indices of (MD) and (Y) determined earlier,
// because the results are dubious if we're here.
// It is appropriate to assume yearStart != -1. The case where the raw year
// is NOT present in the full date string is hard to imagine. As such,
// even though monthDayStart == -1, we can still determine the relative indices
// of (MD) and (Y) as follows.
//
// If yearStart is non-zero positive, then we can probably guess monthDayStart
// comes before the former.
if (yearStart > 0) {
monthAndDay = fullDate.substring(0, yearStart);
year = fullDate.substring(yearStart, fullDate.length());
mLocaleMonthDayIndex = 0;
mLocaleYearIndex = 1;
} else {
year = fullDate.substring(0, yearEnd);
monthAndDay = fullDate.substring(yearEnd, fullDate.length());
mLocaleYearIndex = 0;
mLocaleMonthDayIndex = 1;
}
processed = true;
}
// Year delimiters longer than 2 characters, fall back on pre-2.1.1 implementation.
if (!processed) {
// The month-day is already formatted appropriately
year = extractYearFromFormattedDate(fullDate, monthAndDay);
}
mFirstTextView.setText(mLocaleMonthDayIndex == 0 ? monthAndDay : year);
mSecondTextView.setText(mLocaleMonthDayIndex == 0 ? year : monthAndDay);
// Accessibility.
long millis = mCalendar.getTimeInMillis();
mAnimator.setDateMillis(millis);
int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NO_YEAR;
String monthAndDayText = formatDate(millis, flags);
mMonthDayYearView.setContentDescription(monthAndDayText);
if (announce) {
flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR;
String fullDateText = formatDate(millis, flags);
Utils.tryAccessibilityAnnounce(mAnimator, fullDateText);
}
}
/**
* Use this to set the day that a week should start on.
* @param startOfWeek A value from {@link Calendar#SUNDAY SUNDAY}
* through {@link Calendar#SATURDAY SATURDAY}
*/
public void setFirstDayOfWeek(int startOfWeek) {
if (startOfWeek < Calendar.SUNDAY || startOfWeek > Calendar.SATURDAY) {
throw new IllegalArgumentException("Value must be between Calendar.SUNDAY and " +
"Calendar.SATURDAY");
}
mWeekStart = startOfWeek;
if (mDayPickerView != null) {
mDayPickerView.onChange();
}
}
/**
* Sets the range of years to be displayed by this date picker. If a {@link #setMinDate(Calendar)
* minimal date} and/or {@link #setMaxDate(Calendar) maximal date} were set, dates in the
* specified range of years that lie outside of the minimal and maximal dates will be disallowed
* from being selected.
* <em>This does NOT change the minimal date's year or the maximal date's year.</em>
*
* @param startYear the start of the year range
* @param endYear the end of the year range
*/
public void setYearRange(int startYear, int endYear) {
if (endYear <= startYear) {
throw new IllegalArgumentException("Year end must be larger than year start");
}
mMinYear = startYear;
mMaxYear = endYear;
if (mDayPickerView != null) {
mDayPickerView.onChange();
}
}
/**
* Sets the minimal date that can be selected in this date picker. Dates before (but not including)
* the specified date will be disallowed from being selected.
*
* @param calendar a Calendar object set to the year, month, day desired as the mindate.
*/
public void setMinDate(Calendar calendar) {
mMinDate = calendar;
setYearRange(calendar.get(Calendar.YEAR), mMaxYear);
}
/**
* @return The minimal date supported by this date picker. Null if it has not been set.
*/
@Nullable
@Override
public Calendar getMinDate() {
return mMinDate;
}
/**
* Sets the maximal date that can be selected in this date picker. Dates after (but not including)
* the specified date will be disallowed from being selected.
*
* @param calendar a Calendar object set to the year, month, day desired as the maxdate.
*/
public void setMaxDate(Calendar calendar) {
mMaxDate = calendar;
setYearRange(mMinYear, calendar.get(Calendar.YEAR));
}
/**
* @return The maximal date supported by this date picker. Null if it has not been set.
*/
@Nullable
@Override
public Calendar getMaxDate() {
return mMaxDate;
}
public void setOnDateSetListener(OnDateSetListener listener) {
mCallBack = listener;
}
/**
* Set the color of the header text when it is selected.
*/
public final void setHeaderTextColorSelected(@ColorInt int color) {
mHeaderTextColorSelected = color;
}
/**
* Set the color of the header text when it is not selected.
*/
public final void setHeaderTextColorUnselected(@ColorInt int color) {
mHeaderTextColorUnselected = color;
}
/**
* Set the color of the day-of-week header text.
*/
public final void setDayOfWeekHeaderTextColor(@ColorInt int color) {
mDayOfWeekHeaderTextColor = color;
}
// If the newly selected month / year does not contain the currently selected day number,
// change the selected day number to the last day of the selected month or year.
// e.g. Switching from Mar to Apr when Mar 31 is selected -> Apr 30
// e.g. Switching from 2012 to 2013 when Feb 29, 2012 is selected -> Feb 28, 2013
private void adjustDayInMonthIfNeeded(int month, int year) {
int day = mCalendar.get(Calendar.DAY_OF_MONTH);
int daysInMonth = Utils.getDaysInMonth(month, year);
if (day > daysInMonth) {
mCalendar.set(Calendar.DAY_OF_MONTH, daysInMonth);
}
}
@Override
public void onClick(View v) {
tryVibrate();
if (v.getId() == R.id.date_picker_second_textview) {
setCurrentView(mLocaleMonthDayIndex == 0 ? YEAR_VIEW : MONTH_AND_DAY_VIEW);
} else if (v.getId() == R.id.date_picker_first_textview) {
setCurrentView(mLocaleMonthDayIndex == 0 ? MONTH_AND_DAY_VIEW : YEAR_VIEW);
}
}
@Override
public boolean onTouch(View v, MotionEvent event) {
if (mCurrentView == YEAR_VIEW && v == mYearPickerView
&& event.getY() >= mYearPickerView.getTop()
&& event.getY() <= mYearPickerView.getBottom()) {
setCancelable(false);
return mYearPickerView.onTouchEvent(event);
}
setCancelable(true);
return false;
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
setCancelable(scrollState == SCROLL_STATE_IDLE);
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
// Do nothing.
}
@Override
public void onYearSelected(int year) {
adjustDayInMonthIfNeeded(mCalendar.get(Calendar.MONTH), year);
mCalendar.set(Calendar.YEAR, year);
updatePickers();
setCurrentView(MONTH_AND_DAY_VIEW);
updateDisplay(true);
}
@Override
public void onDayOfMonthSelected(int year, int month, int day) {
mCalendar.set(Calendar.YEAR, year);
mCalendar.set(Calendar.MONTH, month);
mCalendar.set(Calendar.DAY_OF_MONTH, day);
updatePickers();
updateDisplay(true);
}
@Override
public void onMonthYearSelected(int month, int year) {
adjustDayInMonthIfNeeded(month, year);
mCalendar.set(Calendar.MONTH, month);
mCalendar.set(Calendar.YEAR, year);
updatePickers();
// Even though the MonthPickerView is already contained in this index,
// keep this call here for accessibility announcement of the new selection.
setCurrentView(MONTH_AND_DAY_VIEW);
updateDisplay(true);
}
private void updatePickers() {
Iterator<OnDateChangedListener> iterator = mListeners.iterator();
while (iterator.hasNext()) {
iterator.next().onDateChanged();
}
}
@Override
public CalendarDay getSelectedDay() {
if (mSelectedDay == null) {
mSelectedDay = new CalendarDay(mCalendar);
} else {
mSelectedDay.setDay(mCalendar.get(Calendar.YEAR),
mCalendar.get(Calendar.MONTH),
mCalendar.get(Calendar.DAY_OF_MONTH));
}
return mSelectedDay;
}
@Override
public int getMinYear() {
return mMinYear;
}
@Override
public int getMaxYear() {
return mMaxYear;
}
@Override
public int getFirstDayOfWeek() {
return mWeekStart;
}
@Override
public void registerOnDateChangedListener(OnDateChangedListener listener) {
mListeners.add(listener);
}
@Override
public void unregisterOnDateChangedListener(OnDateChangedListener listener) {
mListeners.remove(listener);
}
@Override
public void tryVibrate() {
mHapticFeedbackController.tryVibrate();
}
@Override
protected int contentLayout() {
return R.layout.date_picker_dialog;
}
}
| bottomsheetpickers/src/main/java/com/philliphsu/bottomsheetpickers/date/BottomSheetDatePickerDialog.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.philliphsu.bottomsheetpickers.date;
import android.app.Activity;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.ColorInt;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.philliphsu.bottomsheetpickers.HapticFeedbackController;
import com.philliphsu.bottomsheetpickers.R;
import com.philliphsu.bottomsheetpickers.Utils;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale;
import static com.philliphsu.bottomsheetpickers.date.DateFormatHelper.formatDate;
import static com.philliphsu.bottomsheetpickers.date.PagingDayPickerView.DAY_PICKER_INDEX;
/**
* Dialog allowing users to select a date.
*/
public class BottomSheetDatePickerDialog extends DatePickerDialog implements
OnClickListener, DatePickerController, OnTouchListener, OnScrollListener {
private static final String TAG = "DatePickerDialog";
private static final int UNINITIALIZED = -1;
private static final int MONTH_AND_DAY_VIEW = 0;
private static final int YEAR_VIEW = 1;
private static final String KEY_SELECTED_YEAR = "year";
private static final String KEY_SELECTED_MONTH = "month";
private static final String KEY_SELECTED_DAY = "day";
private static final String KEY_LIST_POSITION = "list_position";
private static final String KEY_WEEK_START = "week_start";
private static final String KEY_YEAR_START = "year_start";
private static final String KEY_YEAR_END = "year_end";
private static final String KEY_CURRENT_VIEW = "current_view";
private static final String KEY_LIST_POSITION_OFFSET = "list_position_offset";
private static final String KEY_DAY_PICKER_CURRENT_INDEX = "day_picker_current_index";
private static final String KEY_MIN_DATE_MILLIS = "min_date_millis";
private static final String KEY_MAX_DATE_MILLIS = "max_date_millis";
private static final int DEFAULT_START_YEAR = 1900;
private static final int DEFAULT_END_YEAR = 2100;
private static final int ANIMATION_DURATION = 300;
private static final int ANIMATION_DELAY = 500;
private static SimpleDateFormat YEAR_FORMAT = new SimpleDateFormat("yyyy", Locale.getDefault());
private static SimpleDateFormat DAY_FORMAT = new SimpleDateFormat("dd", Locale.getDefault());
private final Calendar mCalendar = Calendar.getInstance();
private OnDateSetListener mCallBack;
private HashSet<OnDateChangedListener> mListeners = new HashSet<OnDateChangedListener>();
private AccessibleDateAnimator mAnimator;
private TextView mDayOfWeekView;
private LinearLayout mMonthDayYearView;
private TextView mFirstTextView;
private TextView mSecondTextView;
private PagingDayPickerView mDayPickerView;
private YearPickerView mYearPickerView;
private Button mDoneButton;
private Button mCancelButton;
private int mCurrentView = UNINITIALIZED;
private int mWeekStart = mCalendar.getFirstDayOfWeek();
private int mMinYear = DEFAULT_START_YEAR;
private int mMaxYear = DEFAULT_END_YEAR;
private @Nullable Calendar mMinDate;
private @Nullable Calendar mMaxDate;
private HapticFeedbackController mHapticFeedbackController;
private CalendarDay mSelectedDay;
private boolean mDelayAnimation = true;
// Accessibility strings.
private String mDayPickerDescription;
private String mSelectDay;
private String mYearPickerDescription;
private String mSelectYear;
// Relative positions of (MD) and Y in the locale's date formatting style.
private int mLocaleMonthDayIndex;
private int mLocaleYearIndex;
private int mHeaderTextColorSelected;
private int mHeaderTextColorUnselected;
private int mDayOfWeekHeaderTextColor;
public BottomSheetDatePickerDialog() {
// Empty constructor required for dialog fragment.
}
/**
* @param callBack How the parent is notified that the date is set.
* @param year The initial year of the dialog.
* @param monthOfYear The initial month of the dialog.
* @param dayOfMonth The initial day of the dialog.
*/
public static BottomSheetDatePickerDialog newInstance(OnDateSetListener callBack, int year,
int monthOfYear,
int dayOfMonth) {
BottomSheetDatePickerDialog ret = new BottomSheetDatePickerDialog();
ret.initialize(callBack, year, monthOfYear, dayOfMonth);
return ret;
}
public void initialize(OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) {
mCallBack = callBack;
mCalendar.set(Calendar.YEAR, year);
mCalendar.set(Calendar.MONTH, monthOfYear);
mCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Activity activity = getActivity();
activity.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
if (savedInstanceState != null) {
mCalendar.set(Calendar.YEAR, savedInstanceState.getInt(KEY_SELECTED_YEAR));
mCalendar.set(Calendar.MONTH, savedInstanceState.getInt(KEY_SELECTED_MONTH));
mCalendar.set(Calendar.DAY_OF_MONTH, savedInstanceState.getInt(KEY_SELECTED_DAY));
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(KEY_SELECTED_YEAR, mCalendar.get(Calendar.YEAR));
outState.putInt(KEY_SELECTED_MONTH, mCalendar.get(Calendar.MONTH));
outState.putInt(KEY_SELECTED_DAY, mCalendar.get(Calendar.DAY_OF_MONTH));
outState.putInt(KEY_WEEK_START, mWeekStart);
outState.putInt(KEY_YEAR_START, mMinYear);
outState.putInt(KEY_YEAR_END, mMaxYear);
outState.putInt(KEY_CURRENT_VIEW, mCurrentView);
int listPosition = -1;
if (mCurrentView == MONTH_AND_DAY_VIEW) {
listPosition = mDayPickerView.getPagerPosition();
outState.putInt(KEY_DAY_PICKER_CURRENT_INDEX, mDayPickerView.getCurrentView());
} else if (mCurrentView == YEAR_VIEW) {
listPosition = mYearPickerView.getFirstVisiblePosition();
outState.putInt(KEY_LIST_POSITION_OFFSET, mYearPickerView.getFirstPositionOffset());
}
outState.putInt(KEY_LIST_POSITION, listPosition);
if (mMinDate != null) {
outState.putLong(KEY_MIN_DATE_MILLIS, mMinDate.getTimeInMillis());
}
if (mMaxDate != null) {
outState.putLong(KEY_MAX_DATE_MILLIS, mMaxDate.getTimeInMillis());
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = super.onCreateView(inflater, container, savedInstanceState);
mDayOfWeekView = (TextView) view.findViewById(R.id.date_picker_header);
mDayOfWeekView.setTypeface(Utils.SANS_SERIF_LIGHT_BOLD);
mMonthDayYearView = (LinearLayout) view.findViewById(R.id.date_picker_month_day_year);
mFirstTextView = (TextView) view.findViewById(R.id.date_picker_first_textview);
mFirstTextView.setOnClickListener(this);
mFirstTextView.setTypeface(Utils.SANS_SERIF_LIGHT_BOLD);
mSecondTextView = (TextView) view.findViewById(R.id.date_picker_second_textview);
mSecondTextView.setOnClickListener(this);
mSecondTextView.setTypeface(Utils.SANS_SERIF_LIGHT_BOLD);
int listPosition = -1;
int listPositionOffset = 0;
int currentView = MONTH_AND_DAY_VIEW;
int dayPickerCurrentView = DAY_PICKER_INDEX;
if (savedInstanceState != null) {
mWeekStart = savedInstanceState.getInt(KEY_WEEK_START);
mMinYear = savedInstanceState.getInt(KEY_YEAR_START);
mMaxYear = savedInstanceState.getInt(KEY_YEAR_END);
currentView = savedInstanceState.getInt(KEY_CURRENT_VIEW);
listPosition = savedInstanceState.getInt(KEY_LIST_POSITION);
listPositionOffset = savedInstanceState.getInt(KEY_LIST_POSITION_OFFSET);
dayPickerCurrentView = savedInstanceState.getInt(KEY_DAY_PICKER_CURRENT_INDEX);
// Don't restore both in one block because it may well be that only one was set.
if (savedInstanceState.containsKey(KEY_MIN_DATE_MILLIS)) {
mMinDate = Calendar.getInstance();
mMinDate.setTimeInMillis(savedInstanceState.getLong(KEY_MIN_DATE_MILLIS));
}
if (savedInstanceState.containsKey(KEY_MAX_DATE_MILLIS)) {
mMaxDate = Calendar.getInstance();
mMaxDate.setTimeInMillis(savedInstanceState.getLong(KEY_MAX_DATE_MILLIS));
}
}
final Activity activity = getActivity();
mDayPickerView = new PagingDayPickerView(activity, this, mThemeDark, mAccentColor);
mYearPickerView = new YearPickerView(activity, this);
mYearPickerView.setTheme(activity, mThemeDark);
mYearPickerView.setAccentColor(mAccentColor);
// Listen for touches so that we can enable/disable the bottom sheet's cancelable
// state based on the location of the touch event.
//
// Both views MUST have the listener set. Why? Consider each call individually.
// If we only set the listener on the first call, touch events on the ListView would
// not be detected since it handles and consumes scroll events on its own.
// If we only set the listener on the second call, touch events would only be detected
// within the ListView and not in other views in our hierarchy.
view.setOnTouchListener(this);
mYearPickerView.setOnTouchListener(this);
// Listen for scroll end events, so that we can restore the cancelable state immediately.
mYearPickerView.setOnScrollListener(this);
Resources res = getResources();
mDayPickerDescription = res.getString(R.string.day_picker_description);
mSelectDay = res.getString(R.string.select_day);
mYearPickerDescription = res.getString(R.string.year_picker_description);
mSelectYear = res.getString(R.string.select_year);
mAnimator = (AccessibleDateAnimator) view.findViewById(R.id.animator);
mAnimator.addView(mDayPickerView);
mAnimator.addView(mYearPickerView);
mAnimator.setDateMillis(mCalendar.getTimeInMillis());
// TODO: Replace with animation decided upon by the design team.
Animation animation = new AlphaAnimation(0.0f, 1.0f);
animation.setDuration(ANIMATION_DURATION);
mAnimator.setInAnimation(animation);
// TODO: Replace with animation decided upon by the design team.
Animation animation2 = new AlphaAnimation(1.0f, 0.0f);
animation2.setDuration(ANIMATION_DURATION);
mAnimator.setOutAnimation(animation2);
mDoneButton = (Button) view.findViewById(R.id.done);
mDoneButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
tryVibrate();
if (mCallBack != null) {
mCallBack.onDateSet(BottomSheetDatePickerDialog.this, mCalendar.get(Calendar.YEAR),
mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH));
}
dismiss();
}
});
mCancelButton = (Button) view.findViewById(R.id.cancel);
mCancelButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
}
});
// Setup action button text colors.
mCancelButton.setTextColor(mAccentColor);
mDoneButton.setTextColor(mAccentColor);
final int backgroundColor = mBackgroundColorSetAtRuntime
? mBackgroundColor : (mThemeDark ? mDarkGray : mWhite);
final int headerColor = mHeaderColorSetAtRuntime
? mHeaderColor : (mThemeDark ? mLightGray : mAccentColor);
// This is so the margin gets colored as well.
view.setBackgroundColor(backgroundColor);
mAnimator.setBackgroundColor(backgroundColor);
mDayPickerView.setAccentColor(mAccentColor);
view.findViewById(R.id.day_picker_selected_date_layout).setBackgroundColor(headerColor);
if (mThemeDark) {
final int selectableItemBg = ContextCompat.getColor(activity,
R.color.selectable_item_background_dark);
Utils.setColorControlHighlight(mCancelButton, selectableItemBg);
Utils.setColorControlHighlight(mDoneButton, selectableItemBg);
}
// Before setting any custom header text colors, check if the dark header text theme was
// requested and apply it.
if (mHeaderTextColorSetAtRuntime && mHeaderTextDark) {
final ColorStateList colors = ContextCompat.getColorStateList(activity,
R.color.date_picker_selector_light);
mDayOfWeekView.setTextColor(colors.getDefaultColor() /* text_color_secondary_light */);
mFirstTextView.setTextColor(colors);
mSecondTextView.setTextColor(colors);
}
// Apply the custom colors for the header texts, if applicable.
if (mHeaderTextColorSelected != 0 || mHeaderTextColorUnselected != 0) {
final int[][] states = {
{android.R.attr.state_selected},
{-android.R.attr.state_selected},
{ /* default state */}
};
final int selectedColor = mHeaderTextColorSelected != 0 ? mHeaderTextColorSelected
: (mHeaderTextDark ? mBlackText : mWhite);
final int unselectedColor = mHeaderTextColorUnselected != 0 ? mHeaderTextColorUnselected
: (mHeaderTextDark ? mBlackTextDisabled : mWhiteTextDisabled);
final int[] colors = { selectedColor, unselectedColor, unselectedColor };
final ColorStateList stateColors = new ColorStateList(states, colors);
mFirstTextView.setTextColor(stateColors);
mSecondTextView.setTextColor(stateColors);
}
// Apply the custom color for the day-of-week header text, if applicable.
if (mDayOfWeekHeaderTextColor != 0) {
mDayOfWeekView.setTextColor(mDayOfWeekHeaderTextColor);
}
determineLocale_MD_Y_Indices();
updateDisplay(false);
setCurrentView(currentView);
if (listPosition != -1) {
if (currentView == MONTH_AND_DAY_VIEW) {
mDayPickerView.postSetSelection(listPosition, false);
} else if (currentView == YEAR_VIEW) {
mYearPickerView.postSetSelectionFromTop(listPosition, listPositionOffset);
}
}
mDayPickerView.postSetupCurrentView(dayPickerCurrentView, false);
mHapticFeedbackController = new HapticFeedbackController(activity);
return view;
}
@Override
public void onResume() {
super.onResume();
mHapticFeedbackController.start();
}
@Override
public void onPause() {
super.onPause();
mHapticFeedbackController.stop();
}
private void setCurrentView(final int viewIndex) {
long millis = mCalendar.getTimeInMillis();
switch (viewIndex) {
case MONTH_AND_DAY_VIEW:
mDayPickerView.onDateChanged();
setCancelable(true);
if (mCurrentView != viewIndex) {
updateHeaderSelectedView(MONTH_AND_DAY_VIEW);
mAnimator.setDisplayedChild(MONTH_AND_DAY_VIEW);
mCurrentView = viewIndex;
}
String dayString = formatDate(mCalendar, DateUtils.FORMAT_SHOW_DATE);
mAnimator.setContentDescription(mDayPickerDescription + ": " + dayString);
Utils.tryAccessibilityAnnounce(mAnimator, mSelectDay);
break;
case YEAR_VIEW:
mYearPickerView.onDateChanged();
if (mCurrentView != viewIndex) {
updateHeaderSelectedView(YEAR_VIEW);
mAnimator.setDisplayedChild(YEAR_VIEW);
mCurrentView = viewIndex;
}
CharSequence yearString = YEAR_FORMAT.format(millis);
mAnimator.setContentDescription(mYearPickerDescription + ": " + yearString);
Utils.tryAccessibilityAnnounce(mAnimator, mSelectYear);
break;
}
}
private void updateHeaderSelectedView(final int viewIndex) {
switch (viewIndex) {
case MONTH_AND_DAY_VIEW:
mFirstTextView.setSelected(mLocaleMonthDayIndex == 0);
mSecondTextView.setSelected(mLocaleMonthDayIndex != 0);
break;
case YEAR_VIEW:
mFirstTextView.setSelected(mLocaleYearIndex == 0);
mSecondTextView.setSelected(mLocaleYearIndex != 0);
break;
}
}
/**
* Determine the relative positions of (MD) and Y according to the formatting style
* of the current locale.
*/
private void determineLocale_MD_Y_Indices() {
String formattedDate = formatMonthDayYear(mCalendar);
// Get the (MD) and Y parts of the formatted date in the current locale,
// so that we can compare their relative positions.
//
// You may be wondering why we need this method at all.
// "Just split() the formattedDate string around the year delimiter
// to get the two parts in an array already positioned correctly!
// Then setText() on mFirstTextView and mSecondTextView with the contents of that array!"
// That is harder than it sounds.
// Different locales use different year delimiters, and some don't use one at all.
// For example, a fully formatted date in the French locale is "30 juin 2009".
String monthAndDay = formatMonthAndDay(mCalendar);
String year = extractYearFromFormattedDate(formattedDate, monthAndDay);
// All locales format the M and D together; which comes
// first is not a necessary consideration for the comparison.
if (formattedDate.indexOf(monthAndDay) < formattedDate.indexOf(year/*not null*/)) {
mLocaleMonthDayIndex = 0;
mLocaleYearIndex = 1;
} else {
mLocaleYearIndex = 0;
mLocaleMonthDayIndex = 1;
}
}
private static String formatMonthDayYear(Calendar calendar) {
int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_MONTH | DateUtils.FORMAT_SHOW_YEAR;
return formatDate(calendar, flags);
}
private static String formatMonthAndDay(Calendar calendar) {
int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_MONTH | DateUtils.FORMAT_NO_YEAR;
return formatDate(calendar, flags);
}
private String extractYearFromFormattedDate(String formattedDate, String monthAndDay) {
String[] parts = formattedDate.split(monthAndDay);
for (String part : parts) {
// If the locale's date format is (MD)Y, then split(MD) = {"", Y}.
// If it is Y(MD), then split(MD) = {Y}. "Trailing empty strings are
// [...] not included in the resulting array."
if (!part.isEmpty()) {
return part;
}
}
// We will NEVER reach here, as long as the parameters are valid strings.
// We don't want this because it is not localized.
return YEAR_FORMAT.format(mCalendar.getTime());
}
private void updateDisplay(boolean announce) {
if (mDayOfWeekView != null) {
mDayOfWeekView.setText(mCalendar.getDisplayName(Calendar.DAY_OF_WEEK,
Calendar.LONG, Locale.getDefault()));
}
String fullDate = formatMonthDayYear(mCalendar);
String monthAndDay = formatMonthAndDay(mCalendar);
String year = YEAR_FORMAT.format(mCalendar.getTime());
int yearStart = fullDate.indexOf(year);
int yearEnd = yearStart + year.length();
int monthDayStart = fullDate.indexOf(monthAndDay);
int monthDayEnd = monthDayStart + monthAndDay.length();
boolean processed = false;
if (monthDayStart != -1 && yearStart != -1) {
if (mLocaleMonthDayIndex < mLocaleYearIndex) {
if (yearStart - monthDayEnd <= 2) {
monthAndDay = fullDate.substring(monthDayStart, yearStart);
year = fullDate.substring(yearStart, fullDate.length());
processed = true;
}
} else {
if (monthDayStart - yearEnd <= 2) {
year = fullDate.substring(yearStart, monthDayStart);
monthAndDay = fullDate.substring(monthDayStart, fullDate.length());
processed = true;
}
}
} else {
// Some locales format the standalone month-day or standalone year differently
// than it appears in the full date. For instance, Turkey is one such locale.
// TODO: You may want to consider making localized string resources of the
// pattern strings used to format the (MD) and (Y) parts separately.
//
// We can't compare the relative indices of (MD) and (Y) determined earlier,
// because the results are dubious if we're here.
// It is appropriate to assume yearStart != -1. The case where the raw year
// is NOT present in the full date string is hard to imagine. As such,
// even though monthDayStart == -1, we can still determine the relative indices
// of (MD) and (Y) as follows.
//
// If yearStart is non-zero positive, then we can probably guess monthDayStart
// comes before the former.
if (yearStart > 0) {
monthAndDay = fullDate.substring(0, yearStart);
year = fullDate.substring(yearStart, fullDate.length());
mLocaleMonthDayIndex = 0;
mLocaleYearIndex = 1;
} else {
year = fullDate.substring(0, yearEnd);
monthAndDay = fullDate.substring(yearEnd, fullDate.length());
mLocaleYearIndex = 0;
mLocaleMonthDayIndex = 1;
}
processed = true;
}
// Year delimiters longer than 2 characters, fall back on pre-2.1.1 implementation.
if (!processed) {
// The month-day is already formatted appropriately
year = extractYearFromFormattedDate(fullDate, monthAndDay);
}
mFirstTextView.setText(mLocaleMonthDayIndex == 0 ? monthAndDay : year);
mSecondTextView.setText(mLocaleMonthDayIndex == 0 ? year : monthAndDay);
// Accessibility.
long millis = mCalendar.getTimeInMillis();
mAnimator.setDateMillis(millis);
int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_NO_YEAR;
String monthAndDayText = formatDate(millis, flags);
mMonthDayYearView.setContentDescription(monthAndDayText);
if (announce) {
flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR;
String fullDateText = formatDate(millis, flags);
Utils.tryAccessibilityAnnounce(mAnimator, fullDateText);
}
}
/**
* Use this to set the day that a week should start on.
* @param startOfWeek A value from {@link Calendar#SUNDAY SUNDAY}
* through {@link Calendar#SATURDAY SATURDAY}
*/
public void setFirstDayOfWeek(int startOfWeek) {
if (startOfWeek < Calendar.SUNDAY || startOfWeek > Calendar.SATURDAY) {
throw new IllegalArgumentException("Value must be between Calendar.SUNDAY and " +
"Calendar.SATURDAY");
}
mWeekStart = startOfWeek;
if (mDayPickerView != null) {
mDayPickerView.onChange();
}
}
/**
* Sets the range of years to be displayed by this date picker. If a {@link #setMinDate(Calendar)
* minimal date} and/or {@link #setMaxDate(Calendar) maximal date} were set, dates in the
* specified range of years that lie outside of the minimal and maximal dates will be disallowed
* from being selected.
* <em>This does NOT change the minimal date's year or the maximal date's year.</em>
*
* @param startYear the start of the year range
* @param endYear the end of the year range
*/
public void setYearRange(int startYear, int endYear) {
if (endYear <= startYear) {
throw new IllegalArgumentException("Year end must be larger than year start");
}
mMinYear = startYear;
mMaxYear = endYear;
if (mDayPickerView != null) {
mDayPickerView.onChange();
}
}
/**
* Sets the minimal date that can be selected in this date picker. Dates before (but not including)
* the specified date will be disallowed from being selected.
*
* @param calendar a Calendar object set to the year, month, day desired as the mindate.
*/
public void setMinDate(Calendar calendar) {
mMinDate = calendar;
setYearRange(calendar.get(Calendar.YEAR), mMaxYear);
}
/**
* @return The minimal date supported by this date picker. Null if it has not been set.
*/
@Nullable
@Override
public Calendar getMinDate() {
return mMinDate;
}
/**
* Sets the maximal date that can be selected in this date picker. Dates after (but not including)
* the specified date will be disallowed from being selected.
*
* @param calendar a Calendar object set to the year, month, day desired as the maxdate.
*/
public void setMaxDate(Calendar calendar) {
mMaxDate = calendar;
setYearRange(mMinYear, calendar.get(Calendar.YEAR));
}
/**
* @return The maximal date supported by this date picker. Null if it has not been set.
*/
@Nullable
@Override
public Calendar getMaxDate() {
return mMaxDate;
}
public void setOnDateSetListener(OnDateSetListener listener) {
mCallBack = listener;
}
/**
* Set the color of the header text when it is selected.
*/
public final void setHeaderTextColorSelected(@ColorInt int color) {
mHeaderTextColorSelected = color;
}
/**
* Set the color of the header text when it is not selected.
*/
public final void setHeaderTextColorUnselected(@ColorInt int color) {
mHeaderTextColorUnselected = color;
}
/**
* Set the color of the day-of-week header text.
*/
public final void setDayOfWeekHeaderTextColor(@ColorInt int color) {
mDayOfWeekHeaderTextColor = color;
}
// If the newly selected month / year does not contain the currently selected day number,
// change the selected day number to the last day of the selected month or year.
// e.g. Switching from Mar to Apr when Mar 31 is selected -> Apr 30
// e.g. Switching from 2012 to 2013 when Feb 29, 2012 is selected -> Feb 28, 2013
private void adjustDayInMonthIfNeeded(int month, int year) {
int day = mCalendar.get(Calendar.DAY_OF_MONTH);
int daysInMonth = Utils.getDaysInMonth(month, year);
if (day > daysInMonth) {
mCalendar.set(Calendar.DAY_OF_MONTH, daysInMonth);
}
}
@Override
public void onClick(View v) {
tryVibrate();
if (v.getId() == R.id.date_picker_second_textview) {
setCurrentView(mLocaleMonthDayIndex == 0 ? YEAR_VIEW : MONTH_AND_DAY_VIEW);
} else if (v.getId() == R.id.date_picker_first_textview) {
setCurrentView(mLocaleMonthDayIndex == 0 ? MONTH_AND_DAY_VIEW : YEAR_VIEW);
}
}
@Override
public boolean onTouch(View v, MotionEvent event) {
if (mCurrentView == YEAR_VIEW && v == mYearPickerView
&& event.getY() >= mYearPickerView.getTop()
&& event.getY() <= mYearPickerView.getBottom()) {
setCancelable(false);
return mYearPickerView.onTouchEvent(event);
}
setCancelable(true);
return false;
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
setCancelable(scrollState == SCROLL_STATE_IDLE);
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
// Do nothing.
}
@Override
public void onYearSelected(int year) {
adjustDayInMonthIfNeeded(mCalendar.get(Calendar.MONTH), year);
mCalendar.set(Calendar.YEAR, year);
updatePickers();
setCurrentView(MONTH_AND_DAY_VIEW);
updateDisplay(true);
}
@Override
public void onDayOfMonthSelected(int year, int month, int day) {
mCalendar.set(Calendar.YEAR, year);
mCalendar.set(Calendar.MONTH, month);
mCalendar.set(Calendar.DAY_OF_MONTH, day);
updatePickers();
updateDisplay(true);
}
@Override
public void onMonthYearSelected(int month, int year) {
adjustDayInMonthIfNeeded(month, year);
mCalendar.set(Calendar.MONTH, month);
mCalendar.set(Calendar.YEAR, year);
updatePickers();
// Even though the MonthPickerView is already contained in this index,
// keep this call here for accessibility announcement of the new selection.
setCurrentView(MONTH_AND_DAY_VIEW);
updateDisplay(true);
}
private void updatePickers() {
Iterator<OnDateChangedListener> iterator = mListeners.iterator();
while (iterator.hasNext()) {
iterator.next().onDateChanged();
}
}
@Override
public CalendarDay getSelectedDay() {
if (mSelectedDay == null) {
mSelectedDay = new CalendarDay(mCalendar);
} else {
mSelectedDay.setDay(mCalendar.get(Calendar.YEAR),
mCalendar.get(Calendar.MONTH),
mCalendar.get(Calendar.DAY_OF_MONTH));
}
return mSelectedDay;
}
@Override
public int getMinYear() {
return mMinYear;
}
@Override
public int getMaxYear() {
return mMaxYear;
}
@Override
public int getFirstDayOfWeek() {
return mWeekStart;
}
@Override
public void registerOnDateChangedListener(OnDateChangedListener listener) {
mListeners.add(listener);
}
@Override
public void unregisterOnDateChangedListener(OnDateChangedListener listener) {
mListeners.remove(listener);
}
@Override
public void tryVibrate() {
mHapticFeedbackController.tryVibrate();
}
@Override
protected int contentLayout() {
return R.layout.date_picker_dialog;
}
}
| Save and restore custom header text colors on configuration change.
| bottomsheetpickers/src/main/java/com/philliphsu/bottomsheetpickers/date/BottomSheetDatePickerDialog.java | Save and restore custom header text colors on configuration change. |
|
Java | apache-2.0 | 757e166eaccda433a0627d2b5ac472c83f951d5d | 0 | apache/isis,apache/isis,apache/isis,apache/isis,apache/isis,apache/isis | /*
* 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.isis.core.metamodel.object;
import java.util.Optional;
import java.util.function.Supplier;
import org.springframework.lang.Nullable;
import org.apache.isis.applib.services.bookmark.Bookmark;
import org.apache.isis.commons.internal.exceptions._Exceptions;
import org.apache.isis.core.metamodel.context.MetaModelContext;
import org.apache.isis.core.metamodel.spec.ObjectSpecification;
/**
* (package private) specialization corresponding to {@link Specialization#UNSPECIFIED}
* @see ManagedObject.Specialization#UNSPECIFIED
*/
final class _ManagedObjectUnspecified
implements ManagedObject {
static final ManagedObject INSTANCE = new _ManagedObjectUnspecified();
@Override
public Specialization getSpecialization() {
return Specialization.UNSPECIFIED;
}
@Override
public ObjectSpecification getSpecification() {
throw _Exceptions.unsupportedOperation();
}
@Override
public Object getPojo() {
return null;
}
@Override
public Optional<Bookmark> getBookmark() {
return Optional.empty();
}
@Override
public Optional<Bookmark> getBookmarkRefreshed() {
return Optional.empty();
}
@Override
public boolean isBookmarkMemoized() {
return false;
}
@Override
public void refreshViewmodel(final @Nullable Supplier<Bookmark> bookmarkSupplier) {
}
@Override
public MetaModelContext getMetaModelContext() {
throw _Exceptions
.illegalArgument("Can only retrieve MetaModelContext from ManagedObjects "
+ "that have an ObjectSpecification.");
}
@Override
public Supplier<ManagedObject> asSupplier() {
return ()->this;
}
@Override
public void assertSpecIsInSyncWithPojo() {
}
}
| core/metamodel/src/main/java/org/apache/isis/core/metamodel/object/_ManagedObjectUnspecified.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.isis.core.metamodel.object;
import java.util.Optional;
import java.util.function.Supplier;
import org.springframework.lang.Nullable;
import org.apache.isis.applib.services.bookmark.Bookmark;
import org.apache.isis.commons.internal.exceptions._Exceptions;
import org.apache.isis.core.metamodel.context.MetaModelContext;
import org.apache.isis.core.metamodel.spec.ObjectSpecification;
/**
* (package private) specialization corresponding to {@link Specialization#PACKED}
* @see ManagedObject.Specialization#PACKED
*/
final class _ManagedObjectUnspecified
implements ManagedObject {
static final ManagedObject INSTANCE = new _ManagedObjectUnspecified();
@Override
public Specialization getSpecialization() {
return Specialization.UNSPECIFIED;
}
@Override
public ObjectSpecification getSpecification() {
throw _Exceptions.unsupportedOperation();
}
@Override
public Object getPojo() {
return null;
}
@Override
public Optional<Bookmark> getBookmark() {
return Optional.empty();
}
@Override
public Optional<Bookmark> getBookmarkRefreshed() {
return Optional.empty();
}
@Override
public boolean isBookmarkMemoized() {
return false;
}
@Override
public void refreshViewmodel(final @Nullable Supplier<Bookmark> bookmarkSupplier) {
}
@Override
public MetaModelContext getMetaModelContext() {
throw _Exceptions
.illegalArgument("Can only retrieve MetaModelContext from ManagedObjects "
+ "that have an ObjectSpecification.");
}
@Override
public Supplier<ManagedObject> asSupplier() {
return ()->this;
}
@Override
public void assertSpecIsInSyncWithPojo() {
}
}
| ISIS-3167: java-doc fix | core/metamodel/src/main/java/org/apache/isis/core/metamodel/object/_ManagedObjectUnspecified.java | ISIS-3167: java-doc fix |
|
Java | apache-2.0 | 96d6adf91ebe1117c8bacb65e59699f99fdc80aa | 0 | zoko7677/cordova-plugin-runagain,zoko7677/cordova-plugin-runagain,zoko7677/cordova-plugin-runagain | /*
Copyright 2013-2014 appPlant UG
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 zoko7677.cordova.plugin.background;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.IBinder;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class BackgroundMode extends CordovaPlugin {
// Event types for callbacks
private enum Event {
ACTIVATE, DEACTIVATE, FAILURE
}
// Plugin namespace
private static final String JS_NAMESPACE =
"cordova.plugins.backgroundMode";
// Flag indicates if the app is in background or foreground
private boolean inBackground = false;
// Flag indicates if the plugin is enabled or disabled
private boolean isDisabled = true;
// Flag indicates if the service is bind
private boolean isBind = false;
// Default settings for the notification
private static JSONObject defaultSettings = new JSONObject();
private Context mContext;
ForegroundService mService;
// Used to (un)bind the service to with the activity
private final ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
ForegroundService.ForegroundBinder binder =
(ForegroundService.ForegroundBinder) service;
mService = binder.getService();
}
@Override
public void onServiceDisconnected(ComponentName name) {
// Nothing to do here
}
};
/**
* Executes the request.
*
* @param action The action to execute.
* @param args The exec() arguments.
* @param callback The callback context used when
* calling back into JavaScript.
*
* @return
* Returning false results in a "MethodNotFound" error.
*
* @throws JSONException
*/
@Override
public boolean execute (String action, JSONArray args,
CallbackContext callback) throws JSONException {
if (action.equalsIgnoreCase("configure")) {
JSONObject settings = args.getJSONObject(0);
boolean update = args.getBoolean(1);
if (update) {
updateNotification(settings);
} else {
setDefaultSettings(settings);
}
return true;
}
if (action.equalsIgnoreCase("enable")) {
enableMode();
return true;
}
if (action.equalsIgnoreCase("disable")) {
disableMode();
return true;
}
return false;
}
/**
* Called when the system is about to start resuming a previous activity.
*
* @param multitasking
* Flag indicating if multitasking is turned on for app
*/
@Override
public void onPause(boolean multitasking) {
super.onPause(multitasking);
inBackground = true;
startService();
// Starting your app...
//Log.d("Cordova AppStarter", "STARTING APP...");
//SharedPreferences sp = mContext.getSharedPreferences("BackgroundMode", Context.MODE_PRIVATE);
String packageName = mContext.getPackageName();
webView.loadUrl("javascript:alert('"+packageName+"');");
//String className = sp.getString("class", "");
/*if( !className.equals("") ){
//Log.d("Cordova AppStarter", className);
Intent serviceIntent = new Intent();
serviceIntent.setClassName(mContext, packageName + "." + className);
//serviceIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//serviceIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
mContext.startActivity(serviceIntent);
}*/
Intent LaunchIntent = cordova.getActivity().getPackageManager().getLaunchIntentForPackage(packageName + "." + className);
}
/**
* Called when the activity will start interacting with the user.
*
* @param multitasking
* Flag indicating if multitasking is turned on for app
*/
@Override
public void onResume(boolean multitasking) {
super.onResume(multitasking);
inBackground = false;
stopService();
}
/**
* Called when the activity will be destroyed.
*/
@Override
public void onDestroy() {
//super.onDestroy();
//stopService();
//Open aplication edit by zoko7677
SharedPreferences sp = mContext.getSharedPreferences("BackgroundMode", Context.MODE_PRIVATE);
String packageName = mContext.getPackageName();
String className = sp.getString("BackgroundMode", "");
webView.loadUrl("javascript:alert('"+packageName+"');");
if( !className.equals("") ){
Intent serviceIntent = new Intent();
serviceIntent.setClassName(mContext, packageName + "." + className);
serviceIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
serviceIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
mContext.startActivity(serviceIntent);
}
}
/**
* Enable the background mode.
*/
private void enableMode() {
isDisabled = false;
if (inBackground) {
startService();
}
}
/**
* Disable the background mode.
*/
private void disableMode() {
stopService();
isDisabled = true;
}
/**
* Update the default settings for the notification.
*
* @param settings
* The new default settings
*/
private void setDefaultSettings(JSONObject settings) {
defaultSettings = settings;
}
/**
* The settings for the new/updated notification.
*
* @return
* updateSettings if set or default settings
*/
protected static JSONObject getSettings() {
return defaultSettings;
}
/**
* Update the notification.
*
* @param settings
* The config settings
*/
private void updateNotification(JSONObject settings) {
if (isBind) {
mService.updateNotification(settings);
}
}
/**
* Bind the activity to a background service and put them into foreground
* state.
*/
private void startService() {
Activity context = cordova.getActivity();
if (isDisabled || isBind)
return;
Intent intent = new Intent(
context, ForegroundService.class);
try {
context.bindService(intent,
connection, Context.BIND_AUTO_CREATE);
fireEvent(Event.ACTIVATE, null);
context.startService(intent);
} catch (Exception e) {
fireEvent(Event.FAILURE, e.getMessage());
}
isBind = true;
}
/**
* Bind the activity to a background service and put them into foreground
* state.
*/
private void stopService() {
Activity context = cordova.getActivity();
Intent intent = new Intent(
context, ForegroundService.class);
if (!isBind)
return;
fireEvent(Event.DEACTIVATE, null);
context.unbindService(connection);
context.stopService(intent);
isBind = false;
}
/**
* Fire vent with some parameters inside the web view.
*
* @param event
* The name of the event
* @param params
* Optional arguments for the event
*/
private void fireEvent (Event event, String params) {
String eventName;
switch (event) {
case ACTIVATE:
eventName = "activate"; break;
case DEACTIVATE:
eventName = "deactivate"; break;
default:
eventName = "failure";
}
String active = event == Event.ACTIVATE ? "true" : "false";
String flag = String.format("%s._isActive=%s;",
JS_NAMESPACE, active);
String fn = String.format("setTimeout('%s.on%s(%s)',0);",
JS_NAMESPACE, eventName, params);
final String js = flag + fn;
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
webView.loadUrl("javascript:" + js);
}
});
}
}
| src/android/BackgroundMode.java | /*
Copyright 2013-2014 appPlant UG
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 zoko7677.cordova.plugin.background;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.IBinder;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class BackgroundMode extends CordovaPlugin {
// Event types for callbacks
private enum Event {
ACTIVATE, DEACTIVATE, FAILURE
}
// Plugin namespace
private static final String JS_NAMESPACE =
"cordova.plugins.backgroundMode";
// Flag indicates if the app is in background or foreground
private boolean inBackground = false;
// Flag indicates if the plugin is enabled or disabled
private boolean isDisabled = true;
// Flag indicates if the service is bind
private boolean isBind = false;
// Default settings for the notification
private static JSONObject defaultSettings = new JSONObject();
private Context mContext;
ForegroundService mService;
// Used to (un)bind the service to with the activity
private final ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
ForegroundService.ForegroundBinder binder =
(ForegroundService.ForegroundBinder) service;
mService = binder.getService();
}
@Override
public void onServiceDisconnected(ComponentName name) {
// Nothing to do here
}
};
/**
* Executes the request.
*
* @param action The action to execute.
* @param args The exec() arguments.
* @param callback The callback context used when
* calling back into JavaScript.
*
* @return
* Returning false results in a "MethodNotFound" error.
*
* @throws JSONException
*/
@Override
public boolean execute (String action, JSONArray args,
CallbackContext callback) throws JSONException {
if (action.equalsIgnoreCase("configure")) {
JSONObject settings = args.getJSONObject(0);
boolean update = args.getBoolean(1);
if (update) {
updateNotification(settings);
} else {
setDefaultSettings(settings);
}
return true;
}
if (action.equalsIgnoreCase("enable")) {
enableMode();
return true;
}
if (action.equalsIgnoreCase("disable")) {
disableMode();
return true;
}
return false;
}
/**
* Called when the system is about to start resuming a previous activity.
*
* @param multitasking
* Flag indicating if multitasking is turned on for app
*/
@Override
public void onPause(boolean multitasking) {
super.onPause(multitasking);
inBackground = true;
startService();
// Starting your app...
//Log.d("Cordova AppStarter", "STARTING APP...");
//SharedPreferences sp = mContext.getSharedPreferences("BackgroundMode", Context.MODE_PRIVATE);
String packageName = mContext.getPackageName();
webView.loadUrl("javascript:alert('"+packageName+"');");
String className = sp.getString("class", "");
/*if( !className.equals("") ){
//Log.d("Cordova AppStarter", className);
Intent serviceIntent = new Intent();
serviceIntent.setClassName(mContext, packageName + "." + className);
//serviceIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//serviceIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
mContext.startActivity(serviceIntent);
}*/
Intent LaunchIntent = cordova.getActivity().getPackageManager().getLaunchIntentForPackage(packageName + "." + className);
}
/**
* Called when the activity will start interacting with the user.
*
* @param multitasking
* Flag indicating if multitasking is turned on for app
*/
@Override
public void onResume(boolean multitasking) {
super.onResume(multitasking);
inBackground = false;
stopService();
}
/**
* Called when the activity will be destroyed.
*/
@Override
public void onDestroy() {
//super.onDestroy();
//stopService();
//Open aplication edit by zoko7677
SharedPreferences sp = mContext.getSharedPreferences("BackgroundMode", Context.MODE_PRIVATE);
String packageName = mContext.getPackageName();
String className = sp.getString("BackgroundMode", "");
webView.loadUrl("javascript:alert('"+packageName+"');");
if( !className.equals("") ){
Intent serviceIntent = new Intent();
serviceIntent.setClassName(mContext, packageName + "." + className);
serviceIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
serviceIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
mContext.startActivity(serviceIntent);
}
}
/**
* Enable the background mode.
*/
private void enableMode() {
isDisabled = false;
if (inBackground) {
startService();
}
}
/**
* Disable the background mode.
*/
private void disableMode() {
stopService();
isDisabled = true;
}
/**
* Update the default settings for the notification.
*
* @param settings
* The new default settings
*/
private void setDefaultSettings(JSONObject settings) {
defaultSettings = settings;
}
/**
* The settings for the new/updated notification.
*
* @return
* updateSettings if set or default settings
*/
protected static JSONObject getSettings() {
return defaultSettings;
}
/**
* Update the notification.
*
* @param settings
* The config settings
*/
private void updateNotification(JSONObject settings) {
if (isBind) {
mService.updateNotification(settings);
}
}
/**
* Bind the activity to a background service and put them into foreground
* state.
*/
private void startService() {
Activity context = cordova.getActivity();
if (isDisabled || isBind)
return;
Intent intent = new Intent(
context, ForegroundService.class);
try {
context.bindService(intent,
connection, Context.BIND_AUTO_CREATE);
fireEvent(Event.ACTIVATE, null);
context.startService(intent);
} catch (Exception e) {
fireEvent(Event.FAILURE, e.getMessage());
}
isBind = true;
}
/**
* Bind the activity to a background service and put them into foreground
* state.
*/
private void stopService() {
Activity context = cordova.getActivity();
Intent intent = new Intent(
context, ForegroundService.class);
if (!isBind)
return;
fireEvent(Event.DEACTIVATE, null);
context.unbindService(connection);
context.stopService(intent);
isBind = false;
}
/**
* Fire vent with some parameters inside the web view.
*
* @param event
* The name of the event
* @param params
* Optional arguments for the event
*/
private void fireEvent (Event event, String params) {
String eventName;
switch (event) {
case ACTIVATE:
eventName = "activate"; break;
case DEACTIVATE:
eventName = "deactivate"; break;
default:
eventName = "failure";
}
String active = event == Event.ACTIVATE ? "true" : "false";
String flag = String.format("%s._isActive=%s;",
JS_NAMESPACE, active);
String fn = String.format("setTimeout('%s.on%s(%s)',0);",
JS_NAMESPACE, eventName, params);
final String js = flag + fn;
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
webView.loadUrl("javascript:" + js);
}
});
}
}
| Update BackgroundMode.java | src/android/BackgroundMode.java | Update BackgroundMode.java |
|
Java | apache-2.0 | 85c56795ceff49b773548fc3e02be8ab1e08563d | 0 | osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi,osgi/osgi | package org.osgi.impl.service.discovery.slp;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;
import org.osgi.service.discovery.ServiceEndpointDescription;
import ch.ethz.iks.slp.ServiceLocationException;
import ch.ethz.iks.slp.ServiceURL;
/**
*
* SLP encoding:
*
* <code>service:osgi:/my/company/MyService://<protocol://><host><:port><?path></code>
*
* In the <code>path</code> part service properties are listed.
*
* SLP Spec: http://www.ietf.org/rfc/rfc2608.txt
*
* @version $Revision$
*/
public class SLPServiceDescriptionAdapter implements ServiceEndpointDescription {
public static final String UnknownVersion = "*";
// reserved are: `(' / `)' / `,' / `\' / `!' / `<' / `=' / `>' / `~' / CTL
// TODO: handle CTL
public static final String RESERVED_CHARS_IN_ATTR_VALUES = "(),\\!<>=~";
// RFC2608: Any character except reserved, * / CR / LF / HTAB / `_'.
public static final String RESERVED_CHARS_IN_ATTR_KEYS = RESERVED_CHARS_IN_ATTR_VALUES
+ '*' + 0x0D + 0x0A + 0x09 + '_';
public static final String ESCAPING_CHARACTER = "\\";
private Map/* <String, String> */javaInterfaceAndFilters;
private Map/* <String, String> */javaAndEndpointInterfaces;
private Map/* <String, Object> */properties;
// Java interfaces and associated ServiceURLs. Each interface has its own
// ServiceURL.
private Map/* <String, ServiceURL> */serviceURLs;
public SLPServiceDescriptionAdapter(final Map javaInterfaceAndFilters,
final Map javaAndEndpointInterfaces, final Map properties)
throws ServiceLocationException {
// check the java interface map for validity
if (javaInterfaceAndFilters == null) {
throw new IllegalArgumentException(
"Given set of Java interfaces must not be null.");
}
if (javaInterfaceAndFilters.size() <= 0) {
throw new IllegalArgumentException(
"Given set of Java interfaces must contain at least one service interface name.");
}
// create and copy maps
this.javaInterfaceAndFilters = new HashMap(javaInterfaceAndFilters);
this.javaAndEndpointInterfaces = new HashMap();
if (javaAndEndpointInterfaces != null)
this.javaAndEndpointInterfaces.putAll(javaAndEndpointInterfaces);
this.properties = new HashMap();
if (properties != null)
this.properties.putAll(properties);
addInterfacesAndVersionsToProperties();
}
public SLPServiceDescriptionAdapter(final ServiceURL serviceURL) {
this.javaInterfaceAndFilters = new HashMap();
this.javaAndEndpointInterfaces = new HashMap();
this.properties = new HashMap();
this.serviceURLs = new HashMap();
String interfaceName = retrieveDataFromServiceURL(serviceURL,
javaInterfaceAndFilters, javaAndEndpointInterfaces, properties);
this.serviceURLs.put(interfaceName, serviceURL);
}
private void addInterfacesAndVersionsToProperties()
throws ServiceLocationException {
// create arrays for java-interface, version and endpoint-interface
// info. Array indexes correlate.
int interfaceNmb = this.javaInterfaceAndFilters.size();
String[] javaInterfaces = new String[interfaceNmb];
String[] versions = new String[interfaceNmb];
String[] endpointInterfaces = this.javaAndEndpointInterfaces.size() > 0 ? new String[interfaceNmb]
: null;
// Create a service url for each interface and gather also version and
// endpoint-interface information.
this.serviceURLs = new HashMap();
Iterator intfIterator = this.javaInterfaceAndFilters.keySet()
.iterator();
for (int i = 0; intfIterator.hasNext(); i++) {
Object currentInterface = intfIterator.next();
if (currentInterface instanceof String) {
javaInterfaces[i] = (String) currentInterface;
versions[i] = (String) this.javaInterfaceAndFilters
.get(javaInterfaces[i]);
if (endpointInterfaces != null) {
endpointInterfaces[i] = (String) this.javaAndEndpointInterfaces
.get(javaInterfaces[i]);
}
this.serviceURLs.put(javaInterfaces[i], createServiceURL(
javaInterfaces[i], versions[i],
endpointInterfaces != null ? endpointInterfaces[i]
: null, this.properties));
} else {
// TODO: throw exception
}
}
// added version and endpoint-interface information to the properties
this.properties.put(ServiceEndpointDescription.PROP_KEY_INTERFACE_NAME,
javaInterfaces);
this.properties.put(ServiceEndpointDescription.PROP_KEY_VERSION,
versions);
if (this.javaAndEndpointInterfaces.size() > 0) {
this.properties
.put(
ServiceEndpointDescription.PROP_KEY_PROTOCOL_SPECIFIC_INTERFACE_NAME,
endpointInterfaces);
}
}
public Map getProperties() {
return properties;
}
public Object getProperty(final String key) {
return properties.get(key);
}
public Collection keys() {
return properties.keySet();
}
public ServiceURL getServiceURL(String interfaceName) {
return (ServiceURL) serviceURLs.get(interfaceName);
}
public String toString() {
StringBuffer sb = new StringBuffer("Service:\n");
Iterator intfIterator = this.javaInterfaceAndFilters.keySet()
.iterator();
while (intfIterator.hasNext()) {
String interfaceName = (String) intfIterator.next();
sb.append("interface=").append(interfaceName).append("\n");
sb.append("version=").append(
this.javaInterfaceAndFilters.get(interfaceName)).append(
"\n");
ServiceURL svcURL = getServiceURL(interfaceName);
sb.append("serviceURL=").append(
svcURL != null ? svcURL.toString() : "").append("\n");
}
sb.append("properties=\n");
String key;
Object value;
for (Iterator i = properties.keySet().iterator(); i.hasNext();) {
key = (String) i.next();
value = properties.get(key);
if (value == null) {
value = "<null>";
}
sb.append(key).append("=").append(value.toString()).append("\n");
}
return sb.toString();
}
/**
*
* @see org.osgi.service.discovery.ServiceEndpointDescription#getInterfaceNames()
*/
public String[] getInterfaceNames() {
return (String[]) this.javaInterfaceAndFilters.keySet().toArray(
new String[1]);
}
/**
*
* @see org.osgi.service.discovery.ServiceEndpointDescription#getProtocolSpecificInterfaceName(java.lang.String)
*/
public String getProtocolSpecificInterfaceName(String interfaceName) {
return (String) this.javaAndEndpointInterfaces.get(interfaceName);
}
/**
*
* @see org.osgi.service.discovery.ServiceEndpointDescription#getVersion(java.lang.String)
*/
public String getVersion(String interfaceName) {
return (String) this.javaInterfaceAndFilters.get(interfaceName);
}
/**
*
* @see org.osgi.impl.service.discovery.ProtocolSpecificServiceDescription#getLocation()
*/
public URL getLocation() {
try {
return new URL((String) properties
.get(ServiceEndpointDescription.PROP_KEY_SERVICE_LOCATION));
} catch (MalformedURLException e) {
e.printStackTrace();
}
return null;
}
/**
*
* @see org.osgi.impl.service.discovery.ProtocolSpecificServiceDescription#getPropertyKeys()
*/
public Collection getPropertyKeys() {
return properties.keySet();
}
/**
*
* @param key
* @param value
*/
public void addProperty(String key, Object value) {
properties.put(key, value);
}
/**
*
* @param props
*/
public void setProperties(Map props) {
properties = props;
}
/**
*
* @param interfaceName
* @param version
* @param endpointInterface
* @param properties
* @return
* @throws ServiceLocationException
*/
public static ServiceURL createServiceURL(String interfaceName,
String version, String endpointInterface, Map properties)
throws ServiceLocationException {
String interf = convertJavaInterface2Path(interfaceName);
String path = createStringFromProperties(properties);
// add interface as property to enable LDAP filtering on it
path = appendPropertyToURLPath(path,
ServiceEndpointDescription.PROP_KEY_INTERFACE_NAME,
interfaceName);
if (version != null)
path = appendPropertyToURLPath(path,
ServiceEndpointDescription.PROP_KEY_VERSION, version);
if (endpointInterface != null)
path = appendPropertyToURLPath(
path,
ServiceEndpointDescription.PROP_KEY_PROTOCOL_SPECIFIC_INTERFACE_NAME,
endpointInterface);
String protocol = null;
String host = null;
String port = null;
Integer lifeTime = null;
// init from properties if given
if (properties != null) {
protocol = (String) properties.get("protocol");
host = (String) properties.get("host");
port = (String) properties.get("port");
lifeTime = (Integer) properties.get("lifetime");
}
if (host == null) {
String hostname = null;
try {
InetAddress addr = InetAddress.getLocalHost();
// Get hostname
hostname = addr.getHostName();
if (hostname == null || hostname.equals("")) {
// if hostname is NULL or empty string
// set hostname to ip address
hostname = addr.getHostAddress();
}
host = hostname;
} catch (UnknownHostException e) {
e.printStackTrace();
// TODO log and rethrow
}
}
int lifetime = lifeTime != null ? lifeTime.intValue()
: ServiceURL.LIFETIME_DEFAULT;
StringBuffer buff = new StringBuffer();
buff.append("service:osgi");
buff.append(interf);
buff.append((protocol != null ? protocol + "://" : "://"));
buff.append(host);
buff.append((port != null ? ":" + port : ""));
buff.append("/");
buff.append(path);
return new ServiceURL(buff.toString(), lifetime);
}
/**
*
* @param serviceURL
* @param javaInterfaceAndFilters
* @param javaAndEndpointInterfaces
* @param properties
* @return
*/
public static String retrieveDataFromServiceURL(
final ServiceURL serviceURL,
final Map/* <String, String> */javaInterfaceAndFilters,
final Map/* <String, String> */javaAndEndpointInterfaces,
final Map/* <String, Object> */properties) {
// retrieve main interface
String interfaceName = convertPath2JavaInterface(serviceURL
.getServiceType().getConcreteTypeName());
if (interfaceName == null) {
throw new IllegalArgumentException(
"Interface information is missing!");
}
// Retrieve additional properties from SLP ServiceURL itself
properties.put("slp.serviceURL", serviceURL);
properties.put("type", serviceURL.getServiceType().toString());
if (serviceURL.getHost() != null) {
properties.put("host", serviceURL.getHost());
}
if (serviceURL.getPort() != 0) {
properties.put("port", new Integer(serviceURL.getPort()));
}
if (serviceURL.getProtocol() != null) {
properties.put("protocol", serviceURL.getProtocol());
}
properties.put("lifetime", new Integer(serviceURL.getLifetime()));
// retrieve properties from ServiceURL attributes
retrievePropertiesFromPath(serviceURL.getURLPath(), properties);
// Get version info
String version;
Object versionsValue = properties
.get(ServiceEndpointDescription.PROP_KEY_VERSION);
if (versionsValue instanceof String) {
version = (String) versionsValue;
} else {
// TODO log error
version = SLPServiceDescriptionAdapter.UnknownVersion;
}
javaInterfaceAndFilters.put(interfaceName, version);
// Put interface and version information to properties since base for matching
properties.put(ServiceEndpointDescription.PROP_KEY_INTERFACE_NAME,
new String[] { interfaceName });
properties.put(ServiceEndpointDescription.PROP_KEY_VERSION,
new String[] { version });
// Get endpoint-interface if it exists
Object endpointInterfacesValue = properties
.get(ServiceEndpointDescription.PROP_KEY_PROTOCOL_SPECIFIC_INTERFACE_NAME);
if (endpointInterfacesValue instanceof String) {
javaAndEndpointInterfaces.put(interfaceName,
endpointInterfacesValue);
}
// return main interface name
return interfaceName;
}
/**
*
* @param path
* @param properties
*/
public static void retrievePropertiesFromPath(String path,
final Map properties) {
try {
if (path != null && path.trim() != "") {
path = path.substring(2); // strip off the "/?" in front of
// the
// path
StringTokenizer st = new StringTokenizer(path, "=,");
String key;
String value;
try {
while (st.hasMoreTokens()) {
key = deescapeReservedChars(st.nextToken());
if (st.hasMoreTokens())
value = st.nextToken();
else
value = "";
//TODO check whether got list of values --> create array. This should be done befor deescaping chars.
value = deescapeReservedChars(value);
properties.put(key, value);
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
return;
}
}
/**
*
* @param javaInterfaceName
* @return
*/
public static String convertJavaInterface2Path(
final String javaInterfaceName) {
return javaInterfaceName != null ? ":"
+ javaInterfaceName.replace('.', '/') : "";
}
/**
*
* @param interfaceNameEncodedAsPath
* @return
*/
public static String convertPath2JavaInterface(
final String interfaceNameEncodedAsPath) {
return interfaceNameEncodedAsPath != null ? interfaceNameEncodedAsPath
.replace('/', '.') : null;
}
/**
*
* @param properties
* @return
*/
private static String createStringFromProperties(final Map properties) {
StringBuffer sb = new StringBuffer();
String key = null;
Object value = null;
if ((properties != null) && !properties.isEmpty()) {
for (Iterator i = properties.keySet().iterator(); i.hasNext();) {
key = (String) i.next();
value = properties.get(key);
appendPropertyToURLPath(sb, key, value);
}
}
return sb.toString();
}
/**
*
* @param path
* @param key
* @param value
*/
private static void appendPropertyToURLPath(StringBuffer path, String key,
Object value) {
if (path == null)
throw new IllegalArgumentException("Given StringBuffer is null.");
if (path.length() == 0) {
path.append("?");
} else {
path.append(",");
}
if (value == null) {
value = "<null>";
}
path.append(escapeReservedChars(key,
SLPServiceDescriptionAdapter.RESERVED_CHARS_IN_ATTR_KEYS));
path.append("=");
if (value instanceof Object[]) {
Object[] arrayValue = (Object[]) value;
for (int i = 0; i < arrayValue.length;) {
path
.append(escapeReservedChars(
arrayValue[i].toString(),
SLPServiceDescriptionAdapter.RESERVED_CHARS_IN_ATTR_VALUES));
if (++i != arrayValue.length)
path.append(",");
}
} else
path
.append(escapeReservedChars(
value.toString(),
SLPServiceDescriptionAdapter.RESERVED_CHARS_IN_ATTR_VALUES));
}
/**
*
* @param path
* @param key
* @param value
* @return
*/
public static String appendPropertyToURLPath(String path, String key,
Object value) {
StringBuffer buffer = new StringBuffer(path);
appendPropertyToURLPath(buffer, key, value);
return buffer.toString();
}
/**
* TODO: create test case using reserved chars
*
* @param value
* @param reservedChars
* @return
*/
public static String deescapeReservedChars(String value) {
// tokenize escapedchars as extra chars
StringTokenizer tokenizer = new StringTokenizer(value,
SLPServiceDescriptionAdapter.ESCAPING_CHARACTER);
StringBuffer buffer = new StringBuffer(tokenizer.nextToken());
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
if (token.length() >= 2) {
buffer.append((char)Integer.parseInt(token.substring(0, 2), 16));
buffer.append(token.substring(2));
}
}
return buffer.toString();
}
/**
* TODO: create test case using reserved chars
*
* @param value
* @param reservedChars
* @return
*/
public static String escapeReservedChars(String value, String reservedChars) {
// tokenize reserved chars as extra chars
StringTokenizer tokenizer = new StringTokenizer(value, reservedChars,
true);
StringBuffer buffer = new StringBuffer();
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
if (token.length() == 1 && reservedChars.indexOf(token.charAt(0)) != -1)
{
buffer.append(ESCAPING_CHARACTER
+ Integer.toHexString(token.charAt(0)));
} else {
buffer.append(token);
}
}
return buffer.toString();
}
/**
*
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(final Object serviceDescription) {
if (!(serviceDescription instanceof ServiceEndpointDescription)) {
return false;
}
ServiceEndpointDescription descr = (ServiceEndpointDescription) serviceDescription;
if (properties != null && descr.getProperties() == null) {
return false;
}
if (properties == null && descr.getProperties() != null) {
return false;
}
if (properties == null && descr.getProperties() == null) {
return true;
}
// if (properties.size() != descr.getProperties().size()) {
// return false;
// }
Iterator it = properties.keySet().iterator();
while (it.hasNext()) {
String key = (String) it.next();
if (descr.getProperties().containsKey(key)) {
if (descr.getProperty(key) instanceof String
&& (properties.get(key) instanceof String[])) {
if (!properties.get(key).toString().equals(
(descr.getProperty(key)))) {
return false;
}
} else {
if (!properties.get(key).equals(descr.getProperty(key))) {
return false;
}
}
} else {
return false;
}
}
return true;
}
/**
*
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
return super.hashCode();
}
}
| org.osgi.impl.service.discovery/src/org/osgi/impl/service/discovery/slp/SLPServiceDescriptionAdapter.java | package org.osgi.impl.service.discovery.slp;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;
import org.osgi.service.discovery.ServiceEndpointDescription;
import ch.ethz.iks.slp.ServiceLocationException;
import ch.ethz.iks.slp.ServiceURL;
/**
*
* SLP encoding:
*
* <code>service:osgi:/my/company/MyService://<protocol://><host><:port><?path></code>
*
* In the <code>path</code> part service properties are listed.
*
* SLP Spec: http://www.ietf.org/rfc/rfc2608.txt
*
* @version $Revision$
*/
public class SLPServiceDescriptionAdapter implements ServiceEndpointDescription {
public static final String UnknownVersion = "*";
// reserved are: `(' / `)' / `,' / `\' / `!' / `<' / `=' / `>' / `~' / CTL
// TODO: handle CTL
public static final String RESERVED_CHARS_IN_ATTR_VALUES = "(),\\!<>=~";
// RFC2608: Any character except reserved, * / CR / LF / HTAB / `_'.
public static final String RESERVED_CHARS_IN_ATTR_KEYS = RESERVED_CHARS_IN_ATTR_VALUES
+ '*' + 0x0D + 0x0A + 0x09 + '_';
public static final String ESCAPING_CHARACTER = "\\";
private Map/* <String, String> */javaInterfaceAndFilters;
private Map/* <String, String> */javaAndEndpointInterfaces;
private Map/* <String, Object> */properties;
// Java interfaces and associated ServiceURLs. Each interface has its own
// ServiceURL.
private Map/* <String, ServiceURL> */serviceURLs;
public SLPServiceDescriptionAdapter(final Map javaInterfaceAndFilters,
final Map javaAndEndpointInterfaces, final Map properties)
throws ServiceLocationException {
// check the java interface map for validity
if (javaInterfaceAndFilters == null) {
throw new IllegalArgumentException(
"Given set of Java interfaces must not be null.");
}
if (javaInterfaceAndFilters.size() <= 0) {
throw new IllegalArgumentException(
"Given set of Java interfaces must contain at least one service interface name.");
}
// create and copy maps
this.javaInterfaceAndFilters = new HashMap(javaInterfaceAndFilters);
this.javaAndEndpointInterfaces = new HashMap();
if (javaAndEndpointInterfaces != null)
this.javaAndEndpointInterfaces.putAll(javaAndEndpointInterfaces);
this.properties = new HashMap();
if (properties != null)
this.properties.putAll(properties);
addInterfacesAndVersionsToProperties();
}
public SLPServiceDescriptionAdapter(final ServiceURL serviceURL) {
this.javaInterfaceAndFilters = new HashMap();
this.javaAndEndpointInterfaces = new HashMap();
this.properties = new HashMap();
this.serviceURLs = new HashMap();
String interfaceName = retrieveDataFromServiceURL(serviceURL,
javaInterfaceAndFilters, javaAndEndpointInterfaces, properties);
this.serviceURLs.put(interfaceName, serviceURL);
}
private void addInterfacesAndVersionsToProperties()
throws ServiceLocationException {
// create arrays for java-interface, version and endpoint-interface
// info. Array indexes correlate.
int interfaceNmb = this.javaInterfaceAndFilters.size();
String[] javaInterfaces = new String[interfaceNmb];
String[] versions = new String[interfaceNmb];
String[] endpointInterfaces = this.javaAndEndpointInterfaces.size() > 0 ? new String[interfaceNmb]
: null;
// Create a service url for each interface and gather also version and
// endpoint-interface information.
this.serviceURLs = new HashMap();
Iterator intfIterator = this.javaInterfaceAndFilters.keySet()
.iterator();
for (int i = 0; intfIterator.hasNext(); i++) {
Object currentInterface = intfIterator.next();
if (currentInterface instanceof String) {
javaInterfaces[i] = (String) currentInterface;
versions[i] = (String) this.javaInterfaceAndFilters
.get(javaInterfaces[i]);
if (endpointInterfaces != null) {
endpointInterfaces[i] = (String) this.javaAndEndpointInterfaces
.get(javaInterfaces[i]);
}
this.serviceURLs.put(javaInterfaces[i], createServiceURL(
javaInterfaces[i], versions[i],
endpointInterfaces != null ? endpointInterfaces[i]
: null, this.properties));
} else {
// TODO: throw exception
}
}
// added version and endpoint-interface information to the properties
this.properties.put(ServiceEndpointDescription.PROP_KEY_INTERFACE_NAME,
javaInterfaces);
this.properties.put(ServiceEndpointDescription.PROP_KEY_VERSION,
versions);
if (this.javaAndEndpointInterfaces.size() > 0) {
this.properties
.put(
ServiceEndpointDescription.PROP_KEY_PROTOCOL_SPECIFIC_INTERFACE_NAME,
endpointInterfaces);
}
}
public Map getProperties() {
return properties;
}
public Object getProperty(final String key) {
return properties.get(key);
}
public Collection keys() {
return properties.keySet();
}
public ServiceURL getServiceURL(String interfaceName) {
return (ServiceURL) serviceURLs.get(interfaceName);
}
public String toString() {
StringBuffer sb = new StringBuffer("Service:\n");
Iterator intfIterator = this.javaInterfaceAndFilters.keySet()
.iterator();
while (intfIterator.hasNext()) {
String interfaceName = (String) intfIterator.next();
sb.append("interface=").append(interfaceName).append("\n");
sb.append("version=").append(
this.javaInterfaceAndFilters.get(interfaceName)).append(
"\n");
ServiceURL svcURL = getServiceURL(interfaceName);
sb.append("serviceURL=").append(
svcURL != null ? svcURL.toString() : "").append("\n");
}
sb.append("properties=\n");
String key;
Object value;
for (Iterator i = properties.keySet().iterator(); i.hasNext();) {
key = (String) i.next();
value = properties.get(key);
if (value == null) {
value = "<null>";
}
sb.append(key).append("=").append(value.toString()).append("\n");
}
return sb.toString();
}
/**
*
* @see org.osgi.service.discovery.ServiceEndpointDescription#getInterfaceNames()
*/
public String[] getInterfaceNames() {
return (String[]) this.javaInterfaceAndFilters.keySet().toArray(
new String[1]);
}
/**
*
* @see org.osgi.service.discovery.ServiceEndpointDescription#getProtocolSpecificInterfaceName(java.lang.String)
*/
public String getProtocolSpecificInterfaceName(String interfaceName) {
return (String) this.javaAndEndpointInterfaces.get(interfaceName);
}
/**
*
* @see org.osgi.service.discovery.ServiceEndpointDescription#getVersion(java.lang.String)
*/
public String getVersion(String interfaceName) {
return (String) this.javaInterfaceAndFilters.get(interfaceName);
}
/**
*
* @see org.osgi.impl.service.discovery.ProtocolSpecificServiceDescription#getLocation()
*/
public URL getLocation() {
try {
return new URL((String) properties
.get(ServiceEndpointDescription.PROP_KEY_SERVICE_LOCATION));
} catch (MalformedURLException e) {
e.printStackTrace();
}
return null;
}
/**
*
* @see org.osgi.impl.service.discovery.ProtocolSpecificServiceDescription#getPropertyKeys()
*/
public Collection getPropertyKeys() {
return properties.keySet();
}
/**
*
* @param key
* @param value
*/
public void addProperty(String key, Object value) {
properties.put(key, value);
}
/**
*
* @param props
*/
public void setProperties(Map props) {
properties = props;
}
/**
*
* @param interfaceName
* @param version
* @param endpointInterface
* @param properties
* @return
* @throws ServiceLocationException
*/
public static ServiceURL createServiceURL(String interfaceName,
String version, String endpointInterface, Map properties)
throws ServiceLocationException {
String interf = convertJavaInterface2Path(interfaceName);
String path = createStringFromProperties(properties);
if (version != null)
path = appendPropertyToURLPath(path,
ServiceEndpointDescription.PROP_KEY_VERSION, version);
if (endpointInterface != null)
path = appendPropertyToURLPath(
path,
ServiceEndpointDescription.PROP_KEY_PROTOCOL_SPECIFIC_INTERFACE_NAME,
endpointInterface);
String protocol = null;
String host = null;
String port = null;
Integer lifeTime = null;
// init from properties if given
if (properties != null) {
protocol = (String) properties.get("protocol");
host = (String) properties.get("host");
port = (String) properties.get("port");
lifeTime = (Integer) properties.get("lifetime");
}
if (host == null) {
String hostname = null;
try {
InetAddress addr = InetAddress.getLocalHost();
// Get hostname
hostname = addr.getHostName();
if (hostname == null || hostname.equals("")) {
// if hostname is NULL or empty string
// set hostname to ip address
hostname = addr.getHostAddress();
}
host = hostname;
} catch (UnknownHostException e) {
e.printStackTrace();
// TODO log and rethrow
}
}
int lifetime = lifeTime != null ? lifeTime.intValue()
: ServiceURL.LIFETIME_DEFAULT;
StringBuffer buff = new StringBuffer();
buff.append("service:osgi");
buff.append(interf);
buff.append((protocol != null ? protocol + "://" : "://"));
buff.append(host);
buff.append((port != null ? ":" + port : ""));
buff.append("/");
buff.append(path);
return new ServiceURL(buff.toString(), lifetime);
}
/**
*
* @param serviceURL
* @param javaInterfaceAndFilters
* @param javaAndEndpointInterfaces
* @param properties
* @return
*/
public static String retrieveDataFromServiceURL(
final ServiceURL serviceURL,
final Map/* <String, String> */javaInterfaceAndFilters,
final Map/* <String, String> */javaAndEndpointInterfaces,
final Map/* <String, Object> */properties) {
// retrieve main interface
String interfaceName = convertPath2JavaInterface(serviceURL
.getServiceType().getConcreteTypeName());
if (interfaceName == null) {
throw new IllegalArgumentException(
"Interface information is missing!");
}
// Retrieve additional properties from SLP ServiceURL itself
properties.put("slp.serviceURL", serviceURL);
properties.put("type", serviceURL.getServiceType().toString());
if (serviceURL.getHost() != null) {
properties.put("host", serviceURL.getHost());
}
if (serviceURL.getPort() != 0) {
properties.put("port", new Integer(serviceURL.getPort()));
}
if (serviceURL.getProtocol() != null) {
properties.put("protocol", serviceURL.getProtocol());
}
properties.put("lifetime", new Integer(serviceURL.getLifetime()));
// retrieve properties from ServiceURL attributes
retrievePropertiesFromPath(serviceURL.getURLPath(), properties);
// Get version info
String version;
Object versionsValue = properties
.get(ServiceEndpointDescription.PROP_KEY_VERSION);
if (versionsValue instanceof String) {
version = (String) versionsValue;
} else {
// TODO log error
version = SLPServiceDescriptionAdapter.UnknownVersion;
}
javaInterfaceAndFilters.put(interfaceName, version);
// Get endpoint-interface if it exists
Object endpointInterfacesValue = properties
.get(ServiceEndpointDescription.PROP_KEY_PROTOCOL_SPECIFIC_INTERFACE_NAME);
if (endpointInterfacesValue instanceof String) {
javaAndEndpointInterfaces.put(interfaceName,
endpointInterfacesValue);
}
// return main interface name
return interfaceName;
}
/**
*
* @param path
* @param properties
*/
public static void retrievePropertiesFromPath(String path,
final Map properties) {
try {
if (path != null && path.trim() != "") {
path = path.substring(2); // strip off the "/?" in front of
// the
// path
StringTokenizer st = new StringTokenizer(path, "=,");
String key;
String value;
// TODO de-escape escaped chars
try {
while (st.hasMoreTokens()) {
key = st.nextToken();
if (st.hasMoreTokens())
value = st.nextToken();
else
value = "";
properties.put(key, value);
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
return;
}
}
/**
*
* @param javaInterfaceName
* @return
*/
public static String convertJavaInterface2Path(
final String javaInterfaceName) {
return javaInterfaceName != null ? ":"
+ javaInterfaceName.replace('.', '/') : "";
}
/**
*
* @param interfaceNameEncodedAsPath
* @return
*/
public static String convertPath2JavaInterface(
final String interfaceNameEncodedAsPath) {
return interfaceNameEncodedAsPath != null ? interfaceNameEncodedAsPath
.replace('/', '.') : null;
}
/**
*
* @param properties
* @return
*/
private static String createStringFromProperties(final Map properties) {
StringBuffer sb = new StringBuffer();
String key = null;
Object value = null;
if ((properties != null) && !properties.isEmpty()) {
for (Iterator i = properties.keySet().iterator(); i.hasNext();) {
key = (String) i.next();
value = properties.get(key);
appendPropertyToURLPath(sb, key, value);
}
}
return sb.toString();
}
/**
*
* @param path
* @param key
* @param value
*/
private static void appendPropertyToURLPath(StringBuffer path, String key,
Object value) {
if (path == null)
throw new IllegalArgumentException("Given StringBuffer is null.");
if (path.length() == 0) {
path.append("?");
} else {
path.append(",");
}
if (value == null) {
value = "<null>";
}
path.append(escapeReservedChars(key,
SLPServiceDescriptionAdapter.RESERVED_CHARS_IN_ATTR_KEYS));
path.append("=");
if (value instanceof Object[]) {
Object[] arrayValue = (Object[]) value;
for (int i = 0; i < arrayValue.length;) {
path
.append(escapeReservedChars(
arrayValue[i].toString(),
SLPServiceDescriptionAdapter.RESERVED_CHARS_IN_ATTR_VALUES));
if (++i != arrayValue.length)
path.append(",");
}
} else
path
.append(escapeReservedChars(
value.toString(),
SLPServiceDescriptionAdapter.RESERVED_CHARS_IN_ATTR_VALUES));
}
/**
*
* @param path
* @param key
* @param value
* @return
*/
public static String appendPropertyToURLPath(String path, String key,
Object value) {
StringBuffer buffer = new StringBuffer(path);
appendPropertyToURLPath(buffer, key, value);
return buffer.toString();
}
/**
* TODO: create test case using reserved chars
*
* @param value
* @param reservedChars
* @return
*/
public static String deescapeReservedChars(String value) {
// tokenize escapedchars as extra chars
StringTokenizer tokenizer = new StringTokenizer(value, SLPServiceDescriptionAdapter.ESCAPING_CHARACTER);
//TODO finish
return null;
}
/**
* TODO: create test case using reserved chars
*
* @param value
* @param reservedChars
* @return
*/
public static String escapeReservedChars(String value, String reservedChars) {
// tokenize reserved chars as extra chars
StringTokenizer tokenizer = new StringTokenizer(value, reservedChars,
true);
boolean isReservedChar = false;
// if there is only one token
if (tokenizer.countTokens() == 1) {
String token = tokenizer.nextToken();
// then it might be a reserved char
if (token.length() == 1) {
// if it's a reserved char
if (reservedChars.indexOf(token.charAt(0)) == -1)
isReservedChar = true;
else
return value;
}
// apparently there are no reserved chars
else
return value;
}
StringBuffer buffer = new StringBuffer();
while (tokenizer.hasMoreTokens()) {
if (isReservedChar) {
String token = tokenizer.nextToken();
if (token.length() != 1) {
// TODO log
throw new RuntimeException(
"Error while escaping reserved characters.");
}
buffer.append(ESCAPING_CHARACTER + Integer.toHexString(token.charAt(0)));
isReservedChar = false;
} else {
buffer.append(tokenizer.nextToken());
// next token will be reserved char
isReservedChar = true;
}
}
return buffer.toString();
}
/**
*
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(final Object serviceDescription) {
if (!(serviceDescription instanceof ServiceEndpointDescription)) {
return false;
}
ServiceEndpointDescription descr = (ServiceEndpointDescription) serviceDescription;
if (properties != null && descr.getProperties() == null) {
return false;
}
if (properties == null && descr.getProperties() != null) {
return false;
}
if (properties == null && descr.getProperties() == null) {
return true;
}
// if (properties.size() != descr.getProperties().size()) {
// return false;
// }
Iterator it = properties.keySet().iterator();
while (it.hasNext()) {
String key = (String) it.next();
if (descr.getProperties().containsKey(key)) {
if (descr.getProperty(key) instanceof String
&& (properties.get(key) instanceof String[])) {
if (!properties.get(key).toString().equals(
(descr.getProperty(key)))) {
return false;
}
} else {
if (!properties.get(key).equals(descr.getProperty(key))) {
return false;
}
}
} else {
return false;
}
}
return true;
}
/**
*
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
return super.hashCode();
}
}
| [rfc 119] Updated Discovery-RI: added decoding of escaped values; sending of arrays; usage of interface names in filters; fixed bugs in escaping reserved chars;
| org.osgi.impl.service.discovery/src/org/osgi/impl/service/discovery/slp/SLPServiceDescriptionAdapter.java | [rfc 119] Updated Discovery-RI: added decoding of escaped values; sending of arrays; usage of interface names in filters; fixed bugs in escaping reserved chars; |
|
Java | apache-2.0 | 646104f9a95fb06208319bce84d5f9a0a0223276 | 0 | felixb/websms-api | /*
* Copyright (C) 2010-2011 Felix Bechstein
*
* This file is part of WebSMS.
*
* 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/>.
*/
package de.ub0r.android.websms.connector.common;
import java.util.ArrayList;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.widget.Toast;
/**
* {@link Service} run by the connectors BroadcastReceiver.
*
* @author flx
*/
public final class ConnectorService extends IntentService {
/** Tag for output. */
private static final String TAG = "IO";
/** {@link NotificationManager}. */
private NotificationManager mNM = null;
/** Notification ID of this Service. */
public static final int NOTIFICATION_PENDING = 0;
/** Pending tasks. */
private final ArrayList<Intent> pendingIOOps = new ArrayList<Intent>();
/** {@link WakeLock} for forcing IO done before sleep. */
private WakeLock wakelock = null;
/** {@link Handler}. */
private Handler handler = null;
/**
* Default constructor.
*/
public ConnectorService() {
super("WebSMS.Connector");
}
/**
* {@inheritDoc}
*/
@Override
public void onCreate() {
super.onCreate();
this.handler = new Handler() {
@Override
public void handleMessage(final Message msg) {
Log.i(TAG, "In handleMessage...");
}
};
}
/**
* {@inheritDoc}
*/
@Override
public void onStart(final Intent intent, final int startId) {
Log.d(TAG, "onStart()");
if (intent != null) {
this.register(intent);
}
// note that super.onStart will start processing the intent on the
// background thread so we need to register etc before that
super.onStart(intent, startId);
}
/**
* Show {@link Toast} on main thread.
*
* @param text
* text
*/
void showToast(final String text) {
Log.d(TAG, "showToast(" + text + ")");
this.handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(ConnectorService.this, text, Toast.LENGTH_LONG)
.show();
}
});
}
/**
* Build IO {@link Notification}.
*
* @param context
* {@link Context}
* @param command
* {@link ConnectorCommand}
* @return {@link Notification}
*/
public static Notification getNotification(final Context context,
final ConnectorCommand command) {
final String t = context.getString(R.string.stat_notify_sms_pending);
final String te = context.getString(R.string.stat_notify_sending) + " "
+ Utils.joinRecipients(command.getRecipients(), ", ");
final String tt = command.getText();
final Notification notification = new Notification(
R.drawable.stat_notify_sms_pending, t, System
.currentTimeMillis());
final Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setClassName("de.ub0r.android.websms", "WebSMS");
final PendingIntent contentIntent = PendingIntent.getActivity(context,
0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
notification.setLatestEventInfo(context, te, tt, contentIntent);
notification.defaults |= Notification.FLAG_NO_CLEAR
| Notification.FLAG_ONGOING_EVENT;
notification.defaults &= Notification.DEFAULT_ALL
^ Notification.DEFAULT_LIGHTS ^ Notification.DEFAULT_SOUND
^ Notification.DEFAULT_VIBRATE;
Log.d(TAG, "defaults: " + notification.defaults);
return notification;
}
/**
* Register a IO task.
*
* @param intent
* intent holding IO operation
*/
private void register(final Intent intent) {
Log.i(TAG, "register(" + intent.getAction() + ")");
synchronized (this.pendingIOOps) {
if (this.wakelock == null) {
final PowerManager pm = (PowerManager) this
.getSystemService(Context.POWER_SERVICE);
this.wakelock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
TAG);
this.wakelock.acquire();
}
final ConnectorCommand c = new ConnectorCommand(intent);
if (c.getType() == ConnectorCommand.TYPE_SEND) {
if (this.mNM == null) {
this.mNM = (NotificationManager) this
.getSystemService(NOTIFICATION_SERVICE);
}
try {
final Notification notification = getNotification(this, c);
this.mNM.notify(NOTIFICATION_PENDING, notification);
} catch (IllegalArgumentException e) {
Log.e(TAG, "illegal argument", e);
}
}
Log.d(TAG, "currentIOOps=" + this.pendingIOOps.size());
this.pendingIOOps.add(intent);
Log.d(TAG, "currentIOOps=" + this.pendingIOOps.size());
}
}
/**
* Unregister a IO task.
*
* @param intent
* intent holding IO operation
*/
private void unregister(final Intent intent) {
Log.i(TAG, "unregister(" + intent.getAction() + ")");
synchronized (this.pendingIOOps) {
Log.d(TAG, "currentIOOps=" + this.pendingIOOps.size());
final int l = this.pendingIOOps.size();
if (l == 1) {
this.pendingIOOps.clear();
} else {
Intent oi;
for (int i = 0; i < l; i++) {
oi = this.pendingIOOps.get(i);
// note that ConnectorSpec.equals will not work here because
// not all intent types have ConnectorSpec bundle in them
if (ConnectorCommand.equals(intent, oi)) {
this.pendingIOOps.remove(i);
break;
}
}
}
Log.d(TAG, "currentIOOps=" + this.pendingIOOps.size());
if (this.pendingIOOps.size() == 0) {
// set service to background
if (this.mNM != null) {
this.mNM.cancel(NOTIFICATION_PENDING);
}
if (this.wakelock != null && this.wakelock.isHeld()) {
this.wakelock.release();
}
// stop unneeded service
// this.stopSelf();
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy()");
Log.i(TAG, "currentIOOps=" + this.pendingIOOps.size());
final int s = this.pendingIOOps.size();
ConnectorCommand cc;
ConnectorSpec cs;
Intent in;
for (int i = 0; i < s; i++) {
cc = new ConnectorCommand(this.pendingIOOps.get(i));
cs = new ConnectorSpec(// .
this.pendingIOOps.get(i));
if (cc.getType() == ConnectorCommand.TYPE_SEND) {
cs.setErrorMessage("error while IO");
in = cs.setToIntent(null);
cc.setToIntent(in);
in.setFlags(in.getFlags()
| Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
this.sendBroadcast(in);
in = null;
} else {
// Toast.makeText(this, cs.getName() + ": error while IO",
// Toast.LENGTH_LONG);
}
}
}
/**
* {@inheritDoc}
*/
@Override
protected void onHandleIntent(final Intent intent) {
Log.d(TAG, "onHandleIntent()");
if (intent == null) {
return;
}
final String a = intent.getAction();
Log.d(TAG, "action: " + a);
final String pkg = this.getPackageName();
if (a != null && (// .
a.equals(pkg + Connector.ACTION_RUN_BOOTSTRAP) || // .
a.equals(pkg + Connector.ACTION_RUN_UPDATE) || // .
a.equals(pkg + Connector.ACTION_RUN_SEND))) {
// register intent, if service gets killed, all pending intents
// get send to websms
// this.register(intent);
try {
final ConnectorSpec reqSpec = ConnectorSpec.fromIntent(intent);
final ConnectorCommand command = new ConnectorCommand(intent);
final Connector receiver = Connector.getInstance();
receiver.onNewRequest(this, reqSpec, command);
ConnectorSpec respSpec = receiver.getSpec(this).clone();
this.doInBackground(intent, respSpec, command, receiver);
this.onPostExecute(respSpec, command, receiver);
} catch (WebSMSException e) {
Log.e(TAG, "error starting service", e);
// Toast.makeText(this, e.getMessage(),
// Toast.LENGTH_LONG).show();
}
}
this.unregister(intent);
}
/**
* Do the work in background.
*
* @param intent
* {@link Intent}
* @param respSpec
* {@link ConnectorSpec}
* @param command
* {@link ConnectorCommand}
* @param receiver
* {@link Connector}
*/
private void doInBackground(final Intent intent,
final ConnectorSpec respSpec, final ConnectorCommand command,
final Connector receiver) {
try {
switch (command.getType()) {
case ConnectorCommand.TYPE_BOOTSTRAP:
receiver.doBootstrap(this, intent);
break;
case ConnectorCommand.TYPE_UPDATE:
receiver.doUpdate(this, intent);
break;
case ConnectorCommand.TYPE_SEND:
String t = command.getText();
String[] r = command.getRecipients();
if (t == null || t.length() == 0 || // .
r == null || r.length == 0) {
break;
}
t = null;
r = null;
receiver.doSend(this, intent);
break;
default:
break;
}
} catch (Exception e) {
if (e instanceof WebSMSException) {
Log.d(TAG, respSpec.getPackage() + ": error in AsyncTask", e);
} else {
Log.e(TAG, respSpec.getPackage() + ": error in AsyncTask", e);
}
// put error message to ConnectorSpec
respSpec.setErrorMessage(this, e);
}
}
/**
* Do post processing.
*
* @param respSpec
* {@link ConnectorSpec}
* @param command
* {@link ConnectorCommand}
* @param receiver
* {@link Connector}
*/
private void onPostExecute(final ConnectorSpec respSpec,
final ConnectorCommand command, final Connector receiver) {
// final String e = connector.getErrorMessage();
// if (e != null) {
// Toast.makeText(this, e, Toast.LENGTH_LONG).show();
// }
respSpec.update(receiver.getSpec(this));
final Intent i = respSpec.setToIntent(null);
command.setToIntent(i);
i.setFlags(i.getFlags() | Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
Log.d(TAG, respSpec.getPackage() + ": send broadcast info");
this.sendBroadcast(i);
// this.unregister(i);
}
}
| src/de/ub0r/android/websms/connector/common/ConnectorService.java | /*
* Copyright (C) 2010-2011 Felix Bechstein
*
* This file is part of WebSMS.
*
* 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/>.
*/
package de.ub0r.android.websms.connector.common;
import java.util.ArrayList;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.widget.Toast;
/**
* {@link Service} run by the connectors BroadcastReceiver.
*
* @author flx
*/
public final class ConnectorService extends IntentService {
/** Tag for output. */
private static final String TAG = "IO";
/** {@link NotificationManager}. */
private NotificationManager mNM = null;
/** Notification ID of this Service. */
public static final int NOTIFICATION_PENDING = 0;
/** Pending tasks. */
private final ArrayList<Intent> pendingIOOps = new ArrayList<Intent>();
/** {@link WakeLock} for forcing IO done before sleep. */
private WakeLock wakelock = null;
/** {@link Handler}. */
private Handler handler = null;
/**
* Default constructor.
*/
public ConnectorService() {
super("WebSMS.Connector");
}
/**
* {@inheritDoc}
*/
@Override
public void onCreate() {
super.onCreate();
this.handler = new Handler() {
@Override
public void handleMessage(final Message msg) {
Log.i(TAG, "In handleMessage...");
}
};
}
/**
* {@inheritDoc}
*/
@Override
public void onStart(final Intent intent, final int startId) {
super.onStart(intent, startId);
Log.d(TAG, "onStart()");
if (intent != null) {
this.register(intent);
}
}
/**
* Show {@link Toast} on main thread.
*
* @param text
* text
*/
void showToast(final String text) {
Log.d(TAG, "showToast(" + text + ")");
this.handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(ConnectorService.this, text, Toast.LENGTH_LONG)
.show();
}
});
}
/**
* Build IO {@link Notification}.
*
* @param context
* {@link Context}
* @param command
* {@link ConnectorCommand}
* @return {@link Notification}
*/
public static Notification getNotification(final Context context,
final ConnectorCommand command) {
final String t = context.getString(R.string.stat_notify_sms_pending);
final String te = context.getString(R.string.stat_notify_sending) + " "
+ Utils.joinRecipients(command.getRecipients(), ", ");
final String tt = command.getText();
final Notification notification = new Notification(
R.drawable.stat_notify_sms_pending, t, System
.currentTimeMillis());
final Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setClassName("de.ub0r.android.websms", "WebSMS");
final PendingIntent contentIntent = PendingIntent.getActivity(context,
0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
notification.setLatestEventInfo(context, te, tt, contentIntent);
notification.defaults |= Notification.FLAG_NO_CLEAR
| Notification.FLAG_ONGOING_EVENT;
notification.defaults &= Notification.DEFAULT_ALL
^ Notification.DEFAULT_LIGHTS ^ Notification.DEFAULT_SOUND
^ Notification.DEFAULT_VIBRATE;
Log.d(TAG, "defaults: " + notification.defaults);
return notification;
}
/**
* Register a IO task.
*
* @param intent
* intent holding IO operation
*/
private void register(final Intent intent) {
Log.i(TAG, "register(" + intent.getAction() + ")");
synchronized (this.pendingIOOps) {
if (this.wakelock == null) {
final PowerManager pm = (PowerManager) this
.getSystemService(Context.POWER_SERVICE);
this.wakelock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
TAG);
this.wakelock.acquire();
}
final ConnectorCommand c = new ConnectorCommand(intent);
if (c.getType() == ConnectorCommand.TYPE_SEND) {
if (this.mNM == null) {
this.mNM = (NotificationManager) this
.getSystemService(NOTIFICATION_SERVICE);
}
try {
final Notification notification = getNotification(this, c);
this.mNM.notify(NOTIFICATION_PENDING, notification);
} catch (IllegalArgumentException e) {
Log.e(TAG, "illegal argument", e);
}
}
Log.d(TAG, "currentIOOps=" + this.pendingIOOps.size());
this.pendingIOOps.add(intent);
Log.d(TAG, "currentIOOps=" + this.pendingIOOps.size());
}
}
/**
* Unregister a IO task.
*
* @param intent
* intent holding IO operation
*/
private void unregister(final Intent intent) {
Log.i(TAG, "unregister(" + intent.getAction() + ")");
synchronized (this.pendingIOOps) {
Log.d(TAG, "currentIOOps=" + this.pendingIOOps.size());
final int l = this.pendingIOOps.size();
if (l == 1) {
this.pendingIOOps.clear();
} else {
Intent oi;
for (int i = 0; i < l; i++) {
oi = this.pendingIOOps.get(i);
// note that ConnectorSpec.equals will not work here because
// not all intent types have ConnectorSpec bundle in them
if (ConnectorCommand.equals(intent, oi)) {
this.pendingIOOps.remove(i);
break;
}
}
}
Log.d(TAG, "currentIOOps=" + this.pendingIOOps.size());
if (this.pendingIOOps.size() == 0) {
// set service to background
if (this.mNM != null) {
this.mNM.cancel(NOTIFICATION_PENDING);
}
if (this.wakelock != null && this.wakelock.isHeld()) {
this.wakelock.release();
}
// stop unneeded service
// this.stopSelf();
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy()");
Log.i(TAG, "currentIOOps=" + this.pendingIOOps.size());
final int s = this.pendingIOOps.size();
ConnectorCommand cc;
ConnectorSpec cs;
Intent in;
for (int i = 0; i < s; i++) {
cc = new ConnectorCommand(this.pendingIOOps.get(i));
cs = new ConnectorSpec(// .
this.pendingIOOps.get(i));
if (cc.getType() == ConnectorCommand.TYPE_SEND) {
cs.setErrorMessage("error while IO");
in = cs.setToIntent(null);
cc.setToIntent(in);
in.setFlags(in.getFlags()
| Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
this.sendBroadcast(in);
in = null;
} else {
// Toast.makeText(this, cs.getName() + ": error while IO",
// Toast.LENGTH_LONG);
}
}
}
/**
* {@inheritDoc}
*/
@Override
protected void onHandleIntent(final Intent intent) {
Log.d(TAG, "onHandleIntent()");
if (intent == null) {
return;
}
final String a = intent.getAction();
Log.d(TAG, "action: " + a);
final String pkg = this.getPackageName();
if (a != null && (// .
a.equals(pkg + Connector.ACTION_RUN_BOOTSTRAP) || // .
a.equals(pkg + Connector.ACTION_RUN_UPDATE) || // .
a.equals(pkg + Connector.ACTION_RUN_SEND))) {
// register intent, if service gets killed, all pending intents
// get send to websms
// this.register(intent);
try {
final ConnectorSpec reqSpec = ConnectorSpec.fromIntent(intent);
final ConnectorCommand command = new ConnectorCommand(intent);
final Connector receiver = Connector.getInstance();
receiver.onNewRequest(this, reqSpec, command);
ConnectorSpec respSpec = receiver.getSpec(this).clone();
this.doInBackground(intent, respSpec, command, receiver);
this.onPostExecute(respSpec, command, receiver);
} catch (WebSMSException e) {
Log.e(TAG, "error starting service", e);
// Toast.makeText(this, e.getMessage(),
// Toast.LENGTH_LONG).show();
}
}
this.unregister(intent);
}
/**
* Do the work in background.
*
* @param intent
* {@link Intent}
* @param respSpec
* {@link ConnectorSpec}
* @param command
* {@link ConnectorCommand}
* @param receiver
* {@link Connector}
*/
private void doInBackground(final Intent intent,
final ConnectorSpec respSpec, final ConnectorCommand command,
final Connector receiver) {
try {
switch (command.getType()) {
case ConnectorCommand.TYPE_BOOTSTRAP:
receiver.doBootstrap(this, intent);
break;
case ConnectorCommand.TYPE_UPDATE:
receiver.doUpdate(this, intent);
break;
case ConnectorCommand.TYPE_SEND:
String t = command.getText();
String[] r = command.getRecipients();
if (t == null || t.length() == 0 || // .
r == null || r.length == 0) {
break;
}
t = null;
r = null;
receiver.doSend(this, intent);
break;
default:
break;
}
} catch (Exception e) {
if (e instanceof WebSMSException) {
Log.d(TAG, respSpec.getPackage() + ": error in AsyncTask", e);
} else {
Log.e(TAG, respSpec.getPackage() + ": error in AsyncTask", e);
}
// put error message to ConnectorSpec
respSpec.setErrorMessage(this, e);
}
}
/**
* Do post processing.
*
* @param respSpec
* {@link ConnectorSpec}
* @param command
* {@link ConnectorCommand}
* @param receiver
* {@link Connector}
*/
private void onPostExecute(final ConnectorSpec respSpec,
final ConnectorCommand command, final Connector receiver) {
// final String e = connector.getErrorMessage();
// if (e != null) {
// Toast.makeText(this, e, Toast.LENGTH_LONG).show();
// }
respSpec.update(receiver.getSpec(this));
final Intent i = respSpec.setToIntent(null);
command.setToIntent(i);
i.setFlags(i.getFlags() | Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
Log.d(TAG, respSpec.getPackage() + ": send broadcast info");
this.sendBroadcast(i);
// this.unregister(i);
}
}
| Fixed possible race condition in ConnectorService
| src/de/ub0r/android/websms/connector/common/ConnectorService.java | Fixed possible race condition in ConnectorService |
|
Java | apache-2.0 | ca0cb704168d20a78e0325ae305736c72712b6b9 | 0 | durgadeviramadoss/Hygieia,pavan149679/Hygieia,jimzucker/Hygieia,oshingc/Hygieia,paychex/Hygieia,satishc1/Hygieia,satishc1/Hygieia,paychex/Hygieia,tabladrum/Hygieia,Sbrenthughes/Hygieia,pavan149679/Hygieia,durgadeviramadoss/Hygieia,capitalone/Hygieia,jimzucker/Hygieia,durgadeviramadoss/Hygieia,satishc1/Hygieia,Sbrenthughes/Hygieia,nireeshT/Hygieia,tabladrum/Hygieia,paychex/Hygieia,paychex/Hygieia,wolfspyre/Hygieia,amitmawkin/Hygieia,capitalone/Hygieia,oshingc/Hygieia,nireeshT/Hygieia,nireeshT/Hygieia,Sbrenthughes/Hygieia,pavan149679/Hygieia,oshingc/Hygieia,tabladrum/Hygieia,satishc1/Hygieia,tabladrum/Hygieia,capitalone/Hygieia,pavan149679/Hygieia,Sbrenthughes/Hygieia,wolfspyre/Hygieia,jimzucker/Hygieia,amitmawkin/Hygieia,amitmawkin/Hygieia,capitalone/Hygieia,amitmawkin/Hygieia,wolfspyre/Hygieia,durgadeviramadoss/Hygieia,oshingc/Hygieia,nireeshT/Hygieia,durgadeviramadoss/Hygieia,jimzucker/Hygieia | package com.capitalone.dashboard.collector;
import com.capitalone.dashboard.model.Collector;
import com.capitalone.dashboard.model.CollectorItem;
import com.capitalone.dashboard.model.CollectorType;
import com.capitalone.dashboard.model.Commit;
import com.capitalone.dashboard.model.CommitType;
import com.capitalone.dashboard.model.Component;
import com.capitalone.dashboard.model.GitHubRepo;
import com.capitalone.dashboard.repository.BaseCollectorItemRepository;
import com.capitalone.dashboard.repository.CommitRepository;
import com.capitalone.dashboard.repository.ComponentRepository;
import com.capitalone.dashboard.repository.GitHubRepoRepository;
import org.bson.types.ObjectId;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class GitHubCollectorTaskTest {
@Mock private BaseCollectorItemRepository collectors;
@Mock private GitHubRepoRepository gitHubRepoRepository;
@Mock private GitHubClient gitHubClient;
@Mock private GitHubSettings gitHubSettings;
@Mock private ComponentRepository dbComponentRepository;
@Mock private CommitRepository commitRepository;
@Mock private GitHubRepo repo1;
@Mock private GitHubRepo repo2;
@Mock private Commit commit;
@InjectMocks private GitHubCollectorTask task;
@Test
public void collect_testCollect() {
when(dbComponentRepository.findAll()).thenReturn(components());
Set<ObjectId> gitID = new HashSet<>();
gitID.add(new ObjectId("111ca42a258ad365fbb64ecc"));
when(gitHubRepoRepository.findByCollectorIdIn(gitID)).thenReturn(getGitHubs());
Collector collector = new Collector();
collector.setEnabled(true);
collector.setName("collector");
collector.setId(new ObjectId("111ca42a258ad365fbb64ecc"));
when(gitHubRepoRepository.findEnabledGitHubRepos(collector.getId())).thenReturn(getEnabledRepos());
when(gitHubClient.getCommits(repo1, true)).thenReturn(getCommits());
when(commitRepository.findByCollectorItemIdAndScmRevisionNumber(
repo1.getId(), "1")).thenReturn(null);
task.collect(collector);
//verify that orphaned repo is disabled
assertEquals("repo2.no.collectoritem", repo2.getNiceName());
assertEquals(false, repo2.isEnabled());
//verify that repo1 is enabled
assertEquals("repo1-ci1", repo1.getNiceName());
assertEquals(true, repo1.isEnabled());
//verify that save is called once for the commit item
Mockito.verify(commitRepository, times(1)).save(commit);
}
private ArrayList<Commit> getCommits() {
ArrayList<Commit> commits = new ArrayList<Commit>();
commit = new Commit();
commit.setTimestamp(System.currentTimeMillis());
commit.setScmUrl("http://testcurrenturl");
commit.setScmBranch("master");
commit.setScmRevisionNumber("1");
commit.setScmAuthor("author");
commit.setScmCommitLog("This is a test commit");
commit.setScmCommitTimestamp(System.currentTimeMillis());
commit.setNumberOfChanges(1);
commit.setType(CommitType.New);
commits.add(commit);
return commits;
}
private List<GitHubRepo> getEnabledRepos() {
List<GitHubRepo> gitHubs = new ArrayList<GitHubRepo>();
repo1 = new GitHubRepo();
repo1.setEnabled(true);
repo1.setId(new ObjectId("1c1ca42a258ad365fbb64ecc"));
repo1.setCollectorId(new ObjectId("111ca42a258ad365fbb64ecc"));
repo1.setNiceName("repo1-ci1");
repo1.setRepoUrl("http://current");
gitHubs.add(repo1);
return gitHubs;
}
private ArrayList<GitHubRepo> getGitHubs() {
ArrayList<GitHubRepo> gitHubs = new ArrayList<GitHubRepo>();
repo1 = new GitHubRepo();
repo1.setEnabled(true);
repo1.setId(new ObjectId("1c1ca42a258ad365fbb64ecc"));
repo1.setCollectorId(new ObjectId("111ca42a258ad365fbb64ecc"));
repo1.setNiceName("repo1-ci1");
repo1.setRepoUrl("http://current");
repo2 = new GitHubRepo();
repo2.setEnabled(true);
repo2.setId(new ObjectId("1c4ca42a258ad365fbb64ecc"));
repo2.setCollectorId(new ObjectId("111ca42a258ad365fbb64ecc"));
repo2.setNiceName("repo2.no.collectoritem");
repo2.setRepoUrl("http://obsolete");
gitHubs.add(repo1);
gitHubs.add(repo2);
return gitHubs;
}
private ArrayList<com.capitalone.dashboard.model.Component> components() {
ArrayList<com.capitalone.dashboard.model.Component> cArray = new ArrayList<com.capitalone.dashboard.model.Component>();
com.capitalone.dashboard.model.Component c = new Component();
c.setId(new ObjectId());
c.setName("COMPONENT1");
c.setOwner("JOHN");
CollectorType scmType = CollectorType.SCM;
CollectorItem ci1 = new CollectorItem();
ci1.setId(new ObjectId("1c1ca42a258ad365fbb64ecc"));
ci1.setNiceName("ci1");
ci1.setEnabled(true);
ci1.setPushed(false);
ci1.setCollectorId(new ObjectId("111ca42a258ad365fbb64ecc"));
c.addCollectorItem(scmType, ci1);
CollectorItem ci2 = new CollectorItem();
ci2.setId(new ObjectId("1c2ca42a258ad365fbb64ecc"));
ci2.setNiceName("ci2");
ci2.setEnabled(true);
ci2.setPushed(false);
ci2.setCollectorId(new ObjectId("111ca42a258ad365fbb64ecc"));
c.addCollectorItem(scmType, ci2);
CollectorItem ci3 = new CollectorItem();
ci3.setId(new ObjectId("1c3ca42a258ad365fbb64ecc"));
ci3.setNiceName("ci3");
ci3.setEnabled(true);
ci3.setPushed(false);
ci3.setCollectorId(new ObjectId("222ca42a258ad365fbb64ecc"));
c.addCollectorItem(scmType, ci3);
cArray.add(c);
return cArray;
}
} | github-scm-collector/src/test/java/com/capitalone/dashboard/collector/GitHubCollectorTaskTest.java | package com.capitalone.dashboard.collector;
import com.capitalone.dashboard.model.*;
import com.capitalone.dashboard.repository.BaseCollectorItemRepository;
import com.capitalone.dashboard.repository.CommitRepository;
import com.capitalone.dashboard.repository.ComponentRepository;
import com.capitalone.dashboard.repository.GitHubRepoRepository;
import org.bson.types.ObjectId;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
public class GitHubCollectorTaskTest {
@Mock private BaseCollectorItemRepository collectors;
@Mock private GitHubRepoRepository gitHubRepoRepository;
@Mock private GitHubClient gitHubClient;
@Mock private GitHubSettings gitHubSettings;
@Mock private ComponentRepository dbComponentRepository;
@Mock private CommitRepository commitRepository;
@Mock private GitHubRepo repo1;
@Mock private GitHubRepo repo2;
@Mock private Commit commit;
@InjectMocks private GitHubCollectorTask task;
@Test
public void collect_testCollect() {
when(dbComponentRepository.findAll()).thenReturn(components());
Set<ObjectId> gitID = new HashSet<>();
gitID.add(new ObjectId("111ca42a258ad365fbb64ecc"));
when(gitHubRepoRepository.findByCollectorIdIn(gitID)).thenReturn(getGitHubs());
Collector collector = new Collector();
collector.setEnabled(true);
collector.setName("collector");
collector.setId(new ObjectId("111ca42a258ad365fbb64ecc"));
when(gitHubRepoRepository.findEnabledGitHubRepos(collector.getId())).thenReturn(getEnabledRepos());
when(gitHubClient.getCommits(repo1, true)).thenReturn(getCommits());
when(commitRepository.findByCollectorItemIdAndScmRevisionNumber(
repo1.getId(), "1")).thenReturn(null);
task.collect(collector);
//verify that orphaned repo is disabled
assertEquals("repo2.no.collectoritem", repo2.getNiceName());
assertEquals(false, repo2.isEnabled());
//verify that repo1 is enabled
assertEquals("repo1-ci1", repo1.getNiceName());
assertEquals(true, repo1.isEnabled());
//verify that save is called once for the commit item
Mockito.verify(commitRepository, times(1)).save(commit);
}
private ArrayList<Commit> getCommits() {
ArrayList<Commit> commits = new ArrayList<Commit>();
commit = new Commit();
commit.setTimestamp(System.currentTimeMillis());
commit.setScmUrl("http://testcurrenturl");
commit.setScmBranch("master");
commit.setScmRevisionNumber("1");
commit.setScmAuthor("author");
commit.setScmCommitLog("This is a test commit");
commit.setScmCommitTimestamp(System.currentTimeMillis());
commit.setNumberOfChanges(1);
commit.setType(CommitType.New);
commits.add(commit);
return commits;
}
private List<GitHubRepo> getEnabledRepos() {
List<GitHubRepo> gitHubs = new ArrayList<GitHubRepo>();
repo1 = new GitHubRepo();
repo1.setEnabled(true);
repo1.setId(new ObjectId("1c1ca42a258ad365fbb64ecc"));
repo1.setCollectorId(new ObjectId("111ca42a258ad365fbb64ecc"));
repo1.setNiceName("repo1-ci1");
repo1.setRepoUrl("http://current");
gitHubs.add(repo1);
return gitHubs;
}
private ArrayList<GitHubRepo> getGitHubs() {
ArrayList<GitHubRepo> gitHubs = new ArrayList<GitHubRepo>();
repo1 = new GitHubRepo();
repo1.setEnabled(true);
repo1.setId(new ObjectId("1c1ca42a258ad365fbb64ecc"));
repo1.setCollectorId(new ObjectId("111ca42a258ad365fbb64ecc"));
repo1.setNiceName("repo1-ci1");
repo1.setRepoUrl("http://current");
repo2 = new GitHubRepo();
repo2.setEnabled(true);
repo2.setId(new ObjectId("1c4ca42a258ad365fbb64ecc"));
repo2.setCollectorId(new ObjectId("111ca42a258ad365fbb64ecc"));
repo2.setNiceName("repo2.no.collectoritem");
repo2.setRepoUrl("http://obsolete");
gitHubs.add(repo1);
gitHubs.add(repo2);
return gitHubs;
}
private ArrayList<com.capitalone.dashboard.model.Component> components() {
ArrayList<com.capitalone.dashboard.model.Component> cArray = new ArrayList<com.capitalone.dashboard.model.Component>();
com.capitalone.dashboard.model.Component c = new Component();
c.setId(new ObjectId());
c.setName("COMPONENT1");
c.setOwner("JOHN");
CollectorType scmType = CollectorType.SCM;
CollectorItem ci1 = new CollectorItem();
ci1.setId(new ObjectId("1c1ca42a258ad365fbb64ecc"));
ci1.setNiceName("ci1");
ci1.setEnabled(true);
ci1.setPushed(false);
ci1.setCollectorId(new ObjectId("111ca42a258ad365fbb64ecc"));
c.addCollectorItem(scmType, ci1);
CollectorItem ci2 = new CollectorItem();
ci2.setId(new ObjectId("1c2ca42a258ad365fbb64ecc"));
ci2.setNiceName("ci2");
ci2.setEnabled(true);
ci2.setPushed(false);
ci2.setCollectorId(new ObjectId("111ca42a258ad365fbb64ecc"));
c.addCollectorItem(scmType, ci2);
CollectorItem ci3 = new CollectorItem();
ci3.setId(new ObjectId("1c3ca42a258ad365fbb64ecc"));
ci3.setNiceName("ci3");
ci3.setEnabled(true);
ci3.setPushed(false);
ci3.setCollectorId(new ObjectId("222ca42a258ad365fbb64ecc"));
c.addCollectorItem(scmType, ci3);
cArray.add(c);
return cArray;
}
} | Remove wildcard imports.
| github-scm-collector/src/test/java/com/capitalone/dashboard/collector/GitHubCollectorTaskTest.java | Remove wildcard imports. |
|
Java | apache-2.0 | fa2c309355d02861ed1addd7069fa78b3982cf91 | 0 | rodrigokuroda/recominer,rodrigokuroda/recominer,rodrigokuroda/recominer,rodrigokuroda/recominer,rodrigokuroda/recominer,rodrigokuroda/recominer | package br.edu.utfpr.recominer.batch.calculator;
import br.edu.utfpr.recominer.core.model.Commit;
import br.edu.utfpr.recominer.core.model.File;
import br.edu.utfpr.recominer.core.model.Issue;
import br.edu.utfpr.recominer.core.model.Project;
import br.edu.utfpr.recominer.core.repository.CommitRepository;
import br.edu.utfpr.recominer.core.repository.FileRepository;
import br.edu.utfpr.recominer.core.repository.IssueRepository;
import br.edu.utfpr.recominer.filter.FileFilter;
import br.edu.utfpr.recominer.metric.file.FileMetrics;
import br.edu.utfpr.recominer.metric.file.FileMetricsCalculator;
import br.edu.utfpr.recominer.metric.network.NetworkMetrics;
import br.edu.utfpr.recominer.model.CommitMetrics;
import br.edu.utfpr.recominer.model.IssuesMetrics;
import br.edu.utfpr.recominer.repository.CommitMetricsRepository;
import br.edu.utfpr.recominer.repository.FileMetricsRepository;
import br.edu.utfpr.recominer.repository.IssuesMetricsRepository;
import br.edu.utfpr.recominer.repository.NetworkMetricsRepository;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.inject.Named;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.beans.factory.annotation.Value;
/**
*
* @author Rodrigo T. Kuroda <rodrigokuroda at alunos.utfpr.edu.br>
*/
@Named
@StepScope
public class CalculatorProcessor implements ItemProcessor<Project, CalculatorLog> {
private final Logger log = LoggerFactory.getLogger(CalculatorProcessor.class);
@Inject
private CommitRepository commitRepository;
@Inject
private IssueRepository issueRepository;
@Inject
private FileRepository fileRepository;
@Inject
private CommunicationMetricProcessor communicationMetricProcessor;
@Inject
private CommitMetricsCalculator commitMetricCalculator;
@Inject
private IssuesMetricsRepository issuesMetricsRepository;
@Inject
private IssueMetricCalculator issueMetricCalculator;
@Inject
private NetworkMetricsRepository networkMetricsRepository;
@Inject
private FileMetricsRepository fileMetricsRepository;
@Inject
private FileMetricsCalculator fileMetricCalculator;
@Inject
private CommitMetricsRepository commitMetricsRepository;
@Value("#{jobParameters[filenameFilter]}")
private String filter;
@Value("#{jobParameters[issueKey]}")
private String issueKey;
@Override
public CalculatorLog process(Project project) throws Exception {
CalculatorLog calculatorLog = new CalculatorLog(project, "AllMetrics");
calculatorLog.start();
commitRepository.setProject(project);
issueRepository.setProject(project);
fileRepository.setProject(project);
issuesMetricsRepository.setProject(project);
networkMetricsRepository.setProject(project);
fileMetricsRepository.setProject(project);
commitMetricsRepository.setProject(project);
// select new commits
final List<Commit> newCommits;
if (StringUtils.isBlank(issueKey)) {
newCommits = commitRepository.selectNewCommitsForCalculator();
log.info("{} new commits to be processed.", newCommits.size());
} else {
newCommits = commitRepository.selectCommitsOf(issueKey);
log.info("Running classification for issue {}", issueKey);
}
for (Commit newCommit : newCommits) {
log.info("Computing metrics for changed files on commit {}.", newCommit.getId());
// select changed files
final List<File> changedFiles = fileRepository.selectChangedFilesIn(newCommit);
final Predicate<File> fileFilter = FileFilter.getFilterByFilename(filter);
for (File changedFile : changedFiles.stream()
.filter(fileFilter)
.collect(Collectors.toList())) {
log.info("Computing metrics for file {} in the past.", changedFile.getId());
List<Issue> issuesOfFile = issueRepository.selectFixedIssuesOf(changedFile, newCommit);
long issuesProcessed = 0;
for (Issue issue : issuesOfFile) {
log.info("{} of {} past issues processed.", ++issuesProcessed, issuesOfFile.size());
List<Commit> commitsOfFile = commitRepository.selectCommitsOf(issue, changedFile);
long commitProcessed = 0;
for (Commit commit : commitsOfFile) {
log.info("{} of {} past commits processed.", ++commitProcessed, commitsOfFile.size());
log.info("Computing metrics for file {} of commit {}.", changedFile.getId(), commit.getId());
CommitMetrics historicalCommitMetrics = commitMetricsRepository.selectMetricsOf(commit);
if (historicalCommitMetrics == null) {
log.info("Computing metrics of past commit {}.", commit.getId());
historicalCommitMetrics = commitMetricCalculator.calculeFor(project, commit);
commitMetricsRepository.save(historicalCommitMetrics);
} else {
log.info("Metrics for commit {} has already computed.", commit.getId());
}
FileMetrics historicalFileMetrics = fileMetricsRepository.selectMetricsOf(changedFile, commit);
if (historicalFileMetrics == null) {
log.info("Computing metrics for file {} in past commit {}.", changedFile.getId(), commit.getId());
historicalFileMetrics = fileMetricCalculator.calcule(project, changedFile, commit);
fileMetricsRepository.save(historicalFileMetrics);
} else {
log.info("Metrics for file {} in past commit {} has already computed.", changedFile.getId(), commit.getId());
}
log.info("Computing metrics for file {}of issue {}.", changedFile.getId(), issue.getId());
final IssuesMetrics issueMetrics = issueMetricCalculator.calculeIssueMetrics(project, issue, commit);
issuesMetricsRepository.save(issueMetrics);
log.info("Computing network metrics for file {} of issue {}.", changedFile.getId(), issue.getId());
final NetworkMetrics networkMetrics = communicationMetricProcessor.process(project, issue, commit);
networkMetricsRepository.save(networkMetrics);
}
}
FileMetrics fileMetrics = fileMetricsRepository.selectMetricsOf(changedFile, newCommit);
if (fileMetrics == null) {
log.info("Computing metrics for file {}.", changedFile.getId());
fileMetrics = fileMetricCalculator.calcule(project, changedFile, newCommit);
fileMetricsRepository.save(fileMetrics);
} else {
log.info("Metrics for file {} already computed.", changedFile.getId());
}
}
log.info("Computing metrics of new commit {}.", newCommit.getId());
CommitMetrics newCommitMetrics = commitMetricsRepository.selectMetricsOf(newCommit);
if (newCommitMetrics == null) {
newCommitMetrics = commitMetricCalculator.calculeFor(project, newCommit);
commitMetricsRepository.save(newCommitMetrics);
} else {
log.info("Metrics for new commit {} already computed.", newCommit.getId());
}
// select issues associated to new commit
final List<Issue> issues = issueRepository.selectIssuesRelatedTo(newCommit);
log.info("Computing metrics of issues associated with new commit {}.", newCommit.getId());
for (Issue issue : issues) {
log.info("Computing metrics of issue {}.", issue.getId());
final IssuesMetrics issuesMetrics = issueMetricCalculator.calculeIssueMetrics(project, issue, newCommit);
issuesMetricsRepository.save(issuesMetrics);
log.info("Computing network metrics of issue {}.", issue.getId());
final NetworkMetrics networkMetrics = communicationMetricProcessor.process(project, issue, newCommit);
networkMetricsRepository.save(networkMetrics);
}
}
calculatorLog.stop();
return calculatorLog;
}
}
| recominer-extractor/src/main/java/br/edu/utfpr/recominer/batch/calculator/CalculatorProcessor.java | package br.edu.utfpr.recominer.batch.calculator;
import br.edu.utfpr.recominer.core.model.Commit;
import br.edu.utfpr.recominer.core.model.File;
import br.edu.utfpr.recominer.core.model.Issue;
import br.edu.utfpr.recominer.core.model.Project;
import br.edu.utfpr.recominer.core.repository.CommitRepository;
import br.edu.utfpr.recominer.core.repository.FileRepository;
import br.edu.utfpr.recominer.core.repository.IssueRepository;
import br.edu.utfpr.recominer.filter.FileFilter;
import br.edu.utfpr.recominer.metric.file.FileMetrics;
import br.edu.utfpr.recominer.metric.file.FileMetricsCalculator;
import br.edu.utfpr.recominer.metric.network.NetworkMetrics;
import br.edu.utfpr.recominer.model.CommitMetrics;
import br.edu.utfpr.recominer.model.IssuesMetrics;
import br.edu.utfpr.recominer.repository.CommitMetricsRepository;
import br.edu.utfpr.recominer.repository.FileMetricsRepository;
import br.edu.utfpr.recominer.repository.IssuesMetricsRepository;
import br.edu.utfpr.recominer.repository.NetworkMetricsRepository;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javax.inject.Inject;
import javax.inject.Named;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.beans.factory.annotation.Value;
/**
*
* @author Rodrigo T. Kuroda <rodrigokuroda at alunos.utfpr.edu.br>
*/
@Named
@StepScope
public class CalculatorProcessor implements ItemProcessor<Project, CalculatorLog> {
private final Logger log = LoggerFactory.getLogger(CalculatorProcessor.class);
@Inject
private CommitRepository commitRepository;
@Inject
private IssueRepository issueRepository;
@Inject
private FileRepository fileRepository;
@Inject
private CommunicationMetricProcessor communicationMetricProcessor;
@Inject
private CommitMetricsCalculator commitMetricCalculator;
@Inject
private IssuesMetricsRepository issuesMetricsRepository;
@Inject
private IssueMetricCalculator issueMetricCalculator;
@Inject
private NetworkMetricsRepository networkMetricsRepository;
@Inject
private FileMetricsRepository fileMetricsRepository;
@Inject
private FileMetricsCalculator fileMetricCalculator;
@Inject
private CommitMetricsRepository commitMetricsRepository;
@Value("#{jobParameters[filenameFilter]}")
private String filter;
@Value("#{jobParameters[issueKey]}")
private String issueKey;
@Override
public CalculatorLog process(Project project) throws Exception {
CalculatorLog calculatorLog = new CalculatorLog(project, "AllMetrics");
calculatorLog.start();
commitRepository.setProject(project);
issueRepository.setProject(project);
fileRepository.setProject(project);
issuesMetricsRepository.setProject(project);
networkMetricsRepository.setProject(project);
fileMetricsRepository.setProject(project);
commitMetricsRepository.setProject(project);
// select new commits
final List<Commit> newCommits;
if (StringUtils.isBlank(issueKey)) {
newCommits = commitRepository.selectNewCommitsForAssociationRule();
log.info("{} new commits to be processed.", newCommits.size());
} else {
newCommits = commitRepository.selectCommitsOf(issueKey);
log.info("Running classification for issue {}", issueKey);
}
for (Commit newCommit : newCommits) {
log.info("Computing metrics for changed files on commit {}.", newCommit.getId());
// select changed files
final List<File> changedFiles = fileRepository.selectChangedFilesIn(newCommit);
final Predicate<File> fileFilter = FileFilter.getFilterByFilename(filter);
for (File changedFile : changedFiles.stream()
.filter(fileFilter)
.collect(Collectors.toList())) {
log.info("Computing metrics for file {} in the past.", changedFile.getId());
List<Issue> issuesOfFile = issueRepository.selectFixedIssuesFromLastVersionOf(changedFile, newCommit);
long issuesProcessed = 0;
for (Issue issue : issuesOfFile) {
log.info("{} of {} past issues processed.", ++issuesProcessed, issuesOfFile.size());
List<Commit> commitsOfFile = commitRepository.selectCommitsOf(issue, changedFile);
long commitProcessed = 0;
for (Commit commit : commitsOfFile) {
log.info("{} of {} past commits processed.", ++commitProcessed, commitsOfFile.size());
log.info("Computing metrics for file {} of commit {}.", changedFile.getId(), commit.getId());
CommitMetrics historicalCommitMetrics = commitMetricsRepository.selectMetricsOf(commit);
if (historicalCommitMetrics == null) {
log.info("Computing metrics of past commit {}.", commit.getId());
historicalCommitMetrics = commitMetricCalculator.calculeFor(project, commit);
commitMetricsRepository.save(historicalCommitMetrics);
} else {
log.info("Metrics for commit {} has already computed.", commit.getId());
}
FileMetrics historicalFileMetrics = fileMetricsRepository.selectMetricsOf(changedFile, commit);
if (historicalFileMetrics == null) {
log.info("Computing metrics for file {} in past commit {}.", changedFile.getId(), commit.getId());
historicalFileMetrics = fileMetricCalculator.calcule(project, changedFile, commit);
fileMetricsRepository.save(historicalFileMetrics);
} else {
log.info("Metrics for file {} in past commit {} has already computed.", changedFile.getId(), commit.getId());
}
log.info("Computing metrics for file {}of issue {}.", changedFile.getId(), issue.getId());
final IssuesMetrics issueMetrics = issueMetricCalculator.calculeIssueMetrics(project, issue, commit);
issuesMetricsRepository.save(issueMetrics);
log.info("Computing network metrics for file {} of issue {}.", changedFile.getId(), issue.getId());
final NetworkMetrics networkMetrics = communicationMetricProcessor.process(project, issue, commit);
networkMetricsRepository.save(networkMetrics);
}
}
FileMetrics fileMetrics = fileMetricsRepository.selectMetricsOf(changedFile, newCommit);
if (fileMetrics == null) {
log.info("Computing metrics for file {}.", changedFile.getId());
fileMetrics = fileMetricCalculator.calcule(project, changedFile, newCommit);
fileMetricsRepository.save(fileMetrics);
} else {
log.info("Metrics for file {} already computed.", changedFile.getId());
}
}
log.info("Computing metrics of new commit {}.", newCommit.getId());
CommitMetrics newCommitMetrics = commitMetricsRepository.selectMetricsOf(newCommit);
if (newCommitMetrics == null) {
newCommitMetrics = commitMetricCalculator.calculeFor(project, newCommit);
commitMetricsRepository.save(newCommitMetrics);
} else {
log.info("Metrics for new commit {} already computed.", newCommit.getId());
}
// select issues associated to new commit
final List<Issue> issues = issueRepository.selectIssuesRelatedTo(newCommit);
log.info("Computing metrics of issues associated with new commit {}.", newCommit.getId());
for (Issue issue : issues) {
log.info("Computing metrics of issue {}.", issue.getId());
final IssuesMetrics issuesMetrics = issueMetricCalculator.calculeIssueMetrics(project, issue, newCommit);
issuesMetricsRepository.save(issuesMetrics);
log.info("Computing network metrics of issue {}.", issue.getId());
final NetworkMetrics networkMetrics = communicationMetricProcessor.process(project, issue, newCommit);
networkMetricsRepository.save(networkMetrics);
}
}
calculatorLog.stop();
return calculatorLog;
}
}
| Fix method call.
Changed selection of issues to all data instead of from last release. | recominer-extractor/src/main/java/br/edu/utfpr/recominer/batch/calculator/CalculatorProcessor.java | Fix method call. Changed selection of issues to all data instead of from last release. |
|
Java | bsd-2-clause | dd221197d96a5544223ae37966e39c60255868fd | 0 | chototsu/MikuMikuStudio,chototsu/MikuMikuStudio,chototsu/MikuMikuStudio,chototsu/MikuMikuStudio | /*
* Copyright (c) 2011 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jme3.network.base;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.jme3.network.*;
import com.jme3.network.kernel.Endpoint;
import com.jme3.network.kernel.EndpointEvent;
import com.jme3.network.kernel.Envelope;
import com.jme3.network.kernel.Kernel;
import com.jme3.network.message.ClientRegistrationMessage; //hopefully temporary
import com.jme3.network.serializing.Serializer;
/**
* Wraps a single Kernel and forwards new messages
* to the supplied message dispatcher and new endpoint
* events to the connection dispatcher. This is used
* by DefaultServer to manage its kernel objects.
*
* <p>This adapter assumes a simple protocol where two
* bytes define a (short) object size with the object data
* to follow. Note: this limits the size of serialized
* objects to 32676 bytes... even though, for example,
* datagram packets can hold twice that. :P</p>
*
* @version $Revision$
* @author Paul Speed
*/
public class KernelAdapter extends Thread
{
static Logger log = Logger.getLogger(KernelAdapter.class.getName());
private DefaultServer server; // this is unfortunate
private Kernel kernel;
private MessageListener<HostedConnection> messageDispatcher;
private AtomicBoolean go = new AtomicBoolean(true);
// Keeps track of the in-progress messages that are received
// on reliable connections
private Map<Endpoint, MessageProtocol> messageBuffers = new ConcurrentHashMap<Endpoint,MessageProtocol>();
// Marks the messages as reliable or not if they came
// through this connector.
private boolean reliable;
public KernelAdapter( DefaultServer server, Kernel kernel, MessageListener<HostedConnection> messageDispatcher,
boolean reliable )
{
super( String.valueOf(kernel) );
this.server = server;
this.kernel = kernel;
this.messageDispatcher = messageDispatcher;
this.reliable = reliable;
setDaemon(true);
}
public void close() throws InterruptedException
{
go.set(false);
// Kill the kernel
kernel.terminate();
}
protected void reportError( Endpoint p, Object context, Exception e )
{
// Should really be queued up so the outer thread can
// retrieve them. For now we'll just log it. FIXME
log.log( Level.SEVERE, "Unhandled error, endpoint:" + p + ", context:" + context, e );
}
protected HostedConnection getConnection( Endpoint p )
{
return server.getConnection(p);
}
protected void connectionClosed( Endpoint p )
{
// Remove any message buffer we've been accumulating
// on behalf of this endpoing
messageBuffers.remove(p);
server.connectionClosed(p);
}
/**
* Note on threading for those writing their own server
* or adapter implementations. The rule that a single connection be
* processed by only one thread at a time is more about ensuring that
* the messages are delivered in the order that they are received
* than for any user-code safety. 99% of the time the user code should
* be writing for multithreaded access anyway.
*
* <p>The issue with the messages is that if a an implementation is
* using a general thread pool then it would be possible for a
* naive implementation to have one thread grab an Envelope from
* connection 1's and another grab the next Envelope. Since an Envelope
* may contain several messages, delivering the second thread's messages
* before or during the first's would be really confusing and hard
* to code for in user code.</p>
*
* <p>And that's why this note is here. DefaultServer does a rudimentary
* per-connection locking but it couldn't possibly guard against
* out of order Envelope processing.</p>
*/
protected void dispatch( Endpoint p, Message m )
{
// Because this class is the only one with the information
// to do it... we need to pull of the registration message
// here.
if( m instanceof ClientRegistrationMessage ) {
server.registerClient( this, p, (ClientRegistrationMessage)m );
return;
}
try {
HostedConnection source = getConnection(p);
if( source == null ) {
if( reliable ) {
// If it's a reliable connection then it's slightly more
// concerning but this can happen all the time for a UDP endpoint.
log.log( Level.WARNING, "Recieved message from unconnected endpoint:" + p + " message:" + m );
}
return;
}
messageDispatcher.messageReceived( source, m );
} catch( Exception e ) {
reportError(p, m, e);
}
}
protected MessageProtocol getMessageBuffer( Endpoint p )
{
if( !reliable ) {
// Since UDP comes in packets and they aren't split
// up, there is no reason to buffer. In fact, there would
// be a down side because there is no way for us to reliably
// clean these up later since we'd create another one for
// any random UDP packet that comes to the port.
return new MessageProtocol();
} else {
// See if we already have one
MessageProtocol result = messageBuffers.get(p);
if( result == null ) {
result = new MessageProtocol();
messageBuffers.put(p, result);
}
return result;
}
}
protected void createAndDispatch( Envelope env )
{
MessageProtocol protocol = getMessageBuffer(env.getSource());
byte[] data = env.getData();
ByteBuffer buffer = ByteBuffer.wrap(data);
int count = protocol.addBuffer( buffer );
if( count == 0 ) {
// This can happen if there was only a partial message
// received. However, this should never happen for unreliable
// connections.
if( !reliable ) {
// Log some additional information about the packet.
int len = Math.min( 10, data.length );
StringBuilder sb = new StringBuilder();
for( int i = 0; i < len; i++ ) {
sb.append( "[" + Integer.toHexString(data[i]) + "]" );
}
log.log( Level.INFO, "First 10 bytes of incomplete nessage:" + sb );
throw new RuntimeException( "Envelope contained incomplete data:" + env );
}
}
// Should be complete... and maybe we should check but we don't
Message m = null;
while( (m = protocol.getMessage()) != null ) {
m.setReliable(reliable);
dispatch( env.getSource(), m );
}
}
protected void createAndDispatch( EndpointEvent event )
{
// Only need to tell the server about disconnects
if( event.getType() == EndpointEvent.Type.REMOVE ) {
connectionClosed( event.getEndpoint() );
}
}
protected void flushEvents()
{
EndpointEvent event;
while( (event = kernel.nextEvent()) != null ) {
try {
createAndDispatch( event );
} catch( Exception e ) {
reportError(event.getEndpoint(), event, e);
}
}
}
public void run()
{
while( go.get() ) {
try {
// Check for pending events
flushEvents();
// Grab the next envelope
Envelope e = kernel.read();
if( e == Kernel.EVENTS_PENDING )
continue; // We'll catch it up above
// Check for pending events that might have
// come in while we were blocking. This is usually
// when the connection add events come through
flushEvents();
try {
createAndDispatch( e );
} catch( Exception ex ) {
reportError(e.getSource(), e, ex);
}
} catch( InterruptedException ex ) {
if( !go.get() )
return;
throw new RuntimeException( "Unexpected interruption", ex );
}
}
}
}
| engine/src/networking/com/jme3/network/base/KernelAdapter.java | /*
* Copyright (c) 2011 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jme3.network.base;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.jme3.network.*;
import com.jme3.network.kernel.Endpoint;
import com.jme3.network.kernel.EndpointEvent;
import com.jme3.network.kernel.Envelope;
import com.jme3.network.kernel.Kernel;
import com.jme3.network.message.ClientRegistrationMessage; //hopefully temporary
import com.jme3.network.serializing.Serializer;
/**
* Wraps a single Kernel and forwards new messages
* to the supplied message dispatcher and new endpoint
* events to the connection dispatcher. This is used
* by DefaultServer to manage its kernel objects.
*
* <p>This adapter assumes a simple protocol where two
* bytes define a (short) object size with the object data
* to follow. Note: this limits the size of serialized
* objects to 32676 bytes... even though, for example,
* datagram packets can hold twice that. :P</p>
*
* @version $Revision$
* @author Paul Speed
*/
public class KernelAdapter extends Thread
{
static Logger log = Logger.getLogger(KernelAdapter.class.getName());
private DefaultServer server; // this is unfortunate
private Kernel kernel;
private MessageListener<HostedConnection> messageDispatcher;
private AtomicBoolean go = new AtomicBoolean(true);
// Keeps track of the in-progress messages that are received
// on reliable connections
private Map<Endpoint, MessageProtocol> messageBuffers = new ConcurrentHashMap<Endpoint,MessageProtocol>();
// Marks the messages as reliable or not if they came
// through this connector.
private boolean reliable;
public KernelAdapter( DefaultServer server, Kernel kernel, MessageListener<HostedConnection> messageDispatcher,
boolean reliable )
{
super( String.valueOf(kernel) );
this.server = server;
this.kernel = kernel;
this.messageDispatcher = messageDispatcher;
this.reliable = reliable;
setDaemon(true);
}
public void close() throws InterruptedException
{
go.set(false);
// Kill the kernel
kernel.terminate();
}
protected void reportError( Endpoint p, Object context, Exception e )
{
// Should really be queued up so the outer thread can
// retrieve them. For now we'll just log it. FIXME
log.log( Level.SEVERE, "Unhandled error, endpoint:" + p + ", context:" + context, e );
}
protected HostedConnection getConnection( Endpoint p )
{
return server.getConnection(p);
}
protected void connectionClosed( Endpoint p )
{
// Remove any message buffer we've been accumulating
// on behalf of this endpoing
messageBuffers.remove(p);
server.connectionClosed(p);
}
/**
* Note on threading for those writing their own server
* or adapter implementations. The rule that a single connection be
* processed by only one thread at a time is more about ensuring that
* the messages are delivered in the order that they are received
* than for any user-code safety. 99% of the time the user code should
* be writing for multithreaded access anyway.
*
* <p>The issue with the messages is that if a an implementation is
* using a general thread pool then it would be possible for a
* naive implementation to have one thread grab an Envelope from
* connection 1's and another grab the next Envelope. Since an Envelope
* may contain several messages, delivering the second thread's messages
* before or during the first's would be really confusing and hard
* to code for in user code.</p>
*
* <p>And that's why this note is here. DefaultServer does a rudimentary
* per-connection locking but it couldn't possibly guard against
* out of order Envelope processing.</p>
*/
protected void dispatch( Endpoint p, Message m )
{
// Because this class is the only one with the information
// to do it... we need to pull of the registration message
// here.
if( m instanceof ClientRegistrationMessage ) {
server.registerClient( this, p, (ClientRegistrationMessage)m );
return;
}
try {
HostedConnection source = getConnection(p);
if( source == null ) {
if( reliable ) {
// If it's a reliable connection then it's slightly more
// concerning but this can happen all the time for a UDP endpoint.
log.log( Level.WARNING, "Recieved message from unconnected endpoint:" + p + " message:" + m );
}
return;
}
messageDispatcher.messageReceived( source, m );
} catch( Exception e ) {
reportError(p, m, e);
}
}
protected MessageProtocol getMessageBuffer( Endpoint p )
{
if( !reliable ) {
// Since UDP comes in packets and they aren't split
// up, there is no reason to buffer. In fact, there would
// be a down side because there is no way for us to reliably
// clean these up later since we'd create another one for
// any random UDP packet that comes to the port.
return new MessageProtocol();
} else {
// See if we already have one
MessageProtocol result = messageBuffers.get(p);
if( result != null ) {
result = new MessageProtocol();
messageBuffers.put(p, result);
}
return result;
}
}
protected void createAndDispatch( Envelope env )
{
MessageProtocol protocol = getMessageBuffer(env.getSource());
byte[] data = env.getData();
ByteBuffer buffer = ByteBuffer.wrap(data);
int count = protocol.addBuffer( buffer );
if( count == 0 ) {
// This can happen if there was only a partial message
// received. However, this should never happen for unreliable
// connections.
if( !reliable ) {
// Log some additional information about the packet.
int len = Math.min( 10, data.length );
StringBuilder sb = new StringBuilder();
for( int i = 0; i < len; i++ ) {
sb.append( "[" + Integer.toHexString(data[i]) + "]" );
}
log.log( Level.INFO, "First 10 bytes of incomplete nessage:" + sb );
throw new RuntimeException( "Envelope contained incomplete data:" + env );
}
}
// Should be complete... and maybe we should check but we don't
Message m = null;
while( (m = protocol.getMessage()) != null ) {
m.setReliable(reliable);
dispatch( env.getSource(), m );
}
}
protected void createAndDispatch( EndpointEvent event )
{
// Only need to tell the server about disconnects
if( event.getType() == EndpointEvent.Type.REMOVE ) {
connectionClosed( event.getEndpoint() );
}
}
protected void flushEvents()
{
EndpointEvent event;
while( (event = kernel.nextEvent()) != null ) {
try {
createAndDispatch( event );
} catch( Exception e ) {
reportError(event.getEndpoint(), event, e);
}
}
}
public void run()
{
while( go.get() ) {
try {
// Check for pending events
flushEvents();
// Grab the next envelope
Envelope e = kernel.read();
if( e == Kernel.EVENTS_PENDING )
continue; // We'll catch it up above
// Check for pending events that might have
// come in while we were blocking. This is usually
// when the connection add events come through
flushEvents();
try {
createAndDispatch( e );
} catch( Exception ex ) {
reportError(e.getSource(), e, ex);
}
} catch( InterruptedException ex ) {
if( !go.get() )
return;
throw new RuntimeException( "Unexpected interruption", ex );
}
}
}
}
| Fixing a pretty significant typo.
git-svn-id: 5afc437a751a4ff2ced778146f5faadda0b504ab@7450 75d07b2b-3a1a-0410-a2c5-0572b91ccdca
| engine/src/networking/com/jme3/network/base/KernelAdapter.java | Fixing a pretty significant typo. |
|
Java | bsd-3-clause | bc658656237962730671d49291e3af0721c4d6e9 | 0 | krishagni/openspecimen,krishagni/openspecimen,krishagni/openspecimen |
package com.krishagni.catissueplus.core.biospecimen.services.impl;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.hibernate.SessionFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.krishagni.catissueplus.core.administrative.domain.Site;
import com.krishagni.catissueplus.core.administrative.domain.StorageContainer;
import com.krishagni.catissueplus.core.administrative.domain.User;
import com.krishagni.catissueplus.core.administrative.events.SiteSummary;
import com.krishagni.catissueplus.core.audit.services.impl.DeleteLogUtil;
import com.krishagni.catissueplus.core.biospecimen.ConfigParams;
import com.krishagni.catissueplus.core.biospecimen.WorkflowUtil;
import com.krishagni.catissueplus.core.biospecimen.domain.AliquotSpecimensRequirement;
import com.krishagni.catissueplus.core.biospecimen.domain.CollectionProtocol;
import com.krishagni.catissueplus.core.biospecimen.domain.CollectionProtocolEvent;
import com.krishagni.catissueplus.core.biospecimen.domain.CollectionProtocolRegistration;
import com.krishagni.catissueplus.core.biospecimen.domain.CollectionProtocolSite;
import com.krishagni.catissueplus.core.biospecimen.domain.ConsentStatement;
import com.krishagni.catissueplus.core.biospecimen.domain.CpConsentTier;
import com.krishagni.catissueplus.core.biospecimen.domain.CpReportSettings;
import com.krishagni.catissueplus.core.biospecimen.domain.CpWorkflowConfig;
import com.krishagni.catissueplus.core.biospecimen.domain.CpWorkflowConfig.Workflow;
import com.krishagni.catissueplus.core.biospecimen.domain.DerivedSpecimenRequirement;
import com.krishagni.catissueplus.core.biospecimen.domain.PdeNotif;
import com.krishagni.catissueplus.core.biospecimen.domain.PdeNotifLink;
import com.krishagni.catissueplus.core.biospecimen.domain.Specimen;
import com.krishagni.catissueplus.core.biospecimen.domain.SpecimenRequirement;
import com.krishagni.catissueplus.core.biospecimen.domain.Visit;
import com.krishagni.catissueplus.core.biospecimen.domain.factory.CollectionProtocolFactory;
import com.krishagni.catissueplus.core.biospecimen.domain.factory.ConsentStatementErrorCode;
import com.krishagni.catissueplus.core.biospecimen.domain.factory.CpErrorCode;
import com.krishagni.catissueplus.core.biospecimen.domain.factory.CpReportSettingsFactory;
import com.krishagni.catissueplus.core.biospecimen.domain.factory.CpeErrorCode;
import com.krishagni.catissueplus.core.biospecimen.domain.factory.CpeFactory;
import com.krishagni.catissueplus.core.biospecimen.domain.factory.CprErrorCode;
import com.krishagni.catissueplus.core.biospecimen.domain.factory.SpecimenRequirementFactory;
import com.krishagni.catissueplus.core.biospecimen.domain.factory.SrErrorCode;
import com.krishagni.catissueplus.core.biospecimen.events.CollectionProtocolDetail;
import com.krishagni.catissueplus.core.biospecimen.events.CollectionProtocolEventDetail;
import com.krishagni.catissueplus.core.biospecimen.events.CollectionProtocolSummary;
import com.krishagni.catissueplus.core.biospecimen.events.ConsentTierDetail;
import com.krishagni.catissueplus.core.biospecimen.events.ConsentTierOp;
import com.krishagni.catissueplus.core.biospecimen.events.ConsentTierOp.OP;
import com.krishagni.catissueplus.core.biospecimen.events.CopyCpOpDetail;
import com.krishagni.catissueplus.core.biospecimen.events.CopyCpeOpDetail;
import com.krishagni.catissueplus.core.biospecimen.events.CpQueryCriteria;
import com.krishagni.catissueplus.core.biospecimen.events.CpReportSettingsDetail;
import com.krishagni.catissueplus.core.biospecimen.events.CpWorkflowCfgDetail;
import com.krishagni.catissueplus.core.biospecimen.events.CprSummary;
import com.krishagni.catissueplus.core.biospecimen.events.FileDetail;
import com.krishagni.catissueplus.core.biospecimen.events.MergeCpDetail;
import com.krishagni.catissueplus.core.biospecimen.events.PdeTokenDetail;
import com.krishagni.catissueplus.core.biospecimen.events.SpecimenPoolRequirements;
import com.krishagni.catissueplus.core.biospecimen.events.SpecimenRequirementDetail;
import com.krishagni.catissueplus.core.biospecimen.events.WorkflowDetail;
import com.krishagni.catissueplus.core.biospecimen.repository.CollectionProtocolDao;
import com.krishagni.catissueplus.core.biospecimen.repository.CpListCriteria;
import com.krishagni.catissueplus.core.biospecimen.repository.CprListCriteria;
import com.krishagni.catissueplus.core.biospecimen.repository.DaoFactory;
import com.krishagni.catissueplus.core.biospecimen.repository.PdeNotifListCriteria;
import com.krishagni.catissueplus.core.biospecimen.repository.impl.BiospecimenDaoHelper;
import com.krishagni.catissueplus.core.biospecimen.services.CollectionProtocolService;
import com.krishagni.catissueplus.core.biospecimen.services.PdeTokenGenerator;
import com.krishagni.catissueplus.core.biospecimen.services.PdeTokenGeneratorRegistry;
import com.krishagni.catissueplus.core.common.PlusTransactional;
import com.krishagni.catissueplus.core.common.Tuple;
import com.krishagni.catissueplus.core.common.access.AccessCtrlMgr;
import com.krishagni.catissueplus.core.common.access.AccessCtrlMgr.ParticipantReadAccess;
import com.krishagni.catissueplus.core.common.access.SiteCpPair;
import com.krishagni.catissueplus.core.common.domain.Notification;
import com.krishagni.catissueplus.core.common.errors.ErrorType;
import com.krishagni.catissueplus.core.common.errors.OpenSpecimenException;
import com.krishagni.catissueplus.core.common.events.BulkDeleteEntityOp;
import com.krishagni.catissueplus.core.common.events.BulkDeleteEntityResp;
import com.krishagni.catissueplus.core.common.events.DependentEntityDetail;
import com.krishagni.catissueplus.core.common.events.RequestEvent;
import com.krishagni.catissueplus.core.common.events.ResponseEvent;
import com.krishagni.catissueplus.core.common.service.ObjectAccessor;
import com.krishagni.catissueplus.core.common.service.StarredItemService;
import com.krishagni.catissueplus.core.common.util.AuthUtil;
import com.krishagni.catissueplus.core.common.util.ConfigUtil;
import com.krishagni.catissueplus.core.common.util.EmailUtil;
import com.krishagni.catissueplus.core.common.util.MessageUtil;
import com.krishagni.catissueplus.core.common.util.NotifUtil;
import com.krishagni.catissueplus.core.common.util.Status;
import com.krishagni.catissueplus.core.common.util.Utility;
import com.krishagni.catissueplus.core.init.AppProperties;
import com.krishagni.catissueplus.core.query.Column;
import com.krishagni.catissueplus.core.query.ListConfig;
import com.krishagni.catissueplus.core.query.ListDetail;
import com.krishagni.catissueplus.core.query.ListService;
import com.krishagni.catissueplus.core.query.Row;
import com.krishagni.rbac.common.errors.RbacErrorCode;
import com.krishagni.rbac.events.SubjectRoleOpNotif;
import com.krishagni.rbac.service.RbacService;
public class CollectionProtocolServiceImpl implements CollectionProtocolService, ObjectAccessor, InitializingBean {
private ThreadPoolTaskExecutor taskExecutor;
private CollectionProtocolFactory cpFactory;
private CpeFactory cpeFactory;
private SpecimenRequirementFactory srFactory;
private DaoFactory daoFactory;
private RbacService rbacSvc;
private ListService listSvc;
private CpReportSettingsFactory rptSettingsFactory;
private SessionFactory sessionFactory;
private StarredItemService starredItemSvc;
private PdeTokenGeneratorRegistry pdeTokenGeneratorRegistry;
public void setTaskExecutor(ThreadPoolTaskExecutor taskExecutor) {
this.taskExecutor = taskExecutor;
}
public void setCpFactory(CollectionProtocolFactory cpFactory) {
this.cpFactory = cpFactory;
}
public void setCpeFactory(CpeFactory cpeFactory) {
this.cpeFactory = cpeFactory;
}
public void setSrFactory(SpecimenRequirementFactory srFactory) {
this.srFactory = srFactory;
}
public void setDaoFactory(DaoFactory daoFactory) {
this.daoFactory = daoFactory;
}
public void setRbacSvc(RbacService rbacSvc) {
this.rbacSvc = rbacSvc;
}
public void setListSvc(ListService listSvc) {
this.listSvc = listSvc;
}
public void setRptSettingsFactory(CpReportSettingsFactory rptSettingsFactory) {
this.rptSettingsFactory = rptSettingsFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public void setStarredItemSvc(StarredItemService starredItemSvc) {
this.starredItemSvc = starredItemSvc;
}
public void setPdeTokenGeneratorRegistry(PdeTokenGeneratorRegistry pdeTokenGeneratorRegistry) {
this.pdeTokenGeneratorRegistry = pdeTokenGeneratorRegistry;
}
@Override
@PlusTransactional
public ResponseEvent<List<CollectionProtocolSummary>> getProtocols(RequestEvent<CpListCriteria> req) {
try {
CpListCriteria crit = addCpListCriteria(req.getPayload());
if (crit == null) {
return ResponseEvent.response(Collections.emptyList());
}
return ResponseEvent.response(daoFactory.getCollectionProtocolDao().getCollectionProtocols(crit));
} catch (OpenSpecimenException oce) {
return ResponseEvent.error(oce);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<Long> getProtocolsCount(RequestEvent<CpListCriteria> req) {
try {
CpListCriteria crit = addCpListCriteria(req.getPayload());
if (crit == null) {
return ResponseEvent.response(0L);
}
return ResponseEvent.response(daoFactory.getCollectionProtocolDao().getCpCount(crit));
} catch (OpenSpecimenException oce) {
return ResponseEvent.error(oce);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<CollectionProtocolDetail> getCollectionProtocol(RequestEvent<CpQueryCriteria> req) {
try {
CpQueryCriteria crit = req.getPayload();
CollectionProtocol cp = getCollectionProtocol(crit.getId(), crit.getTitle(), crit.getShortTitle());
AccessCtrlMgr.getInstance().ensureReadCpRights(cp);
return ResponseEvent.response(CollectionProtocolDetail.from(cp, crit.isFullObject()));
} catch (OpenSpecimenException oce) {
return ResponseEvent.error(oce);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<SiteSummary>> getSites(RequestEvent<CpQueryCriteria> req) {
try {
CpQueryCriteria crit = req.getPayload();
CollectionProtocol cp = getCollectionProtocol(crit.getId(), crit.getTitle(), crit.getShortTitle());
AccessCtrlMgr.getInstance().ensureReadCpRights(cp);
List<Site> sites = cp.getSites().stream().map(CollectionProtocolSite::getSite).collect(Collectors.toList());
return ResponseEvent.response(SiteSummary.from(sites));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<CprSummary>> getRegisteredParticipants(RequestEvent<CprListCriteria> req) {
try {
CprListCriteria listCrit = addCprListCriteria(req.getPayload());
if (listCrit == null) {
return ResponseEvent.response(Collections.emptyList());
}
return ResponseEvent.response(daoFactory.getCprDao().getCprList(listCrit));
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<Long> getRegisteredParticipantsCount(RequestEvent<CprListCriteria> req) {
try {
CprListCriteria listCrit = addCprListCriteria(req.getPayload());
if (listCrit == null) {
return ResponseEvent.response(0L);
}
return ResponseEvent.response(daoFactory.getCprDao().getCprCount(listCrit));
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<CollectionProtocolDetail> createCollectionProtocol(RequestEvent<CollectionProtocolDetail> req) {
try {
CollectionProtocol cp = createCollectionProtocol(req.getPayload(), null, false);
notifyUsersOnCpCreate(cp);
return ResponseEvent.response(CollectionProtocolDetail.from(cp));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<CollectionProtocolDetail> updateCollectionProtocol(RequestEvent<CollectionProtocolDetail> req) {
try {
CollectionProtocolDetail detail = req.getPayload();
CollectionProtocol existingCp = daoFactory.getCollectionProtocolDao().getById(detail.getId());
if (existingCp == null) {
return ResponseEvent.userError(CpErrorCode.NOT_FOUND);
}
AccessCtrlMgr.getInstance().ensureUpdateCpRights(existingCp);
CollectionProtocol cp = cpFactory.createCollectionProtocol(detail);
AccessCtrlMgr.getInstance().ensureUpdateCpRights(cp);
ensureUsersBelongtoCpSites(cp);
OpenSpecimenException ose = new OpenSpecimenException(ErrorType.USER_ERROR);
ensureUniqueTitle(existingCp, cp, ose);
ensureUniqueShortTitle(existingCp, cp, ose);
ensureUniqueCode(existingCp, cp, ose);
ensureUniqueCpSiteCode(cp, ose);
if (existingCp.isConsentsWaived() != cp.isConsentsWaived()) {
ensureConsentTierIsEmpty(existingCp, ose);
}
ose.checkAndThrow();
User oldPi = existingCp.getPrincipalInvestigator();
Collection<User> addedCoord = Utility.subtract(cp.getCoordinators(), existingCp.getCoordinators());
Collection<User> removedCoord = Utility.subtract(existingCp.getCoordinators(), cp.getCoordinators());
Set<Site> addedSites = Utility.subtract(cp.getRepositories(), existingCp.getRepositories());
Set<Site> removedSites = Utility.subtract(existingCp.getRepositories(), cp.getRepositories());
ensureSitesAreNotInUse(existingCp, removedSites);
existingCp.update(cp);
existingCp.addOrUpdateExtension();
fixSopDocumentName(existingCp);
// PI and coordinators role handling
addOrRemovePiCoordinatorRoles(cp, "UPDATE", oldPi, cp.getPrincipalInvestigator(), addedCoord, removedCoord);
notifyUsersOnCpUpdate(existingCp, addedSites, removedSites);
return ResponseEvent.response(CollectionProtocolDetail.from(existingCp));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<CollectionProtocolDetail> copyCollectionProtocol(RequestEvent<CopyCpOpDetail> req) {
try {
CopyCpOpDetail opDetail = req.getPayload();
Long cpId = opDetail.getCpId();
CollectionProtocol existing = daoFactory.getCollectionProtocolDao().getById(cpId);
if (existing == null) {
throw OpenSpecimenException.userError(CpErrorCode.NOT_FOUND);
}
AccessCtrlMgr.getInstance().ensureReadCpRights(existing);
CollectionProtocol cp = createCollectionProtocol(opDetail.getCp(), existing, true);
notifyUsersOnCpCreate(cp);
return ResponseEvent.response(CollectionProtocolDetail.from(cp));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<MergeCpDetail> mergeCollectionProtocols(RequestEvent<MergeCpDetail> req) {
AccessCtrlMgr.getInstance().ensureUserIsAdmin();
CollectionProtocol srcCp = getCollectionProtocol(req.getPayload().getSrcCpShortTitle());
CollectionProtocol tgtCp = getCollectionProtocol(req.getPayload().getTgtCpShortTitle());
ensureMergeableCps(srcCp, tgtCp);
int maxRecords = 30;
boolean moreRecords = true;
while (moreRecords) {
List<CollectionProtocolRegistration> cprs = daoFactory.getCprDao().getCprsByCpId(srcCp.getId(), 0, maxRecords);
for (CollectionProtocolRegistration srcCpr: cprs) {
mergeCprIntoCp(srcCpr, tgtCp);
}
if (cprs.size() < maxRecords) {
moreRecords = false;
}
}
return ResponseEvent.response(req.getPayload());
}
@PlusTransactional
public ResponseEvent<CollectionProtocolDetail> updateConsentsWaived(RequestEvent<CollectionProtocolDetail> req) {
try {
CollectionProtocolDetail detail = req.getPayload();
CollectionProtocol existingCp = daoFactory.getCollectionProtocolDao().getById(detail.getId());
if (existingCp == null) {
return ResponseEvent.userError(CpErrorCode.NOT_FOUND);
}
AccessCtrlMgr.getInstance().ensureUpdateCpRights(existingCp);
if (CollectionUtils.isNotEmpty(existingCp.getConsentTier())) {
return ResponseEvent.userError(CpErrorCode.CONSENT_TIER_FOUND, existingCp.getShortTitle());
}
existingCp.setConsentsWaived(detail.getConsentsWaived());
return ResponseEvent.response(CollectionProtocolDetail.from(existingCp));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@PlusTransactional
public ResponseEvent<List<DependentEntityDetail>> getCpDependentEntities(RequestEvent<Long> req) {
try {
CollectionProtocol existingCp = daoFactory.getCollectionProtocolDao().getById(req.getPayload());
if (existingCp == null) {
return ResponseEvent.userError(CpErrorCode.NOT_FOUND);
}
return ResponseEvent.response(existingCp.getDependentEntities());
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<BulkDeleteEntityResp<CollectionProtocolDetail>> deleteCollectionProtocols(RequestEvent<BulkDeleteEntityOp> req) {
try {
BulkDeleteEntityOp crit = req.getPayload();
Set<Long> cpIds = crit.getIds();
List<CollectionProtocol> cps = daoFactory.getCollectionProtocolDao().getByIds(cpIds);
if (crit.getIds().size() != cps.size()) {
cps.forEach(cp -> cpIds.remove(cp.getId()));
throw OpenSpecimenException.userError(CpErrorCode.DOES_NOT_EXIST, cpIds);
}
for (CollectionProtocol cp : cps) {
AccessCtrlMgr.getInstance().ensureDeleteCpRights(cp);
}
boolean completed = crit.isForceDelete() ? forceDeleteCps(cps, crit.getReason()) : deleteCps(cps, crit.getReason());
BulkDeleteEntityResp<CollectionProtocolDetail> resp = new BulkDeleteEntityResp<>();
resp.setCompleted(completed);
resp.setEntities(CollectionProtocolDetail.from(cps));
return ResponseEvent.response(resp);
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<File> getSopDocument(RequestEvent<Long> req) {
try {
Long cpId = req.getPayload();
CollectionProtocol cp = daoFactory.getCollectionProtocolDao().getById(cpId);
if (cp == null) {
return ResponseEvent.userError(CprErrorCode.NOT_FOUND);
}
AccessCtrlMgr.getInstance().ensureReadCpRights(cp);
String filename = cp.getSopDocumentName();
File file = null;
if (StringUtils.isBlank(filename)) {
file = ConfigUtil.getInstance().getFileSetting(ConfigParams.MODULE, ConfigParams.CP_SOP_DOC, null);
} else {
file = new File(getSopDocDir() + filename);
if (!file.exists()) {
filename = filename.split("_", 2)[1];
return ResponseEvent.userError(CpErrorCode.SOP_DOC_MOVED_OR_DELETED, cp.getShortTitle(), filename);
}
}
if (file == null) {
return ResponseEvent.userError(CpErrorCode.SOP_DOC_NOT_FOUND, cp.getShortTitle());
}
return ResponseEvent.response(file);
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
public ResponseEvent<String> uploadSopDocument(RequestEvent<FileDetail> req) {
OutputStream out = null;
try {
FileDetail detail = req.getPayload();
String filename = UUID.randomUUID() + "_" + detail.getFilename();
File file = new File(getSopDocDir() + filename);
out = new FileOutputStream(file);
IOUtils.copy(detail.getFileIn(), out);
return ResponseEvent.response(filename);
} catch (Exception e) {
return ResponseEvent.serverError(e);
} finally {
IOUtils.closeQuietly(out);
}
}
@Override
@PlusTransactional
public ResponseEvent<CollectionProtocolDetail> importCollectionProtocol(RequestEvent<CollectionProtocolDetail> req) {
try {
CollectionProtocolDetail cpDetail = req.getPayload();
ResponseEvent<CollectionProtocolDetail> resp = createCollectionProtocol(req);
resp.throwErrorIfUnsuccessful();
Long cpId = resp.getPayload().getId();
importConsents(cpId, cpDetail.getConsents());
importEvents(cpDetail.getTitle(), cpDetail.getEvents());
importWorkflows(cpId, cpDetail.getWorkflows());
return resp;
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<Boolean> isSpecimenBarcodingEnabled() {
try {
boolean isEnabled = ConfigUtil.getInstance().getBoolSetting(
ConfigParams.MODULE, ConfigParams.ENABLE_SPMN_BARCODING, false);
if (!isEnabled) {
isEnabled = daoFactory.getCollectionProtocolDao().anyBarcodingEnabledCpExists();
}
return ResponseEvent.response(isEnabled);
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<ConsentTierDetail>> getConsentTiers(RequestEvent<Long> req) {
Long cpId = req.getPayload();
try {
CollectionProtocol cp = daoFactory.getCollectionProtocolDao().getById(cpId);
if (cp == null) {
return ResponseEvent.userError(CpErrorCode.NOT_FOUND);
}
AccessCtrlMgr.getInstance().ensureReadCpRights(cp);
return ResponseEvent.response(ConsentTierDetail.from(cp.getConsentTier()));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<ConsentTierDetail> updateConsentTier(RequestEvent<ConsentTierOp> req) {
try {
ConsentTierOp opDetail = req.getPayload();
CollectionProtocol cp = daoFactory.getCollectionProtocolDao().getById(opDetail.getCpId());
if (cp == null) {
return ResponseEvent.userError(CpErrorCode.NOT_FOUND);
}
AccessCtrlMgr.getInstance().ensureUpdateCpRights(cp);
if (cp.isConsentsWaived()) {
return ResponseEvent.userError(CpErrorCode.CONSENTS_WAIVED, cp.getShortTitle());
}
ConsentTierDetail input = opDetail.getConsentTier();
CpConsentTier resp = null;
ConsentStatement stmt = null;
switch (opDetail.getOp()) {
case ADD:
ensureUniqueConsentStatement(input, cp);
stmt = getStatement(input.getStatementId(), input.getStatementCode(), input.getStatement());
resp = cp.addConsentTier(getConsentTierObj(input.getId(), stmt));
break;
case UPDATE:
ensureUniqueConsentStatement(input, cp);
stmt = getStatement(input.getStatementId(), input.getStatementCode(), input.getStatement());
resp = cp.updateConsentTier(getConsentTierObj(input.getId(), stmt));
break;
case REMOVE:
resp = cp.removeConsentTier(input.getId());
break;
}
if (resp != null) {
daoFactory.getCollectionProtocolDao().saveOrUpdate(cp, true);
}
return ResponseEvent.response(ConsentTierDetail.from(resp));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<DependentEntityDetail>> getConsentDependentEntities(RequestEvent<ConsentTierDetail> req) {
try {
ConsentTierDetail consentTierDetail = req.getPayload();
CpConsentTier consentTier = getConsentTier(consentTierDetail);
return ResponseEvent.response(consentTier.getDependentEntities());
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch(Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<CollectionProtocolEventDetail>> getProtocolEvents(RequestEvent<Long> req) {
Long cpId = req.getPayload();
try {
CollectionProtocol cp = daoFactory.getCollectionProtocolDao().getById(cpId);
if (cp == null) {
return ResponseEvent.userError(CpErrorCode.NOT_FOUND);
}
AccessCtrlMgr.getInstance().ensureReadCpRights(cp);
return ResponseEvent.response(CollectionProtocolEventDetail.from(cp.getOrderedCpeList()));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<CollectionProtocolEventDetail> getProtocolEvent(RequestEvent<Long> req) {
Long cpeId = req.getPayload();
try {
CollectionProtocolEvent cpe = daoFactory.getCollectionProtocolDao().getCpe(cpeId);
if (cpe == null) {
return ResponseEvent.userError(CpeErrorCode.NOT_FOUND, cpeId, 1);
}
CollectionProtocol cp = cpe.getCollectionProtocol();
AccessCtrlMgr.getInstance().ensureReadCpRights(cp);
if (cpe.getEventPoint() != null) {
CollectionProtocolEvent firstEvent = cp.firstEvent();
if (firstEvent.getEventPoint() != null) {
cpe.setOffset(firstEvent.getEventPoint());
cpe.setOffsetUnit(firstEvent.getEventPointUnit());
}
}
return ResponseEvent.response(CollectionProtocolEventDetail.from(cpe));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<CollectionProtocolEventDetail> addEvent(RequestEvent<CollectionProtocolEventDetail> req) {
try {
CollectionProtocolEvent cpe = cpeFactory.createCpe(req.getPayload());
CollectionProtocol cp = cpe.getCollectionProtocol();
AccessCtrlMgr.getInstance().ensureUpdateCpRights(cp);
cp.addCpe(cpe);
daoFactory.getCollectionProtocolDao().saveOrUpdate(cp, true);
return ResponseEvent.response(CollectionProtocolEventDetail.from(cpe));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<CollectionProtocolEventDetail> updateEvent(RequestEvent<CollectionProtocolEventDetail> req) {
try {
CollectionProtocolEvent cpe = cpeFactory.createCpe(req.getPayload());
CollectionProtocol cp = cpe.getCollectionProtocol();
AccessCtrlMgr.getInstance().ensureUpdateCpRights(cp);
cp.updateCpe(cpe);
return ResponseEvent.response(CollectionProtocolEventDetail.from(cpe));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<CollectionProtocolEventDetail> copyEvent(RequestEvent<CopyCpeOpDetail> req) {
try {
CollectionProtocolDao cpDao = daoFactory.getCollectionProtocolDao();
CopyCpeOpDetail opDetail = req.getPayload();
String cpTitle = opDetail.getCollectionProtocol();
String eventLabel = opDetail.getEventLabel();
CollectionProtocolEvent existing = null;
Object key = null;
if (opDetail.getEventId() != null) {
existing = cpDao.getCpe(opDetail.getEventId());
key = opDetail.getEventId();
} else if (!StringUtils.isBlank(eventLabel) && !StringUtils.isBlank(cpTitle)) {
existing = cpDao.getCpeByEventLabel(cpTitle, eventLabel);
key = eventLabel;
}
if (existing == null) {
throw OpenSpecimenException.userError(CpeErrorCode.NOT_FOUND, key, 1);
}
CollectionProtocol cp = existing.getCollectionProtocol();
AccessCtrlMgr.getInstance().ensureUpdateCpRights(cp);
CollectionProtocolEvent cpe = cpeFactory.createCpeCopy(opDetail.getCpe(), existing);
existing.copySpecimenRequirementsTo(cpe);
cp.addCpe(cpe);
cpDao.saveOrUpdate(cp, true);
return ResponseEvent.response(CollectionProtocolEventDetail.from(cpe));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<CollectionProtocolEventDetail> deleteEvent(RequestEvent<Long> req) {
try {
Long cpeId = req.getPayload();
CollectionProtocolEvent cpe = daoFactory.getCollectionProtocolDao().getCpe(cpeId);
if (cpe == null) {
throw OpenSpecimenException.userError(CpeErrorCode.NOT_FOUND, cpeId, 1);
}
CollectionProtocol cp = cpe.getCollectionProtocol();
AccessCtrlMgr.getInstance().ensureUpdateCpRights(cp);
cpe.delete();
daoFactory.getCollectionProtocolDao().saveCpe(cpe);
return ResponseEvent.response(CollectionProtocolEventDetail.from(cpe));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<SpecimenRequirementDetail>> getSpecimenRequirments(RequestEvent<Tuple> req) {
try {
Tuple tuple = req.getPayload();
Long cpId = tuple.element(0);
Long cpeId = tuple.element(1);
String cpeLabel = tuple.element(2);
boolean includeChildren = tuple.element(3) == null || (Boolean) tuple.element(3);
CollectionProtocolEvent cpe = null;
Object key = null;
if (cpeId != null) {
cpe = daoFactory.getCollectionProtocolDao().getCpe(cpeId);
key = cpeId;
} else if (StringUtils.isNotBlank(cpeLabel)) {
if (cpId == null) {
throw OpenSpecimenException.userError(CpErrorCode.REQUIRED);
}
cpe = daoFactory.getCollectionProtocolDao().getCpeByEventLabel(cpId, cpeLabel);
key = cpeLabel;
}
if (key == null) {
return ResponseEvent.response(Collections.emptyList());
} else if (cpe == null) {
return ResponseEvent.userError(CpeErrorCode.NOT_FOUND, key, 1);
}
AccessCtrlMgr.getInstance().ensureReadCpRights(cpe.getCollectionProtocol());
return ResponseEvent.response(SpecimenRequirementDetail.from(cpe.getTopLevelAnticipatedSpecimens(), includeChildren));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<SpecimenRequirementDetail> getSpecimenRequirement(RequestEvent<Long> req) {
Long reqId = req.getPayload();
try {
SpecimenRequirement sr = daoFactory.getSpecimenRequirementDao().getById(reqId);
if (sr == null) {
return ResponseEvent.userError(SrErrorCode.NOT_FOUND);
}
AccessCtrlMgr.getInstance().ensureReadCpRights(sr.getCollectionProtocol());
return ResponseEvent.response(SpecimenRequirementDetail.from(sr));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<SpecimenRequirementDetail> addSpecimenRequirement(RequestEvent<SpecimenRequirementDetail> req) {
try {
SpecimenRequirement requirement = srFactory.createSpecimenRequirement(req.getPayload());
CollectionProtocolEvent cpe = requirement.getCollectionProtocolEvent();
AccessCtrlMgr.getInstance().ensureUpdateCpRights(cpe.getCollectionProtocol());
cpe.addSpecimenRequirement(requirement);
daoFactory.getCollectionProtocolDao().saveCpe(cpe, true);
return ResponseEvent.response(SpecimenRequirementDetail.from(requirement));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<SpecimenRequirementDetail>> addSpecimenPoolReqs(RequestEvent<SpecimenPoolRequirements> req) {
try {
List<SpecimenRequirement> spmnPoolReqs = srFactory.createSpecimenPoolReqs(req.getPayload());
SpecimenRequirement pooledReq = spmnPoolReqs.iterator().next().getPooledSpecimenRequirement();
AccessCtrlMgr.getInstance().ensureUpdateCpRights(pooledReq.getCollectionProtocol());
pooledReq.getCollectionProtocolEvent().ensureUniqueSrCodes(spmnPoolReqs);
pooledReq.addSpecimenPoolReqs(spmnPoolReqs);
daoFactory.getSpecimenRequirementDao().saveOrUpdate(pooledReq, true);
return ResponseEvent.response(SpecimenRequirementDetail.from(spmnPoolReqs));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<SpecimenRequirementDetail>> createAliquots(RequestEvent<AliquotSpecimensRequirement> req) {
try {
return ResponseEvent.response(SpecimenRequirementDetail.from(createAliquots(req.getPayload())));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<SpecimenRequirementDetail> createDerived(RequestEvent<DerivedSpecimenRequirement> req) {
try {
DerivedSpecimenRequirement requirement = req.getPayload();
SpecimenRequirement derived = srFactory.createDerived(requirement);
AccessCtrlMgr.getInstance().ensureUpdateCpRights(derived.getCollectionProtocol());
ensureSrIsNotClosed(derived.getParentSpecimenRequirement());
if (StringUtils.isNotBlank(derived.getCode())) {
if (derived.getCollectionProtocolEvent().getSrByCode(derived.getCode()) != null) {
return ResponseEvent.userError(SrErrorCode.DUP_CODE, derived.getCode());
}
}
daoFactory.getSpecimenRequirementDao().saveOrUpdate(derived, true);
return ResponseEvent.response(SpecimenRequirementDetail.from(derived));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<SpecimenRequirementDetail> updateSpecimenRequirement(RequestEvent<SpecimenRequirementDetail> req) {
try {
SpecimenRequirementDetail detail = req.getPayload();
Long srId = detail.getId();
SpecimenRequirement sr = daoFactory.getSpecimenRequirementDao().getById(srId);
if (sr == null) {
throw OpenSpecimenException.userError(SrErrorCode.NOT_FOUND);
}
AccessCtrlMgr.getInstance().ensureUpdateCpRights(sr.getCollectionProtocol());
SpecimenRequirement partial = srFactory.createForUpdate(sr.getLineage(), detail);
if (isSpecimenClassOrTypeChanged(sr, partial)) {
ensureSpecimensNotCollected(sr);
}
sr.update(partial);
return ResponseEvent.response(SpecimenRequirementDetail.from(sr));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<SpecimenRequirementDetail> copySpecimenRequirement(RequestEvent<Long> req) {
try {
Long srId = req.getPayload();
SpecimenRequirement sr = daoFactory.getSpecimenRequirementDao().getById(srId);
if (sr == null) {
throw OpenSpecimenException.userError(SrErrorCode.NOT_FOUND);
}
AccessCtrlMgr.getInstance().ensureUpdateCpRights(sr.getCollectionProtocol());
SpecimenRequirement copy = sr.deepCopy(null);
daoFactory.getSpecimenRequirementDao().saveOrUpdate(copy, true);
return ResponseEvent.response(SpecimenRequirementDetail.from(copy));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<SpecimenRequirementDetail> deleteSpecimenRequirement(RequestEvent<Long> req) {
try {
Long srId = req.getPayload();
SpecimenRequirement sr = daoFactory.getSpecimenRequirementDao().getById(srId);
if (sr == null) {
throw OpenSpecimenException.userError(SrErrorCode.NOT_FOUND);
}
AccessCtrlMgr.getInstance().ensureUpdateCpRights(sr.getCollectionProtocol());
sr.delete();
daoFactory.getSpecimenRequirementDao().saveOrUpdate(sr);
return ResponseEvent.response(SpecimenRequirementDetail.from(sr));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<Integer> getSrSpecimensCount(RequestEvent<Long> req) {
try {
Long srId = req.getPayload();
SpecimenRequirement sr = daoFactory.getSpecimenRequirementDao().getById(srId);
if (sr == null) {
throw OpenSpecimenException.userError(SrErrorCode.NOT_FOUND);
}
return ResponseEvent.response(
daoFactory.getSpecimenRequirementDao().getSpecimensCount(srId));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<PdeTokenDetail>> getPdeLinks(RequestEvent<PdeNotifListCriteria> req) {
try {
PdeNotifListCriteria crit = req.getPayload();
List<PdeNotif> notifs = daoFactory.getPdeNotifDao().getNotifs(crit);
Map<String, List<Long>> tokenIdsByType = new HashMap<>();
for (PdeNotif notif : notifs) {
for (PdeNotifLink link : notif.getLinks()) {
List<Long> tokenIds = tokenIdsByType.computeIfAbsent(link.getType(), (k) -> new ArrayList<>());
tokenIds.add(link.getTokenId());
}
}
Map<String, PdeTokenDetail> tokensMap = new HashMap<>();
for (Map.Entry<String, List<Long>> typeTokenIds : tokenIdsByType.entrySet()) {
PdeTokenGenerator generator = pdeTokenGeneratorRegistry.get(typeTokenIds.getKey());
if (generator == null) {
continue;
}
List<PdeTokenDetail> tokens = generator.getTokens(typeTokenIds.getValue());
for (PdeTokenDetail token : tokens) {
tokensMap.put(token.getType() + ":" + token.getTokenId(), token);
}
}
List<PdeTokenDetail> result = new ArrayList<>();
for (PdeNotif notif : notifs) {
for (PdeNotifLink link : notif.getLinks()) {
PdeTokenDetail token = tokensMap.get(link.getType() + ":" + link.getTokenId());
token.setToken(null);
token.setDataEntryLink(null);
if (token != null) {
result.add(token);
}
}
}
return ResponseEvent.response(result);
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<CpReportSettingsDetail> getReportSettings(RequestEvent<CpQueryCriteria> req) {
try {
CpReportSettings settings = getReportSetting(req.getPayload());
if (settings == null) {
return ResponseEvent.response(null);
}
AccessCtrlMgr.getInstance().ensureReadCpRights(settings.getCp());
return ResponseEvent.response(CpReportSettingsDetail.from(settings));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<CpReportSettingsDetail> saveReportSettings(RequestEvent<CpReportSettingsDetail> req) {
try {
CpReportSettings settings = rptSettingsFactory.createSettings(req.getPayload());
CollectionProtocol cp = settings.getCp();
AccessCtrlMgr.getInstance().ensureUpdateCpRights(cp);
CpReportSettings existing = daoFactory.getCpReportSettingsDao().getByCp(cp.getId());
if (existing == null) {
existing = settings;
} else {
existing.update(settings);
}
daoFactory.getCpReportSettingsDao().saveOrUpdate(existing);
return ResponseEvent.response(CpReportSettingsDetail.from(existing));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<CpReportSettingsDetail> deleteReportSettings(RequestEvent<CpQueryCriteria> req) {
try {
CpReportSettings settings = getReportSetting(req.getPayload());
if (settings == null) {
return ResponseEvent.response(null);
}
AccessCtrlMgr.getInstance().ensureUpdateCpRights(settings.getCp());
settings.delete();
return ResponseEvent.response(CpReportSettingsDetail.from(settings));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<Boolean> generateReport(RequestEvent<CpQueryCriteria> req) {
try {
CpQueryCriteria crit = req.getPayload();
CollectionProtocol cp = getCollectionProtocol(crit.getId(), crit.getTitle(), crit.getShortTitle());
AccessCtrlMgr.getInstance().ensureReadCpRights(cp);
CpReportSettings cpSettings = daoFactory.getCpReportSettingsDao().getByCp(cp.getId());
if (cpSettings != null && !cpSettings.isEnabled()) {
return ResponseEvent.userError(CpErrorCode.RPT_DISABLED, cp.getShortTitle());
}
taskExecutor.execute(new CpReportTask(cp.getId()));
return ResponseEvent.response(true);
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<File> getReportFile(Long cpId, String fileId) {
try {
CollectionProtocol cp = getCollectionProtocol(cpId, null, null);
AccessCtrlMgr.getInstance().ensureReadCpRights(cp);
File file = new CpReportGenerator().getDataFile(cpId, fileId);
if (file == null) {
return ResponseEvent.userError(CpErrorCode.RPT_FILE_NOT_FOUND);
}
return ResponseEvent.response(file);
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<CpWorkflowCfgDetail> getWorkflows(RequestEvent<Long> req) {
Long cpId = req.getPayload();
CollectionProtocol cp = null;
CpWorkflowConfig cfg;
if (cpId == null || cpId == -1L) {
cfg = WorkflowUtil.getInstance().getSysWorkflows();
} else {
cp = daoFactory.getCollectionProtocolDao().getById(cpId);
if (cp == null) {
return ResponseEvent.userError(CpErrorCode.NOT_FOUND);
}
cfg = daoFactory.getCollectionProtocolDao().getCpWorkflows(cpId);
}
if (cfg == null) {
cfg = new CpWorkflowConfig();
cfg.setCp(cp);
}
return ResponseEvent.response(CpWorkflowCfgDetail.from(cfg));
}
@Override
@PlusTransactional
public ResponseEvent<CpWorkflowCfgDetail> saveWorkflows(RequestEvent<CpWorkflowCfgDetail> req) {
try {
CpWorkflowCfgDetail input = req.getPayload();
CollectionProtocol cp = daoFactory.getCollectionProtocolDao().getById(input.getCpId());
if (cp == null) {
return ResponseEvent.userError(CpErrorCode.NOT_FOUND);
}
AccessCtrlMgr.getInstance().ensureUpdateCpRights(cp);
CpWorkflowConfig cfg = saveWorkflows(cp, input);
return ResponseEvent.response(CpWorkflowCfgDetail.from(cfg));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<CollectionProtocolSummary>> getRegisterEnabledCps(
List<String> siteNames, String searchTitle, int maxResults) {
try {
Set<Long> cpIds = AccessCtrlMgr.getInstance().getRegisterEnabledCpIds(siteNames);
CpListCriteria crit = new CpListCriteria().title(searchTitle).maxResults(maxResults);
if (cpIds != null && cpIds.isEmpty()) {
return ResponseEvent.response(Collections.<CollectionProtocolSummary>emptyList());
} else if (cpIds != null) {
crit.ids(new ArrayList<>(cpIds));
}
return ResponseEvent.response(daoFactory.getCollectionProtocolDao().getCollectionProtocols(crit));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<ListConfig> getCpListCfg(RequestEvent<Map<String, Object>> req) {
return listSvc.getListCfg(req);
}
@Override
@PlusTransactional
public ResponseEvent<ListDetail> getList(RequestEvent<Map<String, Object>> req) {
return listSvc.getList(req);
}
@Override
@PlusTransactional
public ResponseEvent<Integer> getListSize(RequestEvent<Map<String, Object>> req) {
return listSvc.getListSize(req);
}
@Override
@PlusTransactional
public ResponseEvent<Collection<Object>> getListExprValues(RequestEvent<Map<String, Object>> req) {
return listSvc.getListExprValues(req);
}
@Override
@PlusTransactional
public boolean toggleStarredCp(Long cpId, boolean starred) {
try {
CollectionProtocol cp = daoFactory.getCollectionProtocolDao().getById(cpId);
if (cp == null) {
throw OpenSpecimenException.userError(CpErrorCode.NOT_FOUND, cpId);
}
AccessCtrlMgr.getInstance().ensureReadCpRights(cp);
if (starred) {
starredItemSvc.save(getObjectName(), cp.getId());
} else {
starredItemSvc.delete(getObjectName(), cp.getId());
}
return true;
} catch (Exception e) {
if (e instanceof OpenSpecimenException) {
throw e;
}
throw OpenSpecimenException.serverError(e);
}
}
@Override
public String getObjectName() {
return CollectionProtocol.getEntityName();
}
@Override
@PlusTransactional
public Map<String, Object> resolveUrl(String key, Object value) {
if (key.equals("id")) {
value = Long.valueOf(value.toString());
}
return daoFactory.getCollectionProtocolDao().getCpIds(key, value);
}
@Override
public String getAuditTable() {
return "CAT_COLLECTION_PROTOCOL_AUD";
}
@Override
public void ensureReadAllowed(Long id) {
CollectionProtocol cp = getCollectionProtocol(id, null, null);
AccessCtrlMgr.getInstance().ensureReadCpRights(cp);
}
@Override
public void afterPropertiesSet() throws Exception {
listSvc.registerListConfigurator("cp-list-view", this::getCpListConfig);
listSvc.registerListConfigurator("participant-list-view", this::getParticipantsListConfig);
listSvc.registerListConfigurator("specimen-list-view", this::getSpecimenListConfig);
}
@Override
public CpWorkflowConfig saveWorkflows(CollectionProtocol cp, CpWorkflowCfgDetail input) {
CpWorkflowConfig cfg = daoFactory.getCollectionProtocolDao().getCpWorkflows(cp.getId());
if (cfg == null) {
cfg = new CpWorkflowConfig();
cfg.setCp(cp);
}
if (!input.isPatch()) {
cfg.getWorkflows().clear();
}
if (input.getWorkflows() != null) {
for (WorkflowDetail detail : input.getWorkflows().values()) {
Workflow wf = new Workflow();
BeanUtils.copyProperties(detail, wf);
cfg.getWorkflows().put(wf.getName(), wf);
}
}
daoFactory.getCollectionProtocolDao().saveCpWorkflows(cfg);
return cfg;
}
private CpListCriteria addCpListCriteria(CpListCriteria crit) {
Set<SiteCpPair> siteCps = AccessCtrlMgr.getInstance().getReadableSiteCps();
return siteCps != null && siteCps.isEmpty() ? null : crit.siteCps(siteCps);
}
private CprListCriteria addCprListCriteria(CprListCriteria listCrit) {
ParticipantReadAccess access = AccessCtrlMgr.getInstance().getParticipantReadAccess(listCrit.cpId());
if (!access.admin) {
if (access.noAccessibleSites() || (!access.phiAccess && listCrit.hasPhiFields())) {
return null;
}
}
return listCrit.includePhi(access.phiAccess)
.phiSiteCps(access.phiSiteCps)
.siteCps(access.siteCps)
.useMrnSites(AccessCtrlMgr.getInstance().isAccessRestrictedBasedOnMrn());
}
private CollectionProtocol createCollectionProtocol(CollectionProtocolDetail detail, CollectionProtocol existing, boolean createCopy) {
CollectionProtocol cp = null;
if (!createCopy) {
cp = cpFactory.createCollectionProtocol(detail);
} else {
cp = cpFactory.createCpCopy(detail, existing);
}
AccessCtrlMgr.getInstance().ensureCreateCpRights(cp);
ensureUsersBelongtoCpSites(cp);
OpenSpecimenException ose = new OpenSpecimenException(ErrorType.USER_ERROR);
ensureUniqueTitle(null, cp, ose);
ensureUniqueShortTitle(null, cp, ose);
ensureUniqueCode(null, cp, ose);
ensureUniqueCpSiteCode(cp, ose);
ose.checkAndThrow();
daoFactory.getCollectionProtocolDao().saveOrUpdate(cp, true);
cp.addOrUpdateExtension();
//Assign default roles to PI and Coordinators
addOrRemovePiCoordinatorRoles(cp, "CREATE", null, cp.getPrincipalInvestigator(), cp.getCoordinators(), null);
fixSopDocumentName(cp);
copyWorkflows(existing, cp);
return cp;
}
private void ensureUsersBelongtoCpSites(CollectionProtocol cp) {
ensureCreatorBelongToCpSites(cp);
}
private void ensureCreatorBelongToCpSites(CollectionProtocol cp) {
User user = AuthUtil.getCurrentUser();
if (user.isAdmin()) {
return;
}
Set<Site> cpSites = cp.getRepositories();
if (cpSites.stream().anyMatch(cpSite -> !cpSite.getInstitute().equals(AuthUtil.getCurrentUserInstitute()))) {
throw OpenSpecimenException.userError(CpErrorCode.CREATOR_DOES_NOT_BELONG_CP_REPOS);
}
}
private void ensureUniqueTitle(CollectionProtocol existingCp, CollectionProtocol cp, OpenSpecimenException ose) {
String title = cp.getTitle();
if (existingCp != null && existingCp.getTitle().equals(title)) {
return;
}
CollectionProtocol dbCp = daoFactory.getCollectionProtocolDao().getCollectionProtocol(title);
if (dbCp != null) {
ose.addError(CpErrorCode.DUP_TITLE, title);
}
}
private void ensureUniqueShortTitle(CollectionProtocol existingCp, CollectionProtocol cp, OpenSpecimenException ose) {
String shortTitle = cp.getShortTitle();
if (existingCp != null && existingCp.getShortTitle().equals(shortTitle)) {
return;
}
CollectionProtocol dbCp = daoFactory.getCollectionProtocolDao().getCpByShortTitle(shortTitle);
if (dbCp != null) {
ose.addError(CpErrorCode.DUP_SHORT_TITLE, shortTitle);
}
}
private void ensureUniqueCode(CollectionProtocol existingCp, CollectionProtocol cp, OpenSpecimenException ose) {
String code = cp.getCode();
if (StringUtils.isBlank(code)) {
return;
}
if (existingCp != null && code.equals(existingCp.getCode())) {
return;
}
CollectionProtocol dbCp = daoFactory.getCollectionProtocolDao().getCpByCode(code);
if (dbCp != null) {
ose.addError(CpErrorCode.DUP_CODE, code);
}
}
private void ensureUniqueCpSiteCode(CollectionProtocol cp, OpenSpecimenException ose) {
List<String> codes = Utility.<List<String>>collect(cp.getSites(), "code");
codes.removeAll(Arrays.asList(new String[] {null, ""}));
Set<String> uniqueCodes = new HashSet<String>(codes);
if (codes.size() != uniqueCodes.size()) {
ose.addError(CpErrorCode.DUP_CP_SITE_CODES, codes);
}
}
private void ensureSitesAreNotInUse(CollectionProtocol cp, Collection<Site> sites) {
if (sites.isEmpty()) {
return;
}
List<Long> siteIds = sites.stream().map(Site::getId).collect(Collectors.toList());
Map<String, Integer> counts = daoFactory.getCprDao().getParticipantsBySite(cp.getId(), siteIds);
if (!counts.isEmpty()) {
String siteLabels = counts.keySet().stream().collect(Collectors.joining(", "));
throw OpenSpecimenException.userError(CpErrorCode.USED_SITES, siteLabels, counts.size());
}
}
private void fixSopDocumentName(CollectionProtocol cp) {
if (StringUtils.isBlank(cp.getSopDocumentName())) {
return;
}
String[] nameParts = cp.getSopDocumentName().split("_", 2);
if (nameParts[0].equals(cp.getId().toString())) {
return;
}
try {
UUID uuid = UUID.fromString(nameParts[0]);
} catch (Exception e) {
throw OpenSpecimenException.userError(CpErrorCode.INVALID_SOP_DOC, cp.getSopDocumentName());
}
if (StringUtils.isBlank(nameParts[1])) {
throw OpenSpecimenException.userError(CpErrorCode.INVALID_SOP_DOC, cp.getSopDocumentName());
}
File src = new File(getSopDocDir() + File.separator + cp.getSopDocumentName());
if (!src.exists()) {
throw OpenSpecimenException.userError(CpErrorCode.SOP_DOC_MOVED_OR_DELETED, cp.getSopDocumentName(), cp.getShortTitle());
}
cp.setSopDocumentName(cp.getId() + "_" + nameParts[1]);
File dest = new File(getSopDocDir() + File.separator + cp.getSopDocumentName());
src.renameTo(dest);
}
private void ensureConsentTierIsEmpty(CollectionProtocol existingCp, OpenSpecimenException ose) {
if (CollectionUtils.isNotEmpty(existingCp.getConsentTier())) {
ose.addError(CpErrorCode.CONSENT_TIER_FOUND, existingCp.getShortTitle());
}
}
private void importConsents(Long cpId, List<ConsentTierDetail> consents) {
if (CollectionUtils.isEmpty(consents)) {
return;
}
for (ConsentTierDetail consent : consents) {
ConsentTierOp addOp = new ConsentTierOp();
addOp.setConsentTier(consent);
addOp.setCpId(cpId);
addOp.setOp(OP.ADD);
ResponseEvent<ConsentTierDetail> resp = updateConsentTier(new RequestEvent<>(addOp));
resp.throwErrorIfUnsuccessful();
}
}
private void importEvents(String cpTitle, List<CollectionProtocolEventDetail> events) {
if (CollectionUtils.isEmpty(events)) {
return;
}
for (CollectionProtocolEventDetail event : events) {
if (Status.isClosedOrDisabledStatus(event.getActivityStatus())) {
continue;
}
event.setCollectionProtocol(cpTitle);
ResponseEvent<CollectionProtocolEventDetail> resp = addEvent(new RequestEvent<>(event));
resp.throwErrorIfUnsuccessful();
Long eventId = resp.getPayload().getId();
importSpecimenReqs(eventId, null, event.getSpecimenRequirements());
}
}
private void importSpecimenReqs(Long eventId, Long parentSrId, List<SpecimenRequirementDetail> srs) {
if (CollectionUtils.isEmpty(srs)) {
return;
}
for (SpecimenRequirementDetail sr : srs) {
if (Status.isClosedOrDisabledStatus(sr.getActivityStatus())) {
continue;
}
sr.setEventId(eventId);
if (sr.getLineage().equals(Specimen.NEW)) {
ResponseEvent<SpecimenRequirementDetail> resp = addSpecimenRequirement(new RequestEvent<>(sr));
resp.throwErrorIfUnsuccessful();
importSpecimenReqs(eventId, resp.getPayload().getId(), sr.getChildren());
} else if (parentSrId != null && sr.getLineage().equals(Specimen.ALIQUOT)) {
AliquotSpecimensRequirement aliquotReq = sr.toAliquotRequirement(parentSrId, 1);
List<SpecimenRequirement> aliquots = createAliquots(aliquotReq);
if (StringUtils.isNotBlank(sr.getCode())) {
aliquots.get(0).setCode(sr.getCode());
}
importSpecimenReqs(eventId, aliquots.get(0).getId(), sr.getChildren());
} else if (parentSrId != null && sr.getLineage().equals(Specimen.DERIVED)) {
DerivedSpecimenRequirement derivedReq = sr.toDerivedRequirement(parentSrId);
ResponseEvent<SpecimenRequirementDetail> resp = createDerived(new RequestEvent<DerivedSpecimenRequirement>(derivedReq));
resp.throwErrorIfUnsuccessful();
importSpecimenReqs(eventId, resp.getPayload().getId(), sr.getChildren());
}
}
}
private void ensureSrIsNotClosed(SpecimenRequirement sr) {
if (!sr.isClosed()) {
return;
}
String key = sr.getCode();
if (StringUtils.isBlank(key)) {
key = sr.getName();
}
if (StringUtils.isBlank(key)) {
key = sr.getId().toString();
}
throw OpenSpecimenException.userError(SrErrorCode.CLOSED, key);
}
private List<SpecimenRequirement> createAliquots(AliquotSpecimensRequirement requirement) {
List<SpecimenRequirement> aliquots = srFactory.createAliquots(requirement);
SpecimenRequirement aliquot = aliquots.iterator().next();
AccessCtrlMgr.getInstance().ensureUpdateCpRights(aliquot.getCollectionProtocol());
SpecimenRequirement parent = aliquot.getParentSpecimenRequirement();
if (StringUtils.isNotBlank(requirement.getCode())) {
setAliquotCode(parent, aliquots, requirement.getCode());
}
parent.addChildRequirements(aliquots);
daoFactory.getSpecimenRequirementDao().saveOrUpdate(parent, true);
return aliquots;
}
private void importWorkflows(Long cpId, Map<String, WorkflowDetail> workflows) {
CpWorkflowCfgDetail input = new CpWorkflowCfgDetail();
input.setCpId(cpId);
input.setWorkflows(workflows);
ResponseEvent<CpWorkflowCfgDetail> resp = saveWorkflows(new RequestEvent<>(input));
resp.throwErrorIfUnsuccessful();
}
private void copyWorkflows(CollectionProtocol srcCp, CollectionProtocol dstCp) {
if (srcCp == null) {
return;
}
CpWorkflowConfig srcWfCfg = daoFactory.getCollectionProtocolDao().getCpWorkflows(srcCp.getId());
if (srcWfCfg != null) {
CpWorkflowConfig newConfig = new CpWorkflowConfig();
newConfig.setCp(dstCp);
newConfig.setWorkflows(srcWfCfg.getWorkflows());
daoFactory.getCollectionProtocolDao().saveCpWorkflows(newConfig);
}
}
private void addOrRemovePiCoordinatorRoles(CollectionProtocol cp, String cpOp, User oldPi, User newPi, Collection<User> newCoord, Collection<User> removedCoord) {
List<User> notifUsers = null;
if (!Objects.equals(oldPi, newPi)) {
notifUsers = AccessCtrlMgr.getInstance().getSiteAdmins(null, cp);
if (newPi != null) {
addDefaultPiRoles(cp, notifUsers, newPi, cpOp);
}
if (oldPi != null) {
removeDefaultPiRoles(cp, notifUsers, oldPi, cpOp);
}
}
if (CollectionUtils.isNotEmpty(newCoord)) {
if (notifUsers == null) {
notifUsers = AccessCtrlMgr.getInstance().getSiteAdmins(null, cp);
}
addDefaultCoordinatorRoles(cp, notifUsers, newCoord, cpOp);
}
if (CollectionUtils.isNotEmpty(removedCoord)) {
if (notifUsers == null) {
notifUsers = AccessCtrlMgr.getInstance().getSiteAdmins(null, cp);
}
removeDefaultCoordinatorRoles(cp, notifUsers, removedCoord, cpOp);
}
}
private void addDefaultPiRoles(CollectionProtocol cp, List<User> notifUsers, User user, String cpOp) {
try {
if (user.isContact()) {
return;
}
for (String role : getDefaultPiRoles()) {
addRole(cp, notifUsers, user, role, cpOp);
}
} catch (OpenSpecimenException ose) {
ose.rethrow(RbacErrorCode.ACCESS_DENIED, CpErrorCode.USER_UPDATE_RIGHTS_REQUIRED);
throw ose;
}
}
private void removeDefaultPiRoles(CollectionProtocol cp, List<User> notifUsers, User user, String cpOp) {
try {
for (String role : getDefaultPiRoles()) {
removeRole(cp, notifUsers, user, role, cpOp);
}
} catch (OpenSpecimenException ose) {
ose.rethrow(RbacErrorCode.ACCESS_DENIED, CpErrorCode.USER_UPDATE_RIGHTS_REQUIRED);
}
}
private void addDefaultCoordinatorRoles(CollectionProtocol cp, List<User> notifUsers, Collection<User> coordinators, String cpOp) {
try {
for (User user : coordinators) {
if (user.isContact()) {
continue;
}
for (String role : getDefaultCoordinatorRoles()) {
addRole(cp, notifUsers, user, role, cpOp);
}
}
} catch (OpenSpecimenException ose) {
ose.rethrow(RbacErrorCode.ACCESS_DENIED, CpErrorCode.USER_UPDATE_RIGHTS_REQUIRED);
}
}
private void removeDefaultCoordinatorRoles(CollectionProtocol cp, List<User> notifUsers, Collection<User> coordinators, String cpOp) {
try {
for (User user : coordinators) {
for (String role : getDefaultCoordinatorRoles()) {
removeRole(cp, notifUsers, user, role, cpOp);
}
}
} catch (OpenSpecimenException ose) {
ose.rethrow(RbacErrorCode.ACCESS_DENIED, CpErrorCode.USER_UPDATE_RIGHTS_REQUIRED);
}
}
private void addRole(CollectionProtocol cp, List<User> admins, User user, String role, String cpOp) {
SubjectRoleOpNotif notifReq = getNotifReq(cp, role, admins, user, cpOp, "ADD");
rbacSvc.addSubjectRole(null, cp, user, new String[] { role }, notifReq);
}
private void removeRole(CollectionProtocol cp, List<User> admins, User user, String role, String cpOp) {
SubjectRoleOpNotif notifReq = getNotifReq(cp, role, admins, user, cpOp, "REMOVE");
rbacSvc.removeSubjectRole(null, cp, user, new String[] { role }, notifReq);
}
private String[] getDefaultPiRoles() {
return new String[] {"Principal Investigator"};
}
private String[] getDefaultCoordinatorRoles() {
return new String[] {"Coordinator"};
}
private CpConsentTier getConsentTier(ConsentTierDetail consentTierDetail) {
CollectionProtocolDao cpDao = daoFactory.getCollectionProtocolDao();
CpConsentTier consentTier = null;
if (consentTierDetail.getId() != null) {
consentTier = cpDao.getConsentTier(consentTierDetail.getId());
} else if (StringUtils.isNotBlank(consentTierDetail.getStatement()) && consentTierDetail.getCpId() != null ) {
consentTier = cpDao.getConsentTierByStatement(consentTierDetail.getCpId(), consentTierDetail.getStatement());
}
if (consentTier == null) {
throw OpenSpecimenException.userError(CpErrorCode.CONSENT_TIER_NOT_FOUND);
}
return consentTier;
}
private void ensureUniqueConsentStatement(ConsentTierDetail consentTierDetail, CollectionProtocol cp) {
Predicate<CpConsentTier> findFn;
if (consentTierDetail.getStatementId() != null) {
findFn = (t) -> t.getStatement().getId().equals(consentTierDetail.getStatementId());
} else if (StringUtils.isNotBlank(consentTierDetail.getStatementCode())) {
findFn = (t) -> t.getStatement().getCode().equals(consentTierDetail.getStatementCode());
} else if (StringUtils.isNotBlank(consentTierDetail.getStatement())) {
findFn = (t) -> t.getStatement().getStatement().equals(consentTierDetail.getStatement());
} else {
throw OpenSpecimenException.userError(ConsentStatementErrorCode.CODE_REQUIRED);
}
CpConsentTier tier = cp.getConsentTier().stream().filter(findFn).findFirst().orElse(null);
if (tier != null && !tier.getId().equals(consentTierDetail.getId())) {
throw OpenSpecimenException.userError(CpErrorCode.DUP_CONSENT, tier.getStatement().getCode(), cp.getShortTitle());
}
}
private CpConsentTier getConsentTierObj(Long id, ConsentStatement stmt) {
CpConsentTier tier = new CpConsentTier();
tier.setId(id);
tier.setStatement(stmt);
return tier;
}
private void ensureSpecimensNotCollected(SpecimenRequirement sr) {
int count = daoFactory.getSpecimenRequirementDao().getSpecimensCount(sr.getId());
if (count > 0) {
throw OpenSpecimenException.userError(SrErrorCode.CANNOT_CHANGE_CLASS_OR_TYPE);
}
}
private boolean isSpecimenClassOrTypeChanged(SpecimenRequirement existingSr, SpecimenRequirement sr) {
return !existingSr.getSpecimenClass().equals(sr.getSpecimenClass()) ||
!existingSr.getSpecimenType().equals(sr.getSpecimenType());
}
private void setAliquotCode(SpecimenRequirement parent, List<SpecimenRequirement> aliquots, String code) {
Set<String> codes = new HashSet<String>();
CollectionProtocolEvent cpe = parent.getCollectionProtocolEvent();
for (SpecimenRequirement sr : cpe.getSpecimenRequirements()) {
if (StringUtils.isNotBlank(sr.getCode())) {
codes.add(sr.getCode());
}
}
int count = 1;
for (SpecimenRequirement sr : aliquots) {
while (!codes.add(code + count)) {
count++;
}
sr.setCode(code + count++);
}
}
private CollectionProtocol getCollectionProtocol(String shortTitle) {
return getCollectionProtocol(null, null, shortTitle);
}
private CollectionProtocol getCollectionProtocol(Long id, String title, String shortTitle) {
CollectionProtocol cp = null;
if (id != null) {
cp = daoFactory.getCollectionProtocolDao().getById(id);
} else if (StringUtils.isNotBlank(title)) {
cp = daoFactory.getCollectionProtocolDao().getCollectionProtocol(title);
} else if (StringUtils.isNoneBlank(shortTitle)) {
cp = daoFactory.getCollectionProtocolDao().getCpByShortTitle(shortTitle);
}
if (cp == null) {
throw OpenSpecimenException.userError(CpErrorCode.NOT_FOUND);
}
return cp;
}
private void mergeCprIntoCp(CollectionProtocolRegistration srcCpr, CollectionProtocol tgtCp) {
//
// Step 1: Get a matching CPR either by PPID or participant ID
//
CollectionProtocolRegistration tgtCpr = daoFactory.getCprDao().getCprByPpid(tgtCp.getId(), srcCpr.getPpid());
if (tgtCpr == null) {
tgtCpr = srcCpr.getParticipant().getCpr(tgtCp);
}
//
// Step 2: Map all visits of source CP registrations to first event of target CP
// Further mark all created specimens as unplanned
//
CollectionProtocolEvent firstCpe = tgtCp.firstEvent();
for (Visit visit : srcCpr.getVisits()) {
visit.setCpEvent(firstCpe);
visit.getSpecimens().forEach(s -> s.setSpecimenRequirement(null));
}
//
// Step 3: Attach registrations to target CP
//
if (tgtCpr == null) {
//
// case 1: No matching registration was found in target CP; therefore make source
// registration as part of target CP
//
srcCpr.setCollectionProtocol(tgtCp);
} else {
//
// case 2: Matching registration was found in target CP; therefore do following
// 2.1 Move all visits of source CP registration to target CP registration
// 2.2 Finally delete source CP registration
//
tgtCpr.addVisits(srcCpr.getVisits());
srcCpr.getVisits().clear();
srcCpr.delete();
}
}
private void ensureMergeableCps(CollectionProtocol srcCp, CollectionProtocol tgtCp) {
ArrayList<String> notSameLabels = new ArrayList<>();
ensureBlankOrSame(srcCp.getPpidFormat(), tgtCp.getPpidFormat(), PPID_MSG, notSameLabels);
ensureBlankOrSame(srcCp.getVisitNameFormat(), tgtCp.getVisitNameFormat(), VISIT_NAME_MSG, notSameLabels);
ensureBlankOrSame(srcCp.getSpecimenLabelFormat(), tgtCp.getSpecimenLabelFormat(), SPECIMEN_LABEL_MSG, notSameLabels);
ensureBlankOrSame(srcCp.getDerivativeLabelFormat(), tgtCp.getDerivativeLabelFormat(), DERIVATIVE_LABEL_MSG, notSameLabels);
ensureBlankOrSame(srcCp.getAliquotLabelFormat(), tgtCp.getAliquotLabelFormat(), ALIQUOT_LABEL_MSG, notSameLabels);
if (!notSameLabels.isEmpty()) {
throw OpenSpecimenException.userError(
CpErrorCode.CANNOT_MERGE_FMT_DIFFERS,
srcCp.getShortTitle(),
tgtCp.getShortTitle(),
notSameLabels);
}
}
private void ensureBlankOrSame(String srcLabelFmt, String tgtLabelFmt, String labelKey, List<String> notSameLabels) {
if (!StringUtils.isBlank(tgtLabelFmt) && !tgtLabelFmt.equals(srcLabelFmt)) {
notSameLabels.add(getMsg(labelKey));
}
}
private boolean forceDeleteCps(final List<CollectionProtocol> cps, final String reason)
throws Exception {
final Authentication auth = AuthUtil.getAuth();
Future<Boolean> result = taskExecutor.submit(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
SecurityContextHolder.getContext().setAuthentication(auth);
cps.forEach(cp -> forceDeleteCp(cp, reason));
return true;
}
});
boolean completed = false;
try {
completed = result.get(30, TimeUnit.SECONDS);
} catch (TimeoutException ex) {
completed = false;
}
return completed;
}
private void forceDeleteCp(CollectionProtocol cp, String reason) {
while (deleteRegistrations(cp));
deleteCp(cp, reason);
}
private boolean deleteCps(List<CollectionProtocol> cps, String reason) {
cps.forEach(cp -> deleteCp(cp, reason));
return true;
}
@PlusTransactional
private boolean deleteCp(CollectionProtocol cp, String reason) {
boolean success = false;
String stackTrace = null;
CollectionProtocol deletedCp = new CollectionProtocol();
try {
//
// refresh cp, as it could have been fetched in another transaction
// if in same transaction, then it will be obtained from session
//
cp = daoFactory.getCollectionProtocolDao().getById(cp.getId());
removeContainerRestrictions(cp);
addOrRemovePiCoordinatorRoles(cp, "DELETE", cp.getPrincipalInvestigator(), null, null, cp.getCoordinators());
removeCpRoles(cp);
BeanUtils.copyProperties(cp, deletedCp);
cp.setOpComments(reason);
cp.delete();
DeleteLogUtil.getInstance().log(cp);
success = true;
} catch (Exception ex) {
stackTrace = ExceptionUtils.getStackTrace(ex);
if (ex instanceof OpenSpecimenException) {
throw ex;
} else {
throw OpenSpecimenException.serverError(ex);
}
} finally {
notifyUsersOnCpDelete(deletedCp, success, stackTrace);
}
return true;
}
@PlusTransactional
private boolean deleteRegistrations(CollectionProtocol cp) {
List<CollectionProtocolRegistration> cprs = daoFactory.getCprDao().getCprsByCpId(cp.getId(), 0, 10);
cprs.forEach(cpr -> cpr.delete(false));
return cprs.size() == 10;
}
private void removeContainerRestrictions(CollectionProtocol cp) {
Set<StorageContainer> containers = cp.getStorageContainers();
for (StorageContainer container : containers) {
container.removeCpRestriction(cp);
}
cp.setStorageContainers(Collections.EMPTY_SET);
}
private void removeCpRoles(CollectionProtocol cp) {
rbacSvc.removeCpRoles(cp.getId());
}
private void notifyUsersOnCpCreate(CollectionProtocol cp) {
notifyUsersOnCpOp(cp, cp.getRepositories(), OP_CP_CREATED);
}
private void notifyUsersOnCpUpdate(CollectionProtocol cp, Collection<Site> addedSites, Collection<Site> removedSites) {
notifyUsersOnCpOp(cp, removedSites, OP_CP_SITE_REMOVED);
notifyUsersOnCpOp(cp, addedSites, OP_CP_SITE_ADDED);
}
private void notifyUsersOnCpDelete(CollectionProtocol cp, boolean success, String stackTrace) {
if (success) {
notifyUsersOnCpOp(cp, cp.getRepositories(), OP_CP_DELETED);
} else {
User currentUser = AuthUtil.getCurrentUser();
String[] rcpts = {currentUser.getEmailAddress(), cp.getPrincipalInvestigator().getEmailAddress()};
String[] subjParams = new String[] {cp.getShortTitle()};
Map<String, Object> props = new HashMap<>();
props.put("cp", cp);
props.put("$subject", subjParams);
props.put("user", currentUser);
props.put("error", stackTrace);
EmailUtil.getInstance().sendEmail(CP_DELETE_FAILED_EMAIL_TMPL, rcpts, null, props);
}
}
private void notifyUsersOnCpOp(CollectionProtocol cp, Collection<Site> sites, int op) {
Map<String, Object> emailProps = new HashMap<>();
emailProps.put("$subject", new Object[] {cp.getShortTitle(), op});
emailProps.put("cp", cp);
emailProps.put("op", op);
emailProps.put("currentUser", AuthUtil.getCurrentUser());
emailProps.put("ccAdmin", false);
if (op == OP_CP_CREATED || op == OP_CP_DELETED) {
List<User> superAdmins = AccessCtrlMgr.getInstance().getSuperAdmins();
notifyUsers(superAdmins, CP_OP_EMAIL_TMPL, emailProps, (op == OP_CP_CREATED) ? "CREATE" : "DELETE");
}
for (Site site : sites) {
String siteName = site.getName();
emailProps.put("siteName", siteName);
emailProps.put("$subject", new Object[] {siteName, op, cp.getShortTitle()});
notifyUsers(site.getCoordinators(), CP_SITE_UPDATED_EMAIL_TMPL, emailProps, "UPDATE");
}
}
private void notifyUsers(Collection<User> users, String template, Map<String, Object> emailProps, String notifOp) {
for (User rcpt : users) {
emailProps.put("rcpt", rcpt);
EmailUtil.getInstance().sendEmail(template, new String[] {rcpt.getEmailAddress()}, null, emailProps);
}
CollectionProtocol cp = (CollectionProtocol)emailProps.get("cp");
Object[] subjParams = (Object[])emailProps.get("$subject");
Notification notif = new Notification();
notif.setEntityType(CollectionProtocol.getEntityName());
notif.setEntityId(cp.getId());
notif.setOperation(notifOp);
notif.setCreatedBy(AuthUtil.getCurrentUser());
notif.setCreationTime(Calendar.getInstance().getTime());
notif.setMessage(MessageUtil.getInstance().getMessage(template + "_subj", subjParams));
NotifUtil.getInstance().notify(notif, Collections.singletonMap("cp-overview", users));
}
private SubjectRoleOpNotif getNotifReq(CollectionProtocol cp, String role, List<User> notifUsers, User user, String cpOp, String roleOp) {
SubjectRoleOpNotif notifReq = new SubjectRoleOpNotif();
notifReq.setAdmins(notifUsers);
notifReq.setAdminNotifMsg("cp_admin_notif_role_" + roleOp.toLowerCase());
notifReq.setAdminNotifParams(new Object[] { user.getFirstName(), user.getLastName(), role, cp.getShortTitle(), user.getInstitute().getName() });
notifReq.setUser(user);
if (cpOp.equals("DELETE")) {
notifReq.setSubjectNotifMsg("cp_delete_user_notif_role");
notifReq.setSubjectNotifParams(new Object[] { cp.getShortTitle(), role });
} else {
notifReq.setSubjectNotifMsg("cp_user_notif_role_" + roleOp.toLowerCase());
notifReq.setSubjectNotifParams(new Object[] { role, cp.getShortTitle(), user.getInstitute().getName() });
}
notifReq.setEndUserOp(cpOp);
return notifReq;
}
private String getMsg(String code) {
return MessageUtil.getInstance().getMessage(code);
}
private String getSopDocDir() {
String defDir = ConfigUtil.getInstance().getDataDir() + File.separator + "cp-sop-documents";
String dir = ConfigUtil.getInstance().getStrSetting(ConfigParams.MODULE, ConfigParams.CP_SOP_DOCS_DIR, defDir);
new File(dir).mkdirs();
return dir + File.separator;
}
private CpReportSettings getReportSetting(CpQueryCriteria crit) {
CpReportSettings settings = null;
if (crit.getId() != null) {
settings = daoFactory.getCpReportSettingsDao().getByCp(crit.getId());
} else if (StringUtils.isNotBlank(crit.getShortTitle())) {
settings = daoFactory.getCpReportSettingsDao().getByCp(crit.getShortTitle());
}
return settings;
}
private ListConfig getSpecimenListConfig(Map<String, Object> listReq) {
ListConfig cfg = getListConfig(listReq, "specimen-list-view", "Specimen");
if (cfg == null) {
return null;
}
Column id = new Column();
id.setExpr("Specimen.id");
id.setCaption("specimenId");
cfg.setPrimaryColumn(id);
Column type = new Column();
type.setExpr("Specimen.type");
type.setCaption("specimenType");
Column specimenClass = new Column();
specimenClass.setExpr("Specimen.class");
specimenClass.setCaption("specimenClass");
List<Column> hiddenColumns = new ArrayList<>();
hiddenColumns.add(id);
hiddenColumns.add(type);
hiddenColumns.add(specimenClass);
cfg.setHiddenColumns(hiddenColumns);
Long cpId = (Long)listReq.get("cpId");
List<SiteCpPair> siteCps = AccessCtrlMgr.getInstance().getReadAccessSpecimenSiteCps(cpId);
if (siteCps == null) {
//
// Admin; hence no additional restrictions
//
return cfg;
}
if (siteCps.isEmpty()) {
throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED);
}
boolean useMrnSites = AccessCtrlMgr.getInstance().isAccessRestrictedBasedOnMrn();
String restrictions = BiospecimenDaoHelper.getInstance().getSiteCpsCondAql(siteCps, useMrnSites);
cfg.setRestriction(restrictions);
cfg.setDistinct(true);
return cfg;
}
private ListConfig getCpListConfig(Map<String, Object> listReq) {
ListConfig cfg = getListConfig(listReq, "cp-list-view", "CollectionProtocol");
if (cfg == null) {
return null;
}
List<Column> hiddenColumns = new ArrayList<>();
Column id = new Column();
id.setExpr("CollectionProtocol.id");
id.setCaption("cpId");
cfg.setPrimaryColumn(id);
hiddenColumns.add(id);
Column catalogId = new Column();
catalogId.setExpr("CollectionProtocol.catalogId");
catalogId.setCaption("catalogId");
hiddenColumns.add(catalogId);
Column starred = new Column();
starred.setExpr("CollectionProtocol.__userLabels.userId");
starred.setCaption("starred");
starred.setDirection(isOracle() ? "asc" : "desc");
hiddenColumns.add(starred);
cfg.setHiddenColumns(hiddenColumns);
List<Column> fixedColumns = new ArrayList<>();
Column participantsCount = new Column();
participantsCount.setCaption("Participants");
participantsCount.setExpr("count(Participant.id)");
fixedColumns.add(participantsCount);
Column specimensCount = new Column();
specimensCount.setCaption("Specimens");
specimensCount.setExpr("count(Specimen.id)");
fixedColumns.add(specimensCount);
cfg.setFixedColumns(fixedColumns);
cfg.setFixedColumnsGenerator(
(rows) -> {
if (rows == null || rows.isEmpty()) {
return rows;
}
Map<Long, Row> cpRows = new HashMap<>();
for (Row row : rows) {
Long cpId = Long.parseLong((String) row.getHidden().get("cpId"));
cpRows.put(cpId, row);
}
List<Object[]> dbRows = sessionFactory.getCurrentSession()
.getNamedQuery(CollectionProtocol.class.getName() + ".getParticipantAndSpecimenCount")
.setParameterList("cpIds", cpRows.keySet())
.list();
for (Object[] dbRow : dbRows) {
int idx = -1;
Long cpId = ((Number) dbRow[++idx]).longValue();
cpRows.get(cpId).setFixedData(new Object[] {dbRow[++idx], dbRow[++idx]});
}
return rows;
}
);
List<Column> orderBy = cfg.getOrderBy();
if (orderBy == null) {
orderBy = new ArrayList<>();
cfg.setOrderBy(orderBy);
}
orderBy.add(0, starred);
cfg.setRestriction(String.format(USR_LABELS_RESTRICTION, AuthUtil.getCurrentUser().getId()));
Set<SiteCpPair> cpSites = AccessCtrlMgr.getInstance().getReadableSiteCps();
if (cpSites == null) {
return cfg;
}
if (cpSites.isEmpty()) {
throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED);
}
String cpSitesRestriction = BiospecimenDaoHelper.getInstance().getSiteCpsCondAqlForCps(cpSites);
if (StringUtils.isNotBlank(cpSitesRestriction)) {
cfg.setRestriction(String.format(AND_COND, cfg.getRestriction(), cpSitesRestriction));
cfg.setDistinct(true);
}
return cfg;
}
private ListConfig getParticipantsListConfig(Map<String, Object> listReq) {
ListConfig cfg = getListConfig(listReq, "participant-list-view", "Participant");
if (cfg == null) {
return null;
}
Column id = new Column();
id.setExpr("Participant.id");
id.setCaption("cprId");
cfg.setPrimaryColumn(id);
cfg.setHiddenColumns(Collections.singletonList(id));
Long cpId = (Long)listReq.get("cpId");
ParticipantReadAccess access = AccessCtrlMgr.getInstance().getParticipantReadAccess(cpId);
if (access.admin) {
return cfg;
}
if (access.siteCps == null || access.siteCps.isEmpty()) {
throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED);
}
boolean useMrnSites = AccessCtrlMgr.getInstance().isAccessRestrictedBasedOnMrn();
cfg.setRestriction(BiospecimenDaoHelper.getInstance().getSiteCpsCondAql(access.siteCps, useMrnSites));
cfg.setDistinct(true);
return cfg;
}
private ListConfig getListConfig(Map<String, Object> listReq, String listName, String drivingForm) {
Long cpId = (Long) listReq.get("cpId");
if (cpId == null) {
cpId = (Long) listReq.get("objectId");
}
Workflow workflow = getWorkFlow(cpId, listName);
if (workflow == null) {
return null;
}
ListConfig listCfg = new ObjectMapper().convertValue(workflow.getData(), ListConfig.class);
listCfg.setCpId(cpId);
listCfg.setDrivingForm(drivingForm);
setListLimit(listReq, listCfg);
Boolean includeCount = (Boolean)listReq.get("includeCount");
listCfg.setIncludeCount(includeCount == null ? false : includeCount);
return listCfg;
}
private Workflow getWorkFlow(Long cpId, String name) {
Workflow workflow = null;
CpWorkflowConfig cfg = null;
if (cpId != null) {
cfg = daoFactory.getCollectionProtocolDao().getCpWorkflows(cpId);
}
if (cfg != null) {
workflow = cfg.getWorkflows().get(name);
}
if (workflow == null) {
workflow = getSysWorkflow(name);
}
return workflow;
}
private Workflow getSysWorkflow(String name) {
return WorkflowUtil.getInstance().getSysWorkflow(name);
}
private void setListLimit(Map<String, Object> listReq, ListConfig cfg) {
Integer startAt = (Integer)listReq.get("startAt");
if (startAt == null) {
startAt = 0;
}
Integer maxResults = (Integer)listReq.get("maxResults");
if (maxResults == null) {
maxResults = 100;
}
cfg.setStartAt(startAt);
cfg.setMaxResults(maxResults);
}
private ConsentStatement getStatement(Long id, String code, String statement) {
ConsentStatement stmt = null;
Object key = null;
if (id != null) {
key = id;
stmt = daoFactory.getConsentStatementDao().getById(id);
} else if (StringUtils.isNotBlank(code)) {
key = code;
stmt = daoFactory.getConsentStatementDao().getByCode(code);
} else if (StringUtils.isNotBlank(statement)) {
key = statement;
stmt = daoFactory.getConsentStatementDao().getByStatement(statement);
}
if (key == null) {
throw OpenSpecimenException.userError(ConsentStatementErrorCode.CODE_REQUIRED);
} else if (stmt == null) {
throw OpenSpecimenException.userError(ConsentStatementErrorCode.NOT_FOUND, key);
}
return stmt;
}
private boolean isOracle() {
String dbType = AppProperties.getInstance().getProperties()
.getProperty("database.type", "mysql")
.toLowerCase();
return dbType.equalsIgnoreCase("oracle");
}
private static final String PPID_MSG = "cp_ppid";
private static final String VISIT_NAME_MSG = "cp_visit_name";
private static final String SPECIMEN_LABEL_MSG = "cp_specimen_label";
private static final String DERIVATIVE_LABEL_MSG = "cp_derivative_label";
private static final String ALIQUOT_LABEL_MSG = "cp_aliquot_label";
private static final String CP_OP_EMAIL_TMPL = "cp_op";
private static final String CP_DELETE_FAILED_EMAIL_TMPL = "cp_delete_failed";
private static final String CP_SITE_UPDATED_EMAIL_TMPL = "cp_site_updated";
private static final int OP_CP_SITE_ADDED = -1;
private static final int OP_CP_SITE_REMOVED = 1;
private static final int OP_CP_CREATED = 0;
private static final int OP_CP_DELETED = 2;
private static final String USR_LABELS_RESTRICTION =
"(CollectionProtocol.__userLabels.userId not exists or CollectionProtocol.__userLabels.userId = %d)";
private static final String AND_COND = "(%s) and (%s)";
}
| WEB-INF/src/com/krishagni/catissueplus/core/biospecimen/services/impl/CollectionProtocolServiceImpl.java |
package com.krishagni.catissueplus.core.biospecimen.services.impl;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.hibernate.SessionFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.krishagni.catissueplus.core.administrative.domain.Site;
import com.krishagni.catissueplus.core.administrative.domain.StorageContainer;
import com.krishagni.catissueplus.core.administrative.domain.User;
import com.krishagni.catissueplus.core.administrative.events.SiteSummary;
import com.krishagni.catissueplus.core.audit.services.impl.DeleteLogUtil;
import com.krishagni.catissueplus.core.biospecimen.ConfigParams;
import com.krishagni.catissueplus.core.biospecimen.WorkflowUtil;
import com.krishagni.catissueplus.core.biospecimen.domain.AliquotSpecimensRequirement;
import com.krishagni.catissueplus.core.biospecimen.domain.CollectionProtocol;
import com.krishagni.catissueplus.core.biospecimen.domain.CollectionProtocolEvent;
import com.krishagni.catissueplus.core.biospecimen.domain.CollectionProtocolRegistration;
import com.krishagni.catissueplus.core.biospecimen.domain.CollectionProtocolSite;
import com.krishagni.catissueplus.core.biospecimen.domain.ConsentStatement;
import com.krishagni.catissueplus.core.biospecimen.domain.CpConsentTier;
import com.krishagni.catissueplus.core.biospecimen.domain.CpReportSettings;
import com.krishagni.catissueplus.core.biospecimen.domain.CpWorkflowConfig;
import com.krishagni.catissueplus.core.biospecimen.domain.CpWorkflowConfig.Workflow;
import com.krishagni.catissueplus.core.biospecimen.domain.DerivedSpecimenRequirement;
import com.krishagni.catissueplus.core.biospecimen.domain.PdeNotif;
import com.krishagni.catissueplus.core.biospecimen.domain.PdeNotifLink;
import com.krishagni.catissueplus.core.biospecimen.domain.Specimen;
import com.krishagni.catissueplus.core.biospecimen.domain.SpecimenRequirement;
import com.krishagni.catissueplus.core.biospecimen.domain.Visit;
import com.krishagni.catissueplus.core.biospecimen.domain.factory.CollectionProtocolFactory;
import com.krishagni.catissueplus.core.biospecimen.domain.factory.ConsentStatementErrorCode;
import com.krishagni.catissueplus.core.biospecimen.domain.factory.CpErrorCode;
import com.krishagni.catissueplus.core.biospecimen.domain.factory.CpReportSettingsFactory;
import com.krishagni.catissueplus.core.biospecimen.domain.factory.CpeErrorCode;
import com.krishagni.catissueplus.core.biospecimen.domain.factory.CpeFactory;
import com.krishagni.catissueplus.core.biospecimen.domain.factory.CprErrorCode;
import com.krishagni.catissueplus.core.biospecimen.domain.factory.SpecimenRequirementFactory;
import com.krishagni.catissueplus.core.biospecimen.domain.factory.SrErrorCode;
import com.krishagni.catissueplus.core.biospecimen.events.CollectionProtocolDetail;
import com.krishagni.catissueplus.core.biospecimen.events.CollectionProtocolEventDetail;
import com.krishagni.catissueplus.core.biospecimen.events.CollectionProtocolSummary;
import com.krishagni.catissueplus.core.biospecimen.events.ConsentTierDetail;
import com.krishagni.catissueplus.core.biospecimen.events.ConsentTierOp;
import com.krishagni.catissueplus.core.biospecimen.events.ConsentTierOp.OP;
import com.krishagni.catissueplus.core.biospecimen.events.CopyCpOpDetail;
import com.krishagni.catissueplus.core.biospecimen.events.CopyCpeOpDetail;
import com.krishagni.catissueplus.core.biospecimen.events.CpQueryCriteria;
import com.krishagni.catissueplus.core.biospecimen.events.CpReportSettingsDetail;
import com.krishagni.catissueplus.core.biospecimen.events.CpWorkflowCfgDetail;
import com.krishagni.catissueplus.core.biospecimen.events.CprSummary;
import com.krishagni.catissueplus.core.biospecimen.events.FileDetail;
import com.krishagni.catissueplus.core.biospecimen.events.MergeCpDetail;
import com.krishagni.catissueplus.core.biospecimen.events.PdeTokenDetail;
import com.krishagni.catissueplus.core.biospecimen.events.SpecimenPoolRequirements;
import com.krishagni.catissueplus.core.biospecimen.events.SpecimenRequirementDetail;
import com.krishagni.catissueplus.core.biospecimen.events.WorkflowDetail;
import com.krishagni.catissueplus.core.biospecimen.repository.CollectionProtocolDao;
import com.krishagni.catissueplus.core.biospecimen.repository.CpListCriteria;
import com.krishagni.catissueplus.core.biospecimen.repository.CprListCriteria;
import com.krishagni.catissueplus.core.biospecimen.repository.DaoFactory;
import com.krishagni.catissueplus.core.biospecimen.repository.PdeNotifListCriteria;
import com.krishagni.catissueplus.core.biospecimen.repository.impl.BiospecimenDaoHelper;
import com.krishagni.catissueplus.core.biospecimen.services.CollectionProtocolService;
import com.krishagni.catissueplus.core.biospecimen.services.PdeTokenGenerator;
import com.krishagni.catissueplus.core.biospecimen.services.PdeTokenGeneratorRegistry;
import com.krishagni.catissueplus.core.common.PlusTransactional;
import com.krishagni.catissueplus.core.common.Tuple;
import com.krishagni.catissueplus.core.common.access.AccessCtrlMgr;
import com.krishagni.catissueplus.core.common.access.AccessCtrlMgr.ParticipantReadAccess;
import com.krishagni.catissueplus.core.common.access.SiteCpPair;
import com.krishagni.catissueplus.core.common.domain.Notification;
import com.krishagni.catissueplus.core.common.errors.ErrorType;
import com.krishagni.catissueplus.core.common.errors.OpenSpecimenException;
import com.krishagni.catissueplus.core.common.events.BulkDeleteEntityOp;
import com.krishagni.catissueplus.core.common.events.BulkDeleteEntityResp;
import com.krishagni.catissueplus.core.common.events.DependentEntityDetail;
import com.krishagni.catissueplus.core.common.events.RequestEvent;
import com.krishagni.catissueplus.core.common.events.ResponseEvent;
import com.krishagni.catissueplus.core.common.service.ObjectAccessor;
import com.krishagni.catissueplus.core.common.service.StarredItemService;
import com.krishagni.catissueplus.core.common.util.AuthUtil;
import com.krishagni.catissueplus.core.common.util.ConfigUtil;
import com.krishagni.catissueplus.core.common.util.EmailUtil;
import com.krishagni.catissueplus.core.common.util.MessageUtil;
import com.krishagni.catissueplus.core.common.util.NotifUtil;
import com.krishagni.catissueplus.core.common.util.Status;
import com.krishagni.catissueplus.core.common.util.Utility;
import com.krishagni.catissueplus.core.init.AppProperties;
import com.krishagni.catissueplus.core.query.Column;
import com.krishagni.catissueplus.core.query.ListConfig;
import com.krishagni.catissueplus.core.query.ListDetail;
import com.krishagni.catissueplus.core.query.ListService;
import com.krishagni.catissueplus.core.query.Row;
import com.krishagni.rbac.common.errors.RbacErrorCode;
import com.krishagni.rbac.events.SubjectRoleOpNotif;
import com.krishagni.rbac.service.RbacService;
public class CollectionProtocolServiceImpl implements CollectionProtocolService, ObjectAccessor, InitializingBean {
private ThreadPoolTaskExecutor taskExecutor;
private CollectionProtocolFactory cpFactory;
private CpeFactory cpeFactory;
private SpecimenRequirementFactory srFactory;
private DaoFactory daoFactory;
private RbacService rbacSvc;
private ListService listSvc;
private CpReportSettingsFactory rptSettingsFactory;
private SessionFactory sessionFactory;
private StarredItemService starredItemSvc;
private PdeTokenGeneratorRegistry pdeTokenGeneratorRegistry;
public void setTaskExecutor(ThreadPoolTaskExecutor taskExecutor) {
this.taskExecutor = taskExecutor;
}
public void setCpFactory(CollectionProtocolFactory cpFactory) {
this.cpFactory = cpFactory;
}
public void setCpeFactory(CpeFactory cpeFactory) {
this.cpeFactory = cpeFactory;
}
public void setSrFactory(SpecimenRequirementFactory srFactory) {
this.srFactory = srFactory;
}
public void setDaoFactory(DaoFactory daoFactory) {
this.daoFactory = daoFactory;
}
public void setRbacSvc(RbacService rbacSvc) {
this.rbacSvc = rbacSvc;
}
public void setListSvc(ListService listSvc) {
this.listSvc = listSvc;
}
public void setRptSettingsFactory(CpReportSettingsFactory rptSettingsFactory) {
this.rptSettingsFactory = rptSettingsFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public void setStarredItemSvc(StarredItemService starredItemSvc) {
this.starredItemSvc = starredItemSvc;
}
public void setPdeTokenGeneratorRegistry(PdeTokenGeneratorRegistry pdeTokenGeneratorRegistry) {
this.pdeTokenGeneratorRegistry = pdeTokenGeneratorRegistry;
}
@Override
@PlusTransactional
public ResponseEvent<List<CollectionProtocolSummary>> getProtocols(RequestEvent<CpListCriteria> req) {
try {
CpListCriteria crit = addCpListCriteria(req.getPayload());
if (crit == null) {
return ResponseEvent.response(Collections.emptyList());
}
return ResponseEvent.response(daoFactory.getCollectionProtocolDao().getCollectionProtocols(crit));
} catch (OpenSpecimenException oce) {
return ResponseEvent.error(oce);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<Long> getProtocolsCount(RequestEvent<CpListCriteria> req) {
try {
CpListCriteria crit = addCpListCriteria(req.getPayload());
if (crit == null) {
return ResponseEvent.response(0L);
}
return ResponseEvent.response(daoFactory.getCollectionProtocolDao().getCpCount(crit));
} catch (OpenSpecimenException oce) {
return ResponseEvent.error(oce);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<CollectionProtocolDetail> getCollectionProtocol(RequestEvent<CpQueryCriteria> req) {
try {
CpQueryCriteria crit = req.getPayload();
CollectionProtocol cp = getCollectionProtocol(crit.getId(), crit.getTitle(), crit.getShortTitle());
AccessCtrlMgr.getInstance().ensureReadCpRights(cp);
return ResponseEvent.response(CollectionProtocolDetail.from(cp, crit.isFullObject()));
} catch (OpenSpecimenException oce) {
return ResponseEvent.error(oce);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<SiteSummary>> getSites(RequestEvent<CpQueryCriteria> req) {
try {
CpQueryCriteria crit = req.getPayload();
CollectionProtocol cp = getCollectionProtocol(crit.getId(), crit.getTitle(), crit.getShortTitle());
AccessCtrlMgr.getInstance().ensureReadCpRights(cp);
List<Site> sites = cp.getSites().stream().map(CollectionProtocolSite::getSite).collect(Collectors.toList());
return ResponseEvent.response(SiteSummary.from(sites));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<CprSummary>> getRegisteredParticipants(RequestEvent<CprListCriteria> req) {
try {
CprListCriteria listCrit = addCprListCriteria(req.getPayload());
if (listCrit == null) {
return ResponseEvent.response(Collections.emptyList());
}
return ResponseEvent.response(daoFactory.getCprDao().getCprList(listCrit));
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<Long> getRegisteredParticipantsCount(RequestEvent<CprListCriteria> req) {
try {
CprListCriteria listCrit = addCprListCriteria(req.getPayload());
if (listCrit == null) {
return ResponseEvent.response(0L);
}
return ResponseEvent.response(daoFactory.getCprDao().getCprCount(listCrit));
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<CollectionProtocolDetail> createCollectionProtocol(RequestEvent<CollectionProtocolDetail> req) {
try {
CollectionProtocol cp = createCollectionProtocol(req.getPayload(), null, false);
notifyUsersOnCpCreate(cp);
return ResponseEvent.response(CollectionProtocolDetail.from(cp));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<CollectionProtocolDetail> updateCollectionProtocol(RequestEvent<CollectionProtocolDetail> req) {
try {
CollectionProtocolDetail detail = req.getPayload();
CollectionProtocol existingCp = daoFactory.getCollectionProtocolDao().getById(detail.getId());
if (existingCp == null) {
return ResponseEvent.userError(CpErrorCode.NOT_FOUND);
}
AccessCtrlMgr.getInstance().ensureUpdateCpRights(existingCp);
CollectionProtocol cp = cpFactory.createCollectionProtocol(detail);
AccessCtrlMgr.getInstance().ensureUpdateCpRights(cp);
ensureUsersBelongtoCpSites(cp);
OpenSpecimenException ose = new OpenSpecimenException(ErrorType.USER_ERROR);
ensureUniqueTitle(existingCp, cp, ose);
ensureUniqueShortTitle(existingCp, cp, ose);
ensureUniqueCode(existingCp, cp, ose);
ensureUniqueCpSiteCode(cp, ose);
if (existingCp.isConsentsWaived() != cp.isConsentsWaived()) {
ensureConsentTierIsEmpty(existingCp, ose);
}
ose.checkAndThrow();
User oldPi = existingCp.getPrincipalInvestigator();
Collection<User> addedCoord = Utility.subtract(cp.getCoordinators(), existingCp.getCoordinators());
Collection<User> removedCoord = Utility.subtract(existingCp.getCoordinators(), cp.getCoordinators());
Set<Site> addedSites = Utility.subtract(cp.getRepositories(), existingCp.getRepositories());
Set<Site> removedSites = Utility.subtract(existingCp.getRepositories(), cp.getRepositories());
ensureSitesAreNotInUse(existingCp, removedSites);
existingCp.update(cp);
existingCp.addOrUpdateExtension();
fixSopDocumentName(existingCp);
// PI and coordinators role handling
addOrRemovePiCoordinatorRoles(cp, "UPDATE", oldPi, cp.getPrincipalInvestigator(), addedCoord, removedCoord);
notifyUsersOnCpUpdate(existingCp, addedSites, removedSites);
return ResponseEvent.response(CollectionProtocolDetail.from(existingCp));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<CollectionProtocolDetail> copyCollectionProtocol(RequestEvent<CopyCpOpDetail> req) {
try {
CopyCpOpDetail opDetail = req.getPayload();
Long cpId = opDetail.getCpId();
CollectionProtocol existing = daoFactory.getCollectionProtocolDao().getById(cpId);
if (existing == null) {
throw OpenSpecimenException.userError(CpErrorCode.NOT_FOUND);
}
AccessCtrlMgr.getInstance().ensureReadCpRights(existing);
CollectionProtocol cp = createCollectionProtocol(opDetail.getCp(), existing, true);
notifyUsersOnCpCreate(cp);
return ResponseEvent.response(CollectionProtocolDetail.from(cp));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<MergeCpDetail> mergeCollectionProtocols(RequestEvent<MergeCpDetail> req) {
AccessCtrlMgr.getInstance().ensureUserIsAdmin();
CollectionProtocol srcCp = getCollectionProtocol(req.getPayload().getSrcCpShortTitle());
CollectionProtocol tgtCp = getCollectionProtocol(req.getPayload().getTgtCpShortTitle());
ensureMergeableCps(srcCp, tgtCp);
int maxRecords = 30;
boolean moreRecords = true;
while (moreRecords) {
List<CollectionProtocolRegistration> cprs = daoFactory.getCprDao().getCprsByCpId(srcCp.getId(), 0, maxRecords);
for (CollectionProtocolRegistration srcCpr: cprs) {
mergeCprIntoCp(srcCpr, tgtCp);
}
if (cprs.size() < maxRecords) {
moreRecords = false;
}
}
return ResponseEvent.response(req.getPayload());
}
@PlusTransactional
public ResponseEvent<CollectionProtocolDetail> updateConsentsWaived(RequestEvent<CollectionProtocolDetail> req) {
try {
CollectionProtocolDetail detail = req.getPayload();
CollectionProtocol existingCp = daoFactory.getCollectionProtocolDao().getById(detail.getId());
if (existingCp == null) {
return ResponseEvent.userError(CpErrorCode.NOT_FOUND);
}
AccessCtrlMgr.getInstance().ensureUpdateCpRights(existingCp);
if (CollectionUtils.isNotEmpty(existingCp.getConsentTier())) {
return ResponseEvent.userError(CpErrorCode.CONSENT_TIER_FOUND, existingCp.getShortTitle());
}
existingCp.setConsentsWaived(detail.getConsentsWaived());
return ResponseEvent.response(CollectionProtocolDetail.from(existingCp));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@PlusTransactional
public ResponseEvent<List<DependentEntityDetail>> getCpDependentEntities(RequestEvent<Long> req) {
try {
CollectionProtocol existingCp = daoFactory.getCollectionProtocolDao().getById(req.getPayload());
if (existingCp == null) {
return ResponseEvent.userError(CpErrorCode.NOT_FOUND);
}
return ResponseEvent.response(existingCp.getDependentEntities());
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<BulkDeleteEntityResp<CollectionProtocolDetail>> deleteCollectionProtocols(RequestEvent<BulkDeleteEntityOp> req) {
try {
BulkDeleteEntityOp crit = req.getPayload();
Set<Long> cpIds = crit.getIds();
List<CollectionProtocol> cps = daoFactory.getCollectionProtocolDao().getByIds(cpIds);
if (crit.getIds().size() != cps.size()) {
cps.forEach(cp -> cpIds.remove(cp.getId()));
throw OpenSpecimenException.userError(CpErrorCode.DOES_NOT_EXIST, cpIds);
}
for (CollectionProtocol cp : cps) {
AccessCtrlMgr.getInstance().ensureDeleteCpRights(cp);
}
boolean completed = crit.isForceDelete() ? forceDeleteCps(cps, crit.getReason()) : deleteCps(cps, crit.getReason());
BulkDeleteEntityResp<CollectionProtocolDetail> resp = new BulkDeleteEntityResp<>();
resp.setCompleted(completed);
resp.setEntities(CollectionProtocolDetail.from(cps));
return ResponseEvent.response(resp);
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<File> getSopDocument(RequestEvent<Long> req) {
try {
Long cpId = req.getPayload();
CollectionProtocol cp = daoFactory.getCollectionProtocolDao().getById(cpId);
if (cp == null) {
return ResponseEvent.userError(CprErrorCode.NOT_FOUND);
}
AccessCtrlMgr.getInstance().ensureReadCpRights(cp);
String filename = cp.getSopDocumentName();
File file = null;
if (StringUtils.isBlank(filename)) {
file = ConfigUtil.getInstance().getFileSetting(ConfigParams.MODULE, ConfigParams.CP_SOP_DOC, null);
} else {
file = new File(getSopDocDir() + filename);
if (!file.exists()) {
filename = filename.split("_", 2)[1];
return ResponseEvent.userError(CpErrorCode.SOP_DOC_MOVED_OR_DELETED, cp.getShortTitle(), filename);
}
}
if (file == null) {
return ResponseEvent.userError(CpErrorCode.SOP_DOC_NOT_FOUND, cp.getShortTitle());
}
return ResponseEvent.response(file);
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
public ResponseEvent<String> uploadSopDocument(RequestEvent<FileDetail> req) {
OutputStream out = null;
try {
FileDetail detail = req.getPayload();
String filename = UUID.randomUUID() + "_" + detail.getFilename();
File file = new File(getSopDocDir() + filename);
out = new FileOutputStream(file);
IOUtils.copy(detail.getFileIn(), out);
return ResponseEvent.response(filename);
} catch (Exception e) {
return ResponseEvent.serverError(e);
} finally {
IOUtils.closeQuietly(out);
}
}
@Override
@PlusTransactional
public ResponseEvent<CollectionProtocolDetail> importCollectionProtocol(RequestEvent<CollectionProtocolDetail> req) {
try {
CollectionProtocolDetail cpDetail = req.getPayload();
ResponseEvent<CollectionProtocolDetail> resp = createCollectionProtocol(req);
resp.throwErrorIfUnsuccessful();
Long cpId = resp.getPayload().getId();
importConsents(cpId, cpDetail.getConsents());
importEvents(cpDetail.getTitle(), cpDetail.getEvents());
importWorkflows(cpId, cpDetail.getWorkflows());
return resp;
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<Boolean> isSpecimenBarcodingEnabled() {
try {
boolean isEnabled = ConfigUtil.getInstance().getBoolSetting(
ConfigParams.MODULE, ConfigParams.ENABLE_SPMN_BARCODING, false);
if (!isEnabled) {
isEnabled = daoFactory.getCollectionProtocolDao().anyBarcodingEnabledCpExists();
}
return ResponseEvent.response(isEnabled);
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<ConsentTierDetail>> getConsentTiers(RequestEvent<Long> req) {
Long cpId = req.getPayload();
try {
CollectionProtocol cp = daoFactory.getCollectionProtocolDao().getById(cpId);
if (cp == null) {
return ResponseEvent.userError(CpErrorCode.NOT_FOUND);
}
AccessCtrlMgr.getInstance().ensureReadCpRights(cp);
return ResponseEvent.response(ConsentTierDetail.from(cp.getConsentTier()));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<ConsentTierDetail> updateConsentTier(RequestEvent<ConsentTierOp> req) {
try {
ConsentTierOp opDetail = req.getPayload();
CollectionProtocol cp = daoFactory.getCollectionProtocolDao().getById(opDetail.getCpId());
if (cp == null) {
return ResponseEvent.userError(CpErrorCode.NOT_FOUND);
}
AccessCtrlMgr.getInstance().ensureUpdateCpRights(cp);
if (cp.isConsentsWaived()) {
return ResponseEvent.userError(CpErrorCode.CONSENTS_WAIVED, cp.getShortTitle());
}
ConsentTierDetail input = opDetail.getConsentTier();
CpConsentTier resp = null;
ConsentStatement stmt = null;
switch (opDetail.getOp()) {
case ADD:
ensureUniqueConsentStatement(input, cp);
stmt = getStatement(input.getStatementId(), input.getStatementCode(), input.getStatement());
resp = cp.addConsentTier(getConsentTierObj(input.getId(), stmt));
break;
case UPDATE:
ensureUniqueConsentStatement(input, cp);
stmt = getStatement(input.getStatementId(), input.getStatementCode(), input.getStatement());
resp = cp.updateConsentTier(getConsentTierObj(input.getId(), stmt));
break;
case REMOVE:
resp = cp.removeConsentTier(input.getId());
break;
}
if (resp != null) {
daoFactory.getCollectionProtocolDao().saveOrUpdate(cp, true);
}
return ResponseEvent.response(ConsentTierDetail.from(resp));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<DependentEntityDetail>> getConsentDependentEntities(RequestEvent<ConsentTierDetail> req) {
try {
ConsentTierDetail consentTierDetail = req.getPayload();
CpConsentTier consentTier = getConsentTier(consentTierDetail);
return ResponseEvent.response(consentTier.getDependentEntities());
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch(Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<CollectionProtocolEventDetail>> getProtocolEvents(RequestEvent<Long> req) {
Long cpId = req.getPayload();
try {
CollectionProtocol cp = daoFactory.getCollectionProtocolDao().getById(cpId);
if (cp == null) {
return ResponseEvent.userError(CpErrorCode.NOT_FOUND);
}
AccessCtrlMgr.getInstance().ensureReadCpRights(cp);
return ResponseEvent.response(CollectionProtocolEventDetail.from(cp.getOrderedCpeList()));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<CollectionProtocolEventDetail> getProtocolEvent(RequestEvent<Long> req) {
Long cpeId = req.getPayload();
try {
CollectionProtocolEvent cpe = daoFactory.getCollectionProtocolDao().getCpe(cpeId);
if (cpe == null) {
return ResponseEvent.userError(CpeErrorCode.NOT_FOUND, cpeId, 1);
}
CollectionProtocol cp = cpe.getCollectionProtocol();
AccessCtrlMgr.getInstance().ensureReadCpRights(cp);
if (cpe.getEventPoint() != null) {
CollectionProtocolEvent firstEvent = cp.firstEvent();
if (firstEvent.getEventPoint() != null) {
cpe.setOffset(firstEvent.getEventPoint());
cpe.setOffsetUnit(firstEvent.getEventPointUnit());
}
}
return ResponseEvent.response(CollectionProtocolEventDetail.from(cpe));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<CollectionProtocolEventDetail> addEvent(RequestEvent<CollectionProtocolEventDetail> req) {
try {
CollectionProtocolEvent cpe = cpeFactory.createCpe(req.getPayload());
CollectionProtocol cp = cpe.getCollectionProtocol();
AccessCtrlMgr.getInstance().ensureUpdateCpRights(cp);
cp.addCpe(cpe);
daoFactory.getCollectionProtocolDao().saveOrUpdate(cp, true);
return ResponseEvent.response(CollectionProtocolEventDetail.from(cpe));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<CollectionProtocolEventDetail> updateEvent(RequestEvent<CollectionProtocolEventDetail> req) {
try {
CollectionProtocolEvent cpe = cpeFactory.createCpe(req.getPayload());
CollectionProtocol cp = cpe.getCollectionProtocol();
AccessCtrlMgr.getInstance().ensureUpdateCpRights(cp);
cp.updateCpe(cpe);
return ResponseEvent.response(CollectionProtocolEventDetail.from(cpe));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<CollectionProtocolEventDetail> copyEvent(RequestEvent<CopyCpeOpDetail> req) {
try {
CollectionProtocolDao cpDao = daoFactory.getCollectionProtocolDao();
CopyCpeOpDetail opDetail = req.getPayload();
String cpTitle = opDetail.getCollectionProtocol();
String eventLabel = opDetail.getEventLabel();
CollectionProtocolEvent existing = null;
Object key = null;
if (opDetail.getEventId() != null) {
existing = cpDao.getCpe(opDetail.getEventId());
key = opDetail.getEventId();
} else if (!StringUtils.isBlank(eventLabel) && !StringUtils.isBlank(cpTitle)) {
existing = cpDao.getCpeByEventLabel(cpTitle, eventLabel);
key = eventLabel;
}
if (existing == null) {
throw OpenSpecimenException.userError(CpeErrorCode.NOT_FOUND, key, 1);
}
CollectionProtocol cp = existing.getCollectionProtocol();
AccessCtrlMgr.getInstance().ensureUpdateCpRights(cp);
CollectionProtocolEvent cpe = cpeFactory.createCpeCopy(opDetail.getCpe(), existing);
existing.copySpecimenRequirementsTo(cpe);
cp.addCpe(cpe);
cpDao.saveOrUpdate(cp, true);
return ResponseEvent.response(CollectionProtocolEventDetail.from(cpe));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<CollectionProtocolEventDetail> deleteEvent(RequestEvent<Long> req) {
try {
Long cpeId = req.getPayload();
CollectionProtocolEvent cpe = daoFactory.getCollectionProtocolDao().getCpe(cpeId);
if (cpe == null) {
throw OpenSpecimenException.userError(CpeErrorCode.NOT_FOUND, cpeId, 1);
}
CollectionProtocol cp = cpe.getCollectionProtocol();
AccessCtrlMgr.getInstance().ensureUpdateCpRights(cp);
cpe.delete();
daoFactory.getCollectionProtocolDao().saveCpe(cpe);
return ResponseEvent.response(CollectionProtocolEventDetail.from(cpe));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<SpecimenRequirementDetail>> getSpecimenRequirments(RequestEvent<Tuple> req) {
try {
Tuple tuple = req.getPayload();
Long cpId = tuple.element(0);
Long cpeId = tuple.element(1);
String cpeLabel = tuple.element(2);
boolean includeChildren = tuple.element(3) == null || (Boolean) tuple.element(3);
CollectionProtocolEvent cpe = null;
Object key = null;
if (cpeId != null) {
cpe = daoFactory.getCollectionProtocolDao().getCpe(cpeId);
key = cpeId;
} else if (StringUtils.isNotBlank(cpeLabel)) {
if (cpId == null) {
throw OpenSpecimenException.userError(CpErrorCode.REQUIRED);
}
cpe = daoFactory.getCollectionProtocolDao().getCpeByEventLabel(cpId, cpeLabel);
key = cpeLabel;
}
if (key == null) {
return ResponseEvent.response(Collections.emptyList());
} else if (cpe == null) {
return ResponseEvent.userError(CpeErrorCode.NOT_FOUND, key, 1);
}
AccessCtrlMgr.getInstance().ensureReadCpRights(cpe.getCollectionProtocol());
return ResponseEvent.response(SpecimenRequirementDetail.from(cpe.getTopLevelAnticipatedSpecimens(), includeChildren));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<SpecimenRequirementDetail> getSpecimenRequirement(RequestEvent<Long> req) {
Long reqId = req.getPayload();
try {
SpecimenRequirement sr = daoFactory.getSpecimenRequirementDao().getById(reqId);
if (sr == null) {
return ResponseEvent.userError(SrErrorCode.NOT_FOUND);
}
AccessCtrlMgr.getInstance().ensureReadCpRights(sr.getCollectionProtocol());
return ResponseEvent.response(SpecimenRequirementDetail.from(sr));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<SpecimenRequirementDetail> addSpecimenRequirement(RequestEvent<SpecimenRequirementDetail> req) {
try {
SpecimenRequirement requirement = srFactory.createSpecimenRequirement(req.getPayload());
CollectionProtocolEvent cpe = requirement.getCollectionProtocolEvent();
AccessCtrlMgr.getInstance().ensureUpdateCpRights(cpe.getCollectionProtocol());
cpe.addSpecimenRequirement(requirement);
daoFactory.getCollectionProtocolDao().saveCpe(cpe, true);
return ResponseEvent.response(SpecimenRequirementDetail.from(requirement));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<SpecimenRequirementDetail>> addSpecimenPoolReqs(RequestEvent<SpecimenPoolRequirements> req) {
try {
List<SpecimenRequirement> spmnPoolReqs = srFactory.createSpecimenPoolReqs(req.getPayload());
SpecimenRequirement pooledReq = spmnPoolReqs.iterator().next().getPooledSpecimenRequirement();
AccessCtrlMgr.getInstance().ensureUpdateCpRights(pooledReq.getCollectionProtocol());
pooledReq.getCollectionProtocolEvent().ensureUniqueSrCodes(spmnPoolReqs);
pooledReq.addSpecimenPoolReqs(spmnPoolReqs);
daoFactory.getSpecimenRequirementDao().saveOrUpdate(pooledReq, true);
return ResponseEvent.response(SpecimenRequirementDetail.from(spmnPoolReqs));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<SpecimenRequirementDetail>> createAliquots(RequestEvent<AliquotSpecimensRequirement> req) {
try {
return ResponseEvent.response(SpecimenRequirementDetail.from(createAliquots(req.getPayload())));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<SpecimenRequirementDetail> createDerived(RequestEvent<DerivedSpecimenRequirement> req) {
try {
DerivedSpecimenRequirement requirement = req.getPayload();
SpecimenRequirement derived = srFactory.createDerived(requirement);
AccessCtrlMgr.getInstance().ensureUpdateCpRights(derived.getCollectionProtocol());
ensureSrIsNotClosed(derived.getParentSpecimenRequirement());
if (StringUtils.isNotBlank(derived.getCode())) {
if (derived.getCollectionProtocolEvent().getSrByCode(derived.getCode()) != null) {
return ResponseEvent.userError(SrErrorCode.DUP_CODE, derived.getCode());
}
}
daoFactory.getSpecimenRequirementDao().saveOrUpdate(derived, true);
return ResponseEvent.response(SpecimenRequirementDetail.from(derived));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<SpecimenRequirementDetail> updateSpecimenRequirement(RequestEvent<SpecimenRequirementDetail> req) {
try {
SpecimenRequirementDetail detail = req.getPayload();
Long srId = detail.getId();
SpecimenRequirement sr = daoFactory.getSpecimenRequirementDao().getById(srId);
if (sr == null) {
throw OpenSpecimenException.userError(SrErrorCode.NOT_FOUND);
}
AccessCtrlMgr.getInstance().ensureUpdateCpRights(sr.getCollectionProtocol());
SpecimenRequirement partial = srFactory.createForUpdate(sr.getLineage(), detail);
if (isSpecimenClassOrTypeChanged(sr, partial)) {
ensureSpecimensNotCollected(sr);
}
sr.update(partial);
return ResponseEvent.response(SpecimenRequirementDetail.from(sr));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<SpecimenRequirementDetail> copySpecimenRequirement(RequestEvent<Long> req) {
try {
Long srId = req.getPayload();
SpecimenRequirement sr = daoFactory.getSpecimenRequirementDao().getById(srId);
if (sr == null) {
throw OpenSpecimenException.userError(SrErrorCode.NOT_FOUND);
}
AccessCtrlMgr.getInstance().ensureUpdateCpRights(sr.getCollectionProtocol());
SpecimenRequirement copy = sr.deepCopy(null);
daoFactory.getSpecimenRequirementDao().saveOrUpdate(copy, true);
return ResponseEvent.response(SpecimenRequirementDetail.from(copy));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<SpecimenRequirementDetail> deleteSpecimenRequirement(RequestEvent<Long> req) {
try {
Long srId = req.getPayload();
SpecimenRequirement sr = daoFactory.getSpecimenRequirementDao().getById(srId);
if (sr == null) {
throw OpenSpecimenException.userError(SrErrorCode.NOT_FOUND);
}
AccessCtrlMgr.getInstance().ensureUpdateCpRights(sr.getCollectionProtocol());
sr.delete();
daoFactory.getSpecimenRequirementDao().saveOrUpdate(sr);
return ResponseEvent.response(SpecimenRequirementDetail.from(sr));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<Integer> getSrSpecimensCount(RequestEvent<Long> req) {
try {
Long srId = req.getPayload();
SpecimenRequirement sr = daoFactory.getSpecimenRequirementDao().getById(srId);
if (sr == null) {
throw OpenSpecimenException.userError(SrErrorCode.NOT_FOUND);
}
return ResponseEvent.response(
daoFactory.getSpecimenRequirementDao().getSpecimensCount(srId));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<PdeTokenDetail>> getPdeLinks(RequestEvent<PdeNotifListCriteria> req) {
try {
PdeNotifListCriteria crit = req.getPayload();
List<PdeNotif> notifs = daoFactory.getPdeNotifDao().getNotifs(crit);
Map<String, List<Long>> tokenIdsByType = new HashMap<>();
for (PdeNotif notif : notifs) {
for (PdeNotifLink link : notif.getLinks()) {
List<Long> tokenIds = tokenIdsByType.computeIfAbsent(link.getType(), (k) -> new ArrayList<>());
tokenIds.add(link.getTokenId());
}
}
Map<String, PdeTokenDetail> tokensMap = new HashMap<>();
for (Map.Entry<String, List<Long>> typeTokenIds : tokenIdsByType.entrySet()) {
PdeTokenGenerator generator = pdeTokenGeneratorRegistry.get(typeTokenIds.getKey());
if (generator == null) {
continue;
}
List<PdeTokenDetail> tokens = generator.getTokens(typeTokenIds.getValue());
for (PdeTokenDetail token : tokens) {
tokensMap.put(token.getType() + ":" + token.getTokenId(), token);
}
}
List<PdeTokenDetail> result = new ArrayList<>();
for (PdeNotif notif : notifs) {
for (PdeNotifLink link : notif.getLinks()) {
PdeTokenDetail token = tokensMap.get(link.getType() + ":" + link.getTokenId());
if (token != null) {
result.add(token);
}
}
}
return ResponseEvent.response(result);
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<CpReportSettingsDetail> getReportSettings(RequestEvent<CpQueryCriteria> req) {
try {
CpReportSettings settings = getReportSetting(req.getPayload());
if (settings == null) {
return ResponseEvent.response(null);
}
AccessCtrlMgr.getInstance().ensureReadCpRights(settings.getCp());
return ResponseEvent.response(CpReportSettingsDetail.from(settings));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<CpReportSettingsDetail> saveReportSettings(RequestEvent<CpReportSettingsDetail> req) {
try {
CpReportSettings settings = rptSettingsFactory.createSettings(req.getPayload());
CollectionProtocol cp = settings.getCp();
AccessCtrlMgr.getInstance().ensureUpdateCpRights(cp);
CpReportSettings existing = daoFactory.getCpReportSettingsDao().getByCp(cp.getId());
if (existing == null) {
existing = settings;
} else {
existing.update(settings);
}
daoFactory.getCpReportSettingsDao().saveOrUpdate(existing);
return ResponseEvent.response(CpReportSettingsDetail.from(existing));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<CpReportSettingsDetail> deleteReportSettings(RequestEvent<CpQueryCriteria> req) {
try {
CpReportSettings settings = getReportSetting(req.getPayload());
if (settings == null) {
return ResponseEvent.response(null);
}
AccessCtrlMgr.getInstance().ensureUpdateCpRights(settings.getCp());
settings.delete();
return ResponseEvent.response(CpReportSettingsDetail.from(settings));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<Boolean> generateReport(RequestEvent<CpQueryCriteria> req) {
try {
CpQueryCriteria crit = req.getPayload();
CollectionProtocol cp = getCollectionProtocol(crit.getId(), crit.getTitle(), crit.getShortTitle());
AccessCtrlMgr.getInstance().ensureReadCpRights(cp);
CpReportSettings cpSettings = daoFactory.getCpReportSettingsDao().getByCp(cp.getId());
if (cpSettings != null && !cpSettings.isEnabled()) {
return ResponseEvent.userError(CpErrorCode.RPT_DISABLED, cp.getShortTitle());
}
taskExecutor.execute(new CpReportTask(cp.getId()));
return ResponseEvent.response(true);
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<File> getReportFile(Long cpId, String fileId) {
try {
CollectionProtocol cp = getCollectionProtocol(cpId, null, null);
AccessCtrlMgr.getInstance().ensureReadCpRights(cp);
File file = new CpReportGenerator().getDataFile(cpId, fileId);
if (file == null) {
return ResponseEvent.userError(CpErrorCode.RPT_FILE_NOT_FOUND);
}
return ResponseEvent.response(file);
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<CpWorkflowCfgDetail> getWorkflows(RequestEvent<Long> req) {
Long cpId = req.getPayload();
CollectionProtocol cp = null;
CpWorkflowConfig cfg;
if (cpId == null || cpId == -1L) {
cfg = WorkflowUtil.getInstance().getSysWorkflows();
} else {
cp = daoFactory.getCollectionProtocolDao().getById(cpId);
if (cp == null) {
return ResponseEvent.userError(CpErrorCode.NOT_FOUND);
}
cfg = daoFactory.getCollectionProtocolDao().getCpWorkflows(cpId);
}
if (cfg == null) {
cfg = new CpWorkflowConfig();
cfg.setCp(cp);
}
return ResponseEvent.response(CpWorkflowCfgDetail.from(cfg));
}
@Override
@PlusTransactional
public ResponseEvent<CpWorkflowCfgDetail> saveWorkflows(RequestEvent<CpWorkflowCfgDetail> req) {
try {
CpWorkflowCfgDetail input = req.getPayload();
CollectionProtocol cp = daoFactory.getCollectionProtocolDao().getById(input.getCpId());
if (cp == null) {
return ResponseEvent.userError(CpErrorCode.NOT_FOUND);
}
AccessCtrlMgr.getInstance().ensureUpdateCpRights(cp);
CpWorkflowConfig cfg = saveWorkflows(cp, input);
return ResponseEvent.response(CpWorkflowCfgDetail.from(cfg));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<List<CollectionProtocolSummary>> getRegisterEnabledCps(
List<String> siteNames, String searchTitle, int maxResults) {
try {
Set<Long> cpIds = AccessCtrlMgr.getInstance().getRegisterEnabledCpIds(siteNames);
CpListCriteria crit = new CpListCriteria().title(searchTitle).maxResults(maxResults);
if (cpIds != null && cpIds.isEmpty()) {
return ResponseEvent.response(Collections.<CollectionProtocolSummary>emptyList());
} else if (cpIds != null) {
crit.ids(new ArrayList<>(cpIds));
}
return ResponseEvent.response(daoFactory.getCollectionProtocolDao().getCollectionProtocols(crit));
} catch (OpenSpecimenException ose) {
return ResponseEvent.error(ose);
} catch (Exception e) {
return ResponseEvent.serverError(e);
}
}
@Override
@PlusTransactional
public ResponseEvent<ListConfig> getCpListCfg(RequestEvent<Map<String, Object>> req) {
return listSvc.getListCfg(req);
}
@Override
@PlusTransactional
public ResponseEvent<ListDetail> getList(RequestEvent<Map<String, Object>> req) {
return listSvc.getList(req);
}
@Override
@PlusTransactional
public ResponseEvent<Integer> getListSize(RequestEvent<Map<String, Object>> req) {
return listSvc.getListSize(req);
}
@Override
@PlusTransactional
public ResponseEvent<Collection<Object>> getListExprValues(RequestEvent<Map<String, Object>> req) {
return listSvc.getListExprValues(req);
}
@Override
@PlusTransactional
public boolean toggleStarredCp(Long cpId, boolean starred) {
try {
CollectionProtocol cp = daoFactory.getCollectionProtocolDao().getById(cpId);
if (cp == null) {
throw OpenSpecimenException.userError(CpErrorCode.NOT_FOUND, cpId);
}
AccessCtrlMgr.getInstance().ensureReadCpRights(cp);
if (starred) {
starredItemSvc.save(getObjectName(), cp.getId());
} else {
starredItemSvc.delete(getObjectName(), cp.getId());
}
return true;
} catch (Exception e) {
if (e instanceof OpenSpecimenException) {
throw e;
}
throw OpenSpecimenException.serverError(e);
}
}
@Override
public String getObjectName() {
return CollectionProtocol.getEntityName();
}
@Override
@PlusTransactional
public Map<String, Object> resolveUrl(String key, Object value) {
if (key.equals("id")) {
value = Long.valueOf(value.toString());
}
return daoFactory.getCollectionProtocolDao().getCpIds(key, value);
}
@Override
public String getAuditTable() {
return "CAT_COLLECTION_PROTOCOL_AUD";
}
@Override
public void ensureReadAllowed(Long id) {
CollectionProtocol cp = getCollectionProtocol(id, null, null);
AccessCtrlMgr.getInstance().ensureReadCpRights(cp);
}
@Override
public void afterPropertiesSet() throws Exception {
listSvc.registerListConfigurator("cp-list-view", this::getCpListConfig);
listSvc.registerListConfigurator("participant-list-view", this::getParticipantsListConfig);
listSvc.registerListConfigurator("specimen-list-view", this::getSpecimenListConfig);
}
@Override
public CpWorkflowConfig saveWorkflows(CollectionProtocol cp, CpWorkflowCfgDetail input) {
CpWorkflowConfig cfg = daoFactory.getCollectionProtocolDao().getCpWorkflows(cp.getId());
if (cfg == null) {
cfg = new CpWorkflowConfig();
cfg.setCp(cp);
}
if (!input.isPatch()) {
cfg.getWorkflows().clear();
}
if (input.getWorkflows() != null) {
for (WorkflowDetail detail : input.getWorkflows().values()) {
Workflow wf = new Workflow();
BeanUtils.copyProperties(detail, wf);
cfg.getWorkflows().put(wf.getName(), wf);
}
}
daoFactory.getCollectionProtocolDao().saveCpWorkflows(cfg);
return cfg;
}
private CpListCriteria addCpListCriteria(CpListCriteria crit) {
Set<SiteCpPair> siteCps = AccessCtrlMgr.getInstance().getReadableSiteCps();
return siteCps != null && siteCps.isEmpty() ? null : crit.siteCps(siteCps);
}
private CprListCriteria addCprListCriteria(CprListCriteria listCrit) {
ParticipantReadAccess access = AccessCtrlMgr.getInstance().getParticipantReadAccess(listCrit.cpId());
if (!access.admin) {
if (access.noAccessibleSites() || (!access.phiAccess && listCrit.hasPhiFields())) {
return null;
}
}
return listCrit.includePhi(access.phiAccess)
.phiSiteCps(access.phiSiteCps)
.siteCps(access.siteCps)
.useMrnSites(AccessCtrlMgr.getInstance().isAccessRestrictedBasedOnMrn());
}
private CollectionProtocol createCollectionProtocol(CollectionProtocolDetail detail, CollectionProtocol existing, boolean createCopy) {
CollectionProtocol cp = null;
if (!createCopy) {
cp = cpFactory.createCollectionProtocol(detail);
} else {
cp = cpFactory.createCpCopy(detail, existing);
}
AccessCtrlMgr.getInstance().ensureCreateCpRights(cp);
ensureUsersBelongtoCpSites(cp);
OpenSpecimenException ose = new OpenSpecimenException(ErrorType.USER_ERROR);
ensureUniqueTitle(null, cp, ose);
ensureUniqueShortTitle(null, cp, ose);
ensureUniqueCode(null, cp, ose);
ensureUniqueCpSiteCode(cp, ose);
ose.checkAndThrow();
daoFactory.getCollectionProtocolDao().saveOrUpdate(cp, true);
cp.addOrUpdateExtension();
//Assign default roles to PI and Coordinators
addOrRemovePiCoordinatorRoles(cp, "CREATE", null, cp.getPrincipalInvestigator(), cp.getCoordinators(), null);
fixSopDocumentName(cp);
copyWorkflows(existing, cp);
return cp;
}
private void ensureUsersBelongtoCpSites(CollectionProtocol cp) {
ensureCreatorBelongToCpSites(cp);
}
private void ensureCreatorBelongToCpSites(CollectionProtocol cp) {
User user = AuthUtil.getCurrentUser();
if (user.isAdmin()) {
return;
}
Set<Site> cpSites = cp.getRepositories();
if (cpSites.stream().anyMatch(cpSite -> !cpSite.getInstitute().equals(AuthUtil.getCurrentUserInstitute()))) {
throw OpenSpecimenException.userError(CpErrorCode.CREATOR_DOES_NOT_BELONG_CP_REPOS);
}
}
private void ensureUniqueTitle(CollectionProtocol existingCp, CollectionProtocol cp, OpenSpecimenException ose) {
String title = cp.getTitle();
if (existingCp != null && existingCp.getTitle().equals(title)) {
return;
}
CollectionProtocol dbCp = daoFactory.getCollectionProtocolDao().getCollectionProtocol(title);
if (dbCp != null) {
ose.addError(CpErrorCode.DUP_TITLE, title);
}
}
private void ensureUniqueShortTitle(CollectionProtocol existingCp, CollectionProtocol cp, OpenSpecimenException ose) {
String shortTitle = cp.getShortTitle();
if (existingCp != null && existingCp.getShortTitle().equals(shortTitle)) {
return;
}
CollectionProtocol dbCp = daoFactory.getCollectionProtocolDao().getCpByShortTitle(shortTitle);
if (dbCp != null) {
ose.addError(CpErrorCode.DUP_SHORT_TITLE, shortTitle);
}
}
private void ensureUniqueCode(CollectionProtocol existingCp, CollectionProtocol cp, OpenSpecimenException ose) {
String code = cp.getCode();
if (StringUtils.isBlank(code)) {
return;
}
if (existingCp != null && code.equals(existingCp.getCode())) {
return;
}
CollectionProtocol dbCp = daoFactory.getCollectionProtocolDao().getCpByCode(code);
if (dbCp != null) {
ose.addError(CpErrorCode.DUP_CODE, code);
}
}
private void ensureUniqueCpSiteCode(CollectionProtocol cp, OpenSpecimenException ose) {
List<String> codes = Utility.<List<String>>collect(cp.getSites(), "code");
codes.removeAll(Arrays.asList(new String[] {null, ""}));
Set<String> uniqueCodes = new HashSet<String>(codes);
if (codes.size() != uniqueCodes.size()) {
ose.addError(CpErrorCode.DUP_CP_SITE_CODES, codes);
}
}
private void ensureSitesAreNotInUse(CollectionProtocol cp, Collection<Site> sites) {
if (sites.isEmpty()) {
return;
}
List<Long> siteIds = sites.stream().map(Site::getId).collect(Collectors.toList());
Map<String, Integer> counts = daoFactory.getCprDao().getParticipantsBySite(cp.getId(), siteIds);
if (!counts.isEmpty()) {
String siteLabels = counts.keySet().stream().collect(Collectors.joining(", "));
throw OpenSpecimenException.userError(CpErrorCode.USED_SITES, siteLabels, counts.size());
}
}
private void fixSopDocumentName(CollectionProtocol cp) {
if (StringUtils.isBlank(cp.getSopDocumentName())) {
return;
}
String[] nameParts = cp.getSopDocumentName().split("_", 2);
if (nameParts[0].equals(cp.getId().toString())) {
return;
}
try {
UUID uuid = UUID.fromString(nameParts[0]);
} catch (Exception e) {
throw OpenSpecimenException.userError(CpErrorCode.INVALID_SOP_DOC, cp.getSopDocumentName());
}
if (StringUtils.isBlank(nameParts[1])) {
throw OpenSpecimenException.userError(CpErrorCode.INVALID_SOP_DOC, cp.getSopDocumentName());
}
File src = new File(getSopDocDir() + File.separator + cp.getSopDocumentName());
if (!src.exists()) {
throw OpenSpecimenException.userError(CpErrorCode.SOP_DOC_MOVED_OR_DELETED, cp.getSopDocumentName(), cp.getShortTitle());
}
cp.setSopDocumentName(cp.getId() + "_" + nameParts[1]);
File dest = new File(getSopDocDir() + File.separator + cp.getSopDocumentName());
src.renameTo(dest);
}
private void ensureConsentTierIsEmpty(CollectionProtocol existingCp, OpenSpecimenException ose) {
if (CollectionUtils.isNotEmpty(existingCp.getConsentTier())) {
ose.addError(CpErrorCode.CONSENT_TIER_FOUND, existingCp.getShortTitle());
}
}
private void importConsents(Long cpId, List<ConsentTierDetail> consents) {
if (CollectionUtils.isEmpty(consents)) {
return;
}
for (ConsentTierDetail consent : consents) {
ConsentTierOp addOp = new ConsentTierOp();
addOp.setConsentTier(consent);
addOp.setCpId(cpId);
addOp.setOp(OP.ADD);
ResponseEvent<ConsentTierDetail> resp = updateConsentTier(new RequestEvent<>(addOp));
resp.throwErrorIfUnsuccessful();
}
}
private void importEvents(String cpTitle, List<CollectionProtocolEventDetail> events) {
if (CollectionUtils.isEmpty(events)) {
return;
}
for (CollectionProtocolEventDetail event : events) {
if (Status.isClosedOrDisabledStatus(event.getActivityStatus())) {
continue;
}
event.setCollectionProtocol(cpTitle);
ResponseEvent<CollectionProtocolEventDetail> resp = addEvent(new RequestEvent<>(event));
resp.throwErrorIfUnsuccessful();
Long eventId = resp.getPayload().getId();
importSpecimenReqs(eventId, null, event.getSpecimenRequirements());
}
}
private void importSpecimenReqs(Long eventId, Long parentSrId, List<SpecimenRequirementDetail> srs) {
if (CollectionUtils.isEmpty(srs)) {
return;
}
for (SpecimenRequirementDetail sr : srs) {
if (Status.isClosedOrDisabledStatus(sr.getActivityStatus())) {
continue;
}
sr.setEventId(eventId);
if (sr.getLineage().equals(Specimen.NEW)) {
ResponseEvent<SpecimenRequirementDetail> resp = addSpecimenRequirement(new RequestEvent<>(sr));
resp.throwErrorIfUnsuccessful();
importSpecimenReqs(eventId, resp.getPayload().getId(), sr.getChildren());
} else if (parentSrId != null && sr.getLineage().equals(Specimen.ALIQUOT)) {
AliquotSpecimensRequirement aliquotReq = sr.toAliquotRequirement(parentSrId, 1);
List<SpecimenRequirement> aliquots = createAliquots(aliquotReq);
if (StringUtils.isNotBlank(sr.getCode())) {
aliquots.get(0).setCode(sr.getCode());
}
importSpecimenReqs(eventId, aliquots.get(0).getId(), sr.getChildren());
} else if (parentSrId != null && sr.getLineage().equals(Specimen.DERIVED)) {
DerivedSpecimenRequirement derivedReq = sr.toDerivedRequirement(parentSrId);
ResponseEvent<SpecimenRequirementDetail> resp = createDerived(new RequestEvent<DerivedSpecimenRequirement>(derivedReq));
resp.throwErrorIfUnsuccessful();
importSpecimenReqs(eventId, resp.getPayload().getId(), sr.getChildren());
}
}
}
private void ensureSrIsNotClosed(SpecimenRequirement sr) {
if (!sr.isClosed()) {
return;
}
String key = sr.getCode();
if (StringUtils.isBlank(key)) {
key = sr.getName();
}
if (StringUtils.isBlank(key)) {
key = sr.getId().toString();
}
throw OpenSpecimenException.userError(SrErrorCode.CLOSED, key);
}
private List<SpecimenRequirement> createAliquots(AliquotSpecimensRequirement requirement) {
List<SpecimenRequirement> aliquots = srFactory.createAliquots(requirement);
SpecimenRequirement aliquot = aliquots.iterator().next();
AccessCtrlMgr.getInstance().ensureUpdateCpRights(aliquot.getCollectionProtocol());
SpecimenRequirement parent = aliquot.getParentSpecimenRequirement();
if (StringUtils.isNotBlank(requirement.getCode())) {
setAliquotCode(parent, aliquots, requirement.getCode());
}
parent.addChildRequirements(aliquots);
daoFactory.getSpecimenRequirementDao().saveOrUpdate(parent, true);
return aliquots;
}
private void importWorkflows(Long cpId, Map<String, WorkflowDetail> workflows) {
CpWorkflowCfgDetail input = new CpWorkflowCfgDetail();
input.setCpId(cpId);
input.setWorkflows(workflows);
ResponseEvent<CpWorkflowCfgDetail> resp = saveWorkflows(new RequestEvent<>(input));
resp.throwErrorIfUnsuccessful();
}
private void copyWorkflows(CollectionProtocol srcCp, CollectionProtocol dstCp) {
if (srcCp == null) {
return;
}
CpWorkflowConfig srcWfCfg = daoFactory.getCollectionProtocolDao().getCpWorkflows(srcCp.getId());
if (srcWfCfg != null) {
CpWorkflowConfig newConfig = new CpWorkflowConfig();
newConfig.setCp(dstCp);
newConfig.setWorkflows(srcWfCfg.getWorkflows());
daoFactory.getCollectionProtocolDao().saveCpWorkflows(newConfig);
}
}
private void addOrRemovePiCoordinatorRoles(CollectionProtocol cp, String cpOp, User oldPi, User newPi, Collection<User> newCoord, Collection<User> removedCoord) {
List<User> notifUsers = null;
if (!Objects.equals(oldPi, newPi)) {
notifUsers = AccessCtrlMgr.getInstance().getSiteAdmins(null, cp);
if (newPi != null) {
addDefaultPiRoles(cp, notifUsers, newPi, cpOp);
}
if (oldPi != null) {
removeDefaultPiRoles(cp, notifUsers, oldPi, cpOp);
}
}
if (CollectionUtils.isNotEmpty(newCoord)) {
if (notifUsers == null) {
notifUsers = AccessCtrlMgr.getInstance().getSiteAdmins(null, cp);
}
addDefaultCoordinatorRoles(cp, notifUsers, newCoord, cpOp);
}
if (CollectionUtils.isNotEmpty(removedCoord)) {
if (notifUsers == null) {
notifUsers = AccessCtrlMgr.getInstance().getSiteAdmins(null, cp);
}
removeDefaultCoordinatorRoles(cp, notifUsers, removedCoord, cpOp);
}
}
private void addDefaultPiRoles(CollectionProtocol cp, List<User> notifUsers, User user, String cpOp) {
try {
if (user.isContact()) {
return;
}
for (String role : getDefaultPiRoles()) {
addRole(cp, notifUsers, user, role, cpOp);
}
} catch (OpenSpecimenException ose) {
ose.rethrow(RbacErrorCode.ACCESS_DENIED, CpErrorCode.USER_UPDATE_RIGHTS_REQUIRED);
throw ose;
}
}
private void removeDefaultPiRoles(CollectionProtocol cp, List<User> notifUsers, User user, String cpOp) {
try {
for (String role : getDefaultPiRoles()) {
removeRole(cp, notifUsers, user, role, cpOp);
}
} catch (OpenSpecimenException ose) {
ose.rethrow(RbacErrorCode.ACCESS_DENIED, CpErrorCode.USER_UPDATE_RIGHTS_REQUIRED);
}
}
private void addDefaultCoordinatorRoles(CollectionProtocol cp, List<User> notifUsers, Collection<User> coordinators, String cpOp) {
try {
for (User user : coordinators) {
if (user.isContact()) {
continue;
}
for (String role : getDefaultCoordinatorRoles()) {
addRole(cp, notifUsers, user, role, cpOp);
}
}
} catch (OpenSpecimenException ose) {
ose.rethrow(RbacErrorCode.ACCESS_DENIED, CpErrorCode.USER_UPDATE_RIGHTS_REQUIRED);
}
}
private void removeDefaultCoordinatorRoles(CollectionProtocol cp, List<User> notifUsers, Collection<User> coordinators, String cpOp) {
try {
for (User user : coordinators) {
for (String role : getDefaultCoordinatorRoles()) {
removeRole(cp, notifUsers, user, role, cpOp);
}
}
} catch (OpenSpecimenException ose) {
ose.rethrow(RbacErrorCode.ACCESS_DENIED, CpErrorCode.USER_UPDATE_RIGHTS_REQUIRED);
}
}
private void addRole(CollectionProtocol cp, List<User> admins, User user, String role, String cpOp) {
SubjectRoleOpNotif notifReq = getNotifReq(cp, role, admins, user, cpOp, "ADD");
rbacSvc.addSubjectRole(null, cp, user, new String[] { role }, notifReq);
}
private void removeRole(CollectionProtocol cp, List<User> admins, User user, String role, String cpOp) {
SubjectRoleOpNotif notifReq = getNotifReq(cp, role, admins, user, cpOp, "REMOVE");
rbacSvc.removeSubjectRole(null, cp, user, new String[] { role }, notifReq);
}
private String[] getDefaultPiRoles() {
return new String[] {"Principal Investigator"};
}
private String[] getDefaultCoordinatorRoles() {
return new String[] {"Coordinator"};
}
private CpConsentTier getConsentTier(ConsentTierDetail consentTierDetail) {
CollectionProtocolDao cpDao = daoFactory.getCollectionProtocolDao();
CpConsentTier consentTier = null;
if (consentTierDetail.getId() != null) {
consentTier = cpDao.getConsentTier(consentTierDetail.getId());
} else if (StringUtils.isNotBlank(consentTierDetail.getStatement()) && consentTierDetail.getCpId() != null ) {
consentTier = cpDao.getConsentTierByStatement(consentTierDetail.getCpId(), consentTierDetail.getStatement());
}
if (consentTier == null) {
throw OpenSpecimenException.userError(CpErrorCode.CONSENT_TIER_NOT_FOUND);
}
return consentTier;
}
private void ensureUniqueConsentStatement(ConsentTierDetail consentTierDetail, CollectionProtocol cp) {
Predicate<CpConsentTier> findFn;
if (consentTierDetail.getStatementId() != null) {
findFn = (t) -> t.getStatement().getId().equals(consentTierDetail.getStatementId());
} else if (StringUtils.isNotBlank(consentTierDetail.getStatementCode())) {
findFn = (t) -> t.getStatement().getCode().equals(consentTierDetail.getStatementCode());
} else if (StringUtils.isNotBlank(consentTierDetail.getStatement())) {
findFn = (t) -> t.getStatement().getStatement().equals(consentTierDetail.getStatement());
} else {
throw OpenSpecimenException.userError(ConsentStatementErrorCode.CODE_REQUIRED);
}
CpConsentTier tier = cp.getConsentTier().stream().filter(findFn).findFirst().orElse(null);
if (tier != null && !tier.getId().equals(consentTierDetail.getId())) {
throw OpenSpecimenException.userError(CpErrorCode.DUP_CONSENT, tier.getStatement().getCode(), cp.getShortTitle());
}
}
private CpConsentTier getConsentTierObj(Long id, ConsentStatement stmt) {
CpConsentTier tier = new CpConsentTier();
tier.setId(id);
tier.setStatement(stmt);
return tier;
}
private void ensureSpecimensNotCollected(SpecimenRequirement sr) {
int count = daoFactory.getSpecimenRequirementDao().getSpecimensCount(sr.getId());
if (count > 0) {
throw OpenSpecimenException.userError(SrErrorCode.CANNOT_CHANGE_CLASS_OR_TYPE);
}
}
private boolean isSpecimenClassOrTypeChanged(SpecimenRequirement existingSr, SpecimenRequirement sr) {
return !existingSr.getSpecimenClass().equals(sr.getSpecimenClass()) ||
!existingSr.getSpecimenType().equals(sr.getSpecimenType());
}
private void setAliquotCode(SpecimenRequirement parent, List<SpecimenRequirement> aliquots, String code) {
Set<String> codes = new HashSet<String>();
CollectionProtocolEvent cpe = parent.getCollectionProtocolEvent();
for (SpecimenRequirement sr : cpe.getSpecimenRequirements()) {
if (StringUtils.isNotBlank(sr.getCode())) {
codes.add(sr.getCode());
}
}
int count = 1;
for (SpecimenRequirement sr : aliquots) {
while (!codes.add(code + count)) {
count++;
}
sr.setCode(code + count++);
}
}
private CollectionProtocol getCollectionProtocol(String shortTitle) {
return getCollectionProtocol(null, null, shortTitle);
}
private CollectionProtocol getCollectionProtocol(Long id, String title, String shortTitle) {
CollectionProtocol cp = null;
if (id != null) {
cp = daoFactory.getCollectionProtocolDao().getById(id);
} else if (StringUtils.isNotBlank(title)) {
cp = daoFactory.getCollectionProtocolDao().getCollectionProtocol(title);
} else if (StringUtils.isNoneBlank(shortTitle)) {
cp = daoFactory.getCollectionProtocolDao().getCpByShortTitle(shortTitle);
}
if (cp == null) {
throw OpenSpecimenException.userError(CpErrorCode.NOT_FOUND);
}
return cp;
}
private void mergeCprIntoCp(CollectionProtocolRegistration srcCpr, CollectionProtocol tgtCp) {
//
// Step 1: Get a matching CPR either by PPID or participant ID
//
CollectionProtocolRegistration tgtCpr = daoFactory.getCprDao().getCprByPpid(tgtCp.getId(), srcCpr.getPpid());
if (tgtCpr == null) {
tgtCpr = srcCpr.getParticipant().getCpr(tgtCp);
}
//
// Step 2: Map all visits of source CP registrations to first event of target CP
// Further mark all created specimens as unplanned
//
CollectionProtocolEvent firstCpe = tgtCp.firstEvent();
for (Visit visit : srcCpr.getVisits()) {
visit.setCpEvent(firstCpe);
visit.getSpecimens().forEach(s -> s.setSpecimenRequirement(null));
}
//
// Step 3: Attach registrations to target CP
//
if (tgtCpr == null) {
//
// case 1: No matching registration was found in target CP; therefore make source
// registration as part of target CP
//
srcCpr.setCollectionProtocol(tgtCp);
} else {
//
// case 2: Matching registration was found in target CP; therefore do following
// 2.1 Move all visits of source CP registration to target CP registration
// 2.2 Finally delete source CP registration
//
tgtCpr.addVisits(srcCpr.getVisits());
srcCpr.getVisits().clear();
srcCpr.delete();
}
}
private void ensureMergeableCps(CollectionProtocol srcCp, CollectionProtocol tgtCp) {
ArrayList<String> notSameLabels = new ArrayList<>();
ensureBlankOrSame(srcCp.getPpidFormat(), tgtCp.getPpidFormat(), PPID_MSG, notSameLabels);
ensureBlankOrSame(srcCp.getVisitNameFormat(), tgtCp.getVisitNameFormat(), VISIT_NAME_MSG, notSameLabels);
ensureBlankOrSame(srcCp.getSpecimenLabelFormat(), tgtCp.getSpecimenLabelFormat(), SPECIMEN_LABEL_MSG, notSameLabels);
ensureBlankOrSame(srcCp.getDerivativeLabelFormat(), tgtCp.getDerivativeLabelFormat(), DERIVATIVE_LABEL_MSG, notSameLabels);
ensureBlankOrSame(srcCp.getAliquotLabelFormat(), tgtCp.getAliquotLabelFormat(), ALIQUOT_LABEL_MSG, notSameLabels);
if (!notSameLabels.isEmpty()) {
throw OpenSpecimenException.userError(
CpErrorCode.CANNOT_MERGE_FMT_DIFFERS,
srcCp.getShortTitle(),
tgtCp.getShortTitle(),
notSameLabels);
}
}
private void ensureBlankOrSame(String srcLabelFmt, String tgtLabelFmt, String labelKey, List<String> notSameLabels) {
if (!StringUtils.isBlank(tgtLabelFmt) && !tgtLabelFmt.equals(srcLabelFmt)) {
notSameLabels.add(getMsg(labelKey));
}
}
private boolean forceDeleteCps(final List<CollectionProtocol> cps, final String reason)
throws Exception {
final Authentication auth = AuthUtil.getAuth();
Future<Boolean> result = taskExecutor.submit(new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
SecurityContextHolder.getContext().setAuthentication(auth);
cps.forEach(cp -> forceDeleteCp(cp, reason));
return true;
}
});
boolean completed = false;
try {
completed = result.get(30, TimeUnit.SECONDS);
} catch (TimeoutException ex) {
completed = false;
}
return completed;
}
private void forceDeleteCp(CollectionProtocol cp, String reason) {
while (deleteRegistrations(cp));
deleteCp(cp, reason);
}
private boolean deleteCps(List<CollectionProtocol> cps, String reason) {
cps.forEach(cp -> deleteCp(cp, reason));
return true;
}
@PlusTransactional
private boolean deleteCp(CollectionProtocol cp, String reason) {
boolean success = false;
String stackTrace = null;
CollectionProtocol deletedCp = new CollectionProtocol();
try {
//
// refresh cp, as it could have been fetched in another transaction
// if in same transaction, then it will be obtained from session
//
cp = daoFactory.getCollectionProtocolDao().getById(cp.getId());
removeContainerRestrictions(cp);
addOrRemovePiCoordinatorRoles(cp, "DELETE", cp.getPrincipalInvestigator(), null, null, cp.getCoordinators());
removeCpRoles(cp);
BeanUtils.copyProperties(cp, deletedCp);
cp.setOpComments(reason);
cp.delete();
DeleteLogUtil.getInstance().log(cp);
success = true;
} catch (Exception ex) {
stackTrace = ExceptionUtils.getStackTrace(ex);
if (ex instanceof OpenSpecimenException) {
throw ex;
} else {
throw OpenSpecimenException.serverError(ex);
}
} finally {
notifyUsersOnCpDelete(deletedCp, success, stackTrace);
}
return true;
}
@PlusTransactional
private boolean deleteRegistrations(CollectionProtocol cp) {
List<CollectionProtocolRegistration> cprs = daoFactory.getCprDao().getCprsByCpId(cp.getId(), 0, 10);
cprs.forEach(cpr -> cpr.delete(false));
return cprs.size() == 10;
}
private void removeContainerRestrictions(CollectionProtocol cp) {
Set<StorageContainer> containers = cp.getStorageContainers();
for (StorageContainer container : containers) {
container.removeCpRestriction(cp);
}
cp.setStorageContainers(Collections.EMPTY_SET);
}
private void removeCpRoles(CollectionProtocol cp) {
rbacSvc.removeCpRoles(cp.getId());
}
private void notifyUsersOnCpCreate(CollectionProtocol cp) {
notifyUsersOnCpOp(cp, cp.getRepositories(), OP_CP_CREATED);
}
private void notifyUsersOnCpUpdate(CollectionProtocol cp, Collection<Site> addedSites, Collection<Site> removedSites) {
notifyUsersOnCpOp(cp, removedSites, OP_CP_SITE_REMOVED);
notifyUsersOnCpOp(cp, addedSites, OP_CP_SITE_ADDED);
}
private void notifyUsersOnCpDelete(CollectionProtocol cp, boolean success, String stackTrace) {
if (success) {
notifyUsersOnCpOp(cp, cp.getRepositories(), OP_CP_DELETED);
} else {
User currentUser = AuthUtil.getCurrentUser();
String[] rcpts = {currentUser.getEmailAddress(), cp.getPrincipalInvestigator().getEmailAddress()};
String[] subjParams = new String[] {cp.getShortTitle()};
Map<String, Object> props = new HashMap<>();
props.put("cp", cp);
props.put("$subject", subjParams);
props.put("user", currentUser);
props.put("error", stackTrace);
EmailUtil.getInstance().sendEmail(CP_DELETE_FAILED_EMAIL_TMPL, rcpts, null, props);
}
}
private void notifyUsersOnCpOp(CollectionProtocol cp, Collection<Site> sites, int op) {
Map<String, Object> emailProps = new HashMap<>();
emailProps.put("$subject", new Object[] {cp.getShortTitle(), op});
emailProps.put("cp", cp);
emailProps.put("op", op);
emailProps.put("currentUser", AuthUtil.getCurrentUser());
emailProps.put("ccAdmin", false);
if (op == OP_CP_CREATED || op == OP_CP_DELETED) {
List<User> superAdmins = AccessCtrlMgr.getInstance().getSuperAdmins();
notifyUsers(superAdmins, CP_OP_EMAIL_TMPL, emailProps, (op == OP_CP_CREATED) ? "CREATE" : "DELETE");
}
for (Site site : sites) {
String siteName = site.getName();
emailProps.put("siteName", siteName);
emailProps.put("$subject", new Object[] {siteName, op, cp.getShortTitle()});
notifyUsers(site.getCoordinators(), CP_SITE_UPDATED_EMAIL_TMPL, emailProps, "UPDATE");
}
}
private void notifyUsers(Collection<User> users, String template, Map<String, Object> emailProps, String notifOp) {
for (User rcpt : users) {
emailProps.put("rcpt", rcpt);
EmailUtil.getInstance().sendEmail(template, new String[] {rcpt.getEmailAddress()}, null, emailProps);
}
CollectionProtocol cp = (CollectionProtocol)emailProps.get("cp");
Object[] subjParams = (Object[])emailProps.get("$subject");
Notification notif = new Notification();
notif.setEntityType(CollectionProtocol.getEntityName());
notif.setEntityId(cp.getId());
notif.setOperation(notifOp);
notif.setCreatedBy(AuthUtil.getCurrentUser());
notif.setCreationTime(Calendar.getInstance().getTime());
notif.setMessage(MessageUtil.getInstance().getMessage(template + "_subj", subjParams));
NotifUtil.getInstance().notify(notif, Collections.singletonMap("cp-overview", users));
}
private SubjectRoleOpNotif getNotifReq(CollectionProtocol cp, String role, List<User> notifUsers, User user, String cpOp, String roleOp) {
SubjectRoleOpNotif notifReq = new SubjectRoleOpNotif();
notifReq.setAdmins(notifUsers);
notifReq.setAdminNotifMsg("cp_admin_notif_role_" + roleOp.toLowerCase());
notifReq.setAdminNotifParams(new Object[] { user.getFirstName(), user.getLastName(), role, cp.getShortTitle(), user.getInstitute().getName() });
notifReq.setUser(user);
if (cpOp.equals("DELETE")) {
notifReq.setSubjectNotifMsg("cp_delete_user_notif_role");
notifReq.setSubjectNotifParams(new Object[] { cp.getShortTitle(), role });
} else {
notifReq.setSubjectNotifMsg("cp_user_notif_role_" + roleOp.toLowerCase());
notifReq.setSubjectNotifParams(new Object[] { role, cp.getShortTitle(), user.getInstitute().getName() });
}
notifReq.setEndUserOp(cpOp);
return notifReq;
}
private String getMsg(String code) {
return MessageUtil.getInstance().getMessage(code);
}
private String getSopDocDir() {
String defDir = ConfigUtil.getInstance().getDataDir() + File.separator + "cp-sop-documents";
String dir = ConfigUtil.getInstance().getStrSetting(ConfigParams.MODULE, ConfigParams.CP_SOP_DOCS_DIR, defDir);
new File(dir).mkdirs();
return dir + File.separator;
}
private CpReportSettings getReportSetting(CpQueryCriteria crit) {
CpReportSettings settings = null;
if (crit.getId() != null) {
settings = daoFactory.getCpReportSettingsDao().getByCp(crit.getId());
} else if (StringUtils.isNotBlank(crit.getShortTitle())) {
settings = daoFactory.getCpReportSettingsDao().getByCp(crit.getShortTitle());
}
return settings;
}
private ListConfig getSpecimenListConfig(Map<String, Object> listReq) {
ListConfig cfg = getListConfig(listReq, "specimen-list-view", "Specimen");
if (cfg == null) {
return null;
}
Column id = new Column();
id.setExpr("Specimen.id");
id.setCaption("specimenId");
cfg.setPrimaryColumn(id);
Column type = new Column();
type.setExpr("Specimen.type");
type.setCaption("specimenType");
Column specimenClass = new Column();
specimenClass.setExpr("Specimen.class");
specimenClass.setCaption("specimenClass");
List<Column> hiddenColumns = new ArrayList<>();
hiddenColumns.add(id);
hiddenColumns.add(type);
hiddenColumns.add(specimenClass);
cfg.setHiddenColumns(hiddenColumns);
Long cpId = (Long)listReq.get("cpId");
List<SiteCpPair> siteCps = AccessCtrlMgr.getInstance().getReadAccessSpecimenSiteCps(cpId);
if (siteCps == null) {
//
// Admin; hence no additional restrictions
//
return cfg;
}
if (siteCps.isEmpty()) {
throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED);
}
boolean useMrnSites = AccessCtrlMgr.getInstance().isAccessRestrictedBasedOnMrn();
String restrictions = BiospecimenDaoHelper.getInstance().getSiteCpsCondAql(siteCps, useMrnSites);
cfg.setRestriction(restrictions);
cfg.setDistinct(true);
return cfg;
}
private ListConfig getCpListConfig(Map<String, Object> listReq) {
ListConfig cfg = getListConfig(listReq, "cp-list-view", "CollectionProtocol");
if (cfg == null) {
return null;
}
List<Column> hiddenColumns = new ArrayList<>();
Column id = new Column();
id.setExpr("CollectionProtocol.id");
id.setCaption("cpId");
cfg.setPrimaryColumn(id);
hiddenColumns.add(id);
Column catalogId = new Column();
catalogId.setExpr("CollectionProtocol.catalogId");
catalogId.setCaption("catalogId");
hiddenColumns.add(catalogId);
Column starred = new Column();
starred.setExpr("CollectionProtocol.__userLabels.userId");
starred.setCaption("starred");
starred.setDirection(isOracle() ? "asc" : "desc");
hiddenColumns.add(starred);
cfg.setHiddenColumns(hiddenColumns);
List<Column> fixedColumns = new ArrayList<>();
Column participantsCount = new Column();
participantsCount.setCaption("Participants");
participantsCount.setExpr("count(Participant.id)");
fixedColumns.add(participantsCount);
Column specimensCount = new Column();
specimensCount.setCaption("Specimens");
specimensCount.setExpr("count(Specimen.id)");
fixedColumns.add(specimensCount);
cfg.setFixedColumns(fixedColumns);
cfg.setFixedColumnsGenerator(
(rows) -> {
if (rows == null || rows.isEmpty()) {
return rows;
}
Map<Long, Row> cpRows = new HashMap<>();
for (Row row : rows) {
Long cpId = Long.parseLong((String) row.getHidden().get("cpId"));
cpRows.put(cpId, row);
}
List<Object[]> dbRows = sessionFactory.getCurrentSession()
.getNamedQuery(CollectionProtocol.class.getName() + ".getParticipantAndSpecimenCount")
.setParameterList("cpIds", cpRows.keySet())
.list();
for (Object[] dbRow : dbRows) {
int idx = -1;
Long cpId = ((Number) dbRow[++idx]).longValue();
cpRows.get(cpId).setFixedData(new Object[] {dbRow[++idx], dbRow[++idx]});
}
return rows;
}
);
List<Column> orderBy = cfg.getOrderBy();
if (orderBy == null) {
orderBy = new ArrayList<>();
cfg.setOrderBy(orderBy);
}
orderBy.add(0, starred);
cfg.setRestriction(String.format(USR_LABELS_RESTRICTION, AuthUtil.getCurrentUser().getId()));
Set<SiteCpPair> cpSites = AccessCtrlMgr.getInstance().getReadableSiteCps();
if (cpSites == null) {
return cfg;
}
if (cpSites.isEmpty()) {
throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED);
}
String cpSitesRestriction = BiospecimenDaoHelper.getInstance().getSiteCpsCondAqlForCps(cpSites);
if (StringUtils.isNotBlank(cpSitesRestriction)) {
cfg.setRestriction(String.format(AND_COND, cfg.getRestriction(), cpSitesRestriction));
cfg.setDistinct(true);
}
return cfg;
}
private ListConfig getParticipantsListConfig(Map<String, Object> listReq) {
ListConfig cfg = getListConfig(listReq, "participant-list-view", "Participant");
if (cfg == null) {
return null;
}
Column id = new Column();
id.setExpr("Participant.id");
id.setCaption("cprId");
cfg.setPrimaryColumn(id);
cfg.setHiddenColumns(Collections.singletonList(id));
Long cpId = (Long)listReq.get("cpId");
ParticipantReadAccess access = AccessCtrlMgr.getInstance().getParticipantReadAccess(cpId);
if (access.admin) {
return cfg;
}
if (access.siteCps == null || access.siteCps.isEmpty()) {
throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED);
}
boolean useMrnSites = AccessCtrlMgr.getInstance().isAccessRestrictedBasedOnMrn();
cfg.setRestriction(BiospecimenDaoHelper.getInstance().getSiteCpsCondAql(access.siteCps, useMrnSites));
cfg.setDistinct(true);
return cfg;
}
private ListConfig getListConfig(Map<String, Object> listReq, String listName, String drivingForm) {
Long cpId = (Long) listReq.get("cpId");
if (cpId == null) {
cpId = (Long) listReq.get("objectId");
}
Workflow workflow = getWorkFlow(cpId, listName);
if (workflow == null) {
return null;
}
ListConfig listCfg = new ObjectMapper().convertValue(workflow.getData(), ListConfig.class);
listCfg.setCpId(cpId);
listCfg.setDrivingForm(drivingForm);
setListLimit(listReq, listCfg);
Boolean includeCount = (Boolean)listReq.get("includeCount");
listCfg.setIncludeCount(includeCount == null ? false : includeCount);
return listCfg;
}
private Workflow getWorkFlow(Long cpId, String name) {
Workflow workflow = null;
CpWorkflowConfig cfg = null;
if (cpId != null) {
cfg = daoFactory.getCollectionProtocolDao().getCpWorkflows(cpId);
}
if (cfg != null) {
workflow = cfg.getWorkflows().get(name);
}
if (workflow == null) {
workflow = getSysWorkflow(name);
}
return workflow;
}
private Workflow getSysWorkflow(String name) {
return WorkflowUtil.getInstance().getSysWorkflow(name);
}
private void setListLimit(Map<String, Object> listReq, ListConfig cfg) {
Integer startAt = (Integer)listReq.get("startAt");
if (startAt == null) {
startAt = 0;
}
Integer maxResults = (Integer)listReq.get("maxResults");
if (maxResults == null) {
maxResults = 100;
}
cfg.setStartAt(startAt);
cfg.setMaxResults(maxResults);
}
private ConsentStatement getStatement(Long id, String code, String statement) {
ConsentStatement stmt = null;
Object key = null;
if (id != null) {
key = id;
stmt = daoFactory.getConsentStatementDao().getById(id);
} else if (StringUtils.isNotBlank(code)) {
key = code;
stmt = daoFactory.getConsentStatementDao().getByCode(code);
} else if (StringUtils.isNotBlank(statement)) {
key = statement;
stmt = daoFactory.getConsentStatementDao().getByStatement(statement);
}
if (key == null) {
throw OpenSpecimenException.userError(ConsentStatementErrorCode.CODE_REQUIRED);
} else if (stmt == null) {
throw OpenSpecimenException.userError(ConsentStatementErrorCode.NOT_FOUND, key);
}
return stmt;
}
private boolean isOracle() {
String dbType = AppProperties.getInstance().getProperties()
.getProperty("database.type", "mysql")
.toLowerCase();
return dbType.equalsIgnoreCase("oracle");
}
private static final String PPID_MSG = "cp_ppid";
private static final String VISIT_NAME_MSG = "cp_visit_name";
private static final String SPECIMEN_LABEL_MSG = "cp_specimen_label";
private static final String DERIVATIVE_LABEL_MSG = "cp_derivative_label";
private static final String ALIQUOT_LABEL_MSG = "cp_aliquot_label";
private static final String CP_OP_EMAIL_TMPL = "cp_op";
private static final String CP_DELETE_FAILED_EMAIL_TMPL = "cp_delete_failed";
private static final String CP_SITE_UPDATED_EMAIL_TMPL = "cp_site_updated";
private static final int OP_CP_SITE_ADDED = -1;
private static final int OP_CP_SITE_REMOVED = 1;
private static final int OP_CP_CREATED = 0;
private static final int OP_CP_DELETED = 2;
private static final String USR_LABELS_RESTRICTION =
"(CollectionProtocol.__userLabels.userId not exists or CollectionProtocol.__userLabels.userId = %d)";
private static final String AND_COND = "(%s) and (%s)";
}
| Clear the tokens and data entry links from the notif list API response.
| WEB-INF/src/com/krishagni/catissueplus/core/biospecimen/services/impl/CollectionProtocolServiceImpl.java | Clear the tokens and data entry links from the notif list API response. |
|
Java | bsd-3-clause | 8c23facc76c572176935c89dd42cded3f166fec2 | 0 | NCIP/c3pr,NCIP/c3pr,NCIP/c3pr | package edu.duke.cabig.c3pr.web.study.tabs;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.validation.Errors;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;
import edu.duke.cabig.c3pr.domain.CoordinatingCenterStudyStatus;
import edu.duke.cabig.c3pr.domain.Error;
import edu.duke.cabig.c3pr.domain.SiteStudyStatus;
import edu.duke.cabig.c3pr.domain.Study;
import edu.duke.cabig.c3pr.domain.StudySite;
import edu.duke.cabig.c3pr.exception.C3PRBaseException;
import edu.duke.cabig.c3pr.exception.C3PRInvalidDataEntryException;
import edu.duke.cabig.c3pr.service.StudyService;
import edu.duke.cabig.c3pr.tools.Configuration;
import edu.duke.cabig.c3pr.utils.ErrorHelper;
import edu.duke.cabig.c3pr.utils.web.spring.tabbedflow.AjaxableUtils;
import edu.duke.cabig.c3pr.web.study.StudyWrapper;
/**
* Tab for Study Overview/Summary page <p/> Created by IntelliJ IDEA. User: kherm Date: Jun 15, 2007
* Time: 3:38:59 PM To change this template use File | Settings | File Templates.
*/
public class StudyOverviewTab extends StudyTab {
protected StudyService studyService;
protected Configuration configuration;
public void setConfiguration(Configuration configuration) {
this.configuration = configuration;
}
public StudyOverviewTab(String longTitle, String shortTitle, String viewName) {
super(longTitle, shortTitle, viewName);
}
public StudyOverviewTab(String longTitle, String shortTitle, String viewName, Boolean willSave) {
super(longTitle, shortTitle, viewName,willSave);
}
@Override
public void postProcessOnValidation(HttpServletRequest request, StudyWrapper wrapper,
Errors errors) {
Study study = wrapper.getStudy();
if(WebUtils.hasSubmitParameter(request, "statusChange")){
if(request.getParameter("statusChange").equals("readyToOpen")){
study = studyRepository.createStudy(study.getIdentifiers());
}else if(request.getParameter("statusChange").equals("open")){
study = studyRepository.openStudy(study.getIdentifiers());
}else if(request.getParameter("statusChange").equals("close")){
study = studyRepository.closeStudy(study.getIdentifiers());
}
wrapper.setStudy(study);
}
}
public ModelAndView getMessageBroadcastStatus(HttpServletRequest request, Object commandObj,
Errors error) {
Study study = ((StudyWrapper) commandObj).getStudy();
String responseMessage = null;
try {
log.debug("Getting status for study");
responseMessage = studyService.getCCTSWofkflowStatus(study).getDisplayName();
}
catch (Exception e) {
log.error(e);
responseMessage = "error";
}
Map<String, Object> map = new HashMap<String, Object>();
map.put("responseMessage", responseMessage);
return new ModelAndView(AjaxableUtils.getAjaxViewName(request), map);
}
public ModelAndView sendMessageToESB(HttpServletRequest request, Object commandObj, Errors error) {
try {
log.debug("Sending message to CCTS esb");
Study study = ((StudyWrapper) commandObj).getStudy();
studyService.broadcastMessage(study);
return getMessageBroadcastStatus(request, commandObj, error);
}
catch (C3PRBaseException e) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("responseMessage", e.getMessage());
return new ModelAndView(AjaxableUtils.getAjaxViewName(request), map);
}
}
@Override
public Map referenceData(HttpServletRequest request, StudyWrapper command) {
request.setAttribute("isCCTSEnv", isCCTSEnv());
List<Error> dataEntryErrors = new ArrayList<Error>();
command.getStudy().setDataEntryStatus(command.getStudy().evaluateDataEntryStatus(dataEntryErrors));
request.setAttribute("errors", dataEntryErrors);
return super.referenceData(request, command);
}
private String handleInPlaceEditing(HttpServletRequest request, StudyWrapper command,
String property, String value) throws Exception{
if (property.contains("changedSiteStudy")) {
int studySiteIndex = Integer.parseInt(property.split("_")[1]);
if (property.contains("changedSiteStudyStatus")) {
SiteStudyStatus statusObject = SiteStudyStatus.getByCode(value);
if(statusObject==SiteStudyStatus.ACTIVE){
StudySite studySite=studyRepository.activateStudySite(command.getStudy().getIdentifiers(), command.getStudy().getStudySites().get(studySiteIndex).getHealthcareSite().getNciInstituteCode());
}else if(statusObject==SiteStudyStatus.APPROVED_FOR_ACTIVTION){
StudySite studySite=studyRepository.approveStudySiteForActivation(command.getStudy().getIdentifiers(), command.getStudy().getStudySites().get(studySiteIndex).getHealthcareSite().getNciInstituteCode());
}else if(statusObject==SiteStudyStatus.CLOSED_TO_ACCRUAL){
StudySite studySite=studyRepository.closeStudySite(command.getStudy().getIdentifiers(), command.getStudy().getStudySites().get(studySiteIndex).getHealthcareSite().getNciInstituteCode());
}else if(statusObject==SiteStudyStatus.CLOSED_TO_ACCRUAL_AND_TREATMENT){
StudySite studySite=studyRepository.closeStudySiteToAccrualAndTreatment(command.getStudy().getIdentifiers(), command.getStudy().getStudySites().get(studySiteIndex).getHealthcareSite().getNciInstituteCode());
}else if(statusObject==SiteStudyStatus.TEMPORARILY_CLOSED_TO_ACCRUAL){
StudySite studySite=studyRepository.temporarilyCloseStudySite(command.getStudy().getIdentifiers(), command.getStudy().getStudySites().get(studySiteIndex).getHealthcareSite().getNciInstituteCode());
}else if(statusObject==SiteStudyStatus.TEMPORARILY_CLOSED_TO_ACCRUAL_AND_TREATMENT){
StudySite studySite=studyRepository.temporarilyCloseStudySiteToAccrualAndTreatment(command.getStudy().getIdentifiers(), command.getStudy().getStudySites().get(studySiteIndex).getHealthcareSite().getNciInstituteCode());
}
return command.getStudy().getStudySites().get(studySiteIndex).getSiteStudyStatus()
.getCode();
} else if (property.contains("changedSiteStudyStartDate")) {
Date startDate = new SimpleDateFormat("MM/dd/yyyy").parse(value);
command.getStudy().getStudySites().get(studySiteIndex).setStartDate(startDate);
return command.getStudy().getStudySites().get(studySiteIndex).getStartDateStr();
} else if (property.contains("changedSiteStudyIrbApprovalDate")) {
Date irbApprovalDate = new SimpleDateFormat("MM/dd/yyyy").parse(value);
command.getStudy().getStudySites().get(studySiteIndex).setIrbApprovalDate(irbApprovalDate);
return command.getStudy().getStudySites().get(studySiteIndex).getIrbApprovalDateStr();
}
} else if (property.contains("changedCoordinatingCenterStudyStatus")) {
CoordinatingCenterStudyStatus statusObject = CoordinatingCenterStudyStatus
.getByCode(value);
if(statusObject==CoordinatingCenterStudyStatus.OPEN){
Study study=studyRepository.openStudy(command.getStudy().getIdentifiers());
command.setStudy(study);
}else if(statusObject==CoordinatingCenterStudyStatus.CLOSED_TO_ACCRUAL){
Study study=studyRepository.closeStudy(command.getStudy().getIdentifiers());
command.setStudy(study);
}else if(statusObject==CoordinatingCenterStudyStatus.CLOSED_TO_ACCRUAL_AND_TREATMENT){
Study study=studyRepository.closeStudyToAccrualAndTreatment(command.getStudy().getIdentifiers());
command.setStudy(study);
}else if(statusObject==CoordinatingCenterStudyStatus.TEMPORARILY_CLOSED_TO_ACCRUAL){
Study study=studyRepository.temporarilyCloseStudy(command.getStudy().getIdentifiers());
command.setStudy(study);
}else if(statusObject==CoordinatingCenterStudyStatus.TEMPORARILY_CLOSED_TO_ACCRUAL_AND_TREATMENT){
Study study=studyRepository.temporarilyCloseStudyToAccrualAndTreatment(command.getStudy().getIdentifiers());
command.setStudy(study);
}else if(statusObject==CoordinatingCenterStudyStatus.READY_TO_OPEN){
Study study=studyRepository.createStudy(command.getStudy().getIdentifiers());
command.setStudy(study);
}
return command.getStudy().getCoordinatingCenterStudyStatus().getCode();
} else if (property.contains("changedTargetAccrualNumber")) {
command.getStudy().setTargetAccrualNumber(new Integer(value));
return command.getStudy().getTargetAccrualNumber().toString();
} else {
return command.getStudy().getCoordinatingCenterStudyStatus().getCode();
}
return value;
}
@SuppressWarnings("finally")
@Override
protected ModelAndView postProcessInPlaceEditing(HttpServletRequest request, StudyWrapper command,
String property, String value) {
Map<String, String> map = new HashMap<String, String>();
String retValue = "";
try {
retValue=handleInPlaceEditing(request, command, property, value);
}
catch (Exception e) {
retValue = "<script>alert('" + e.getMessage() + "')</script>";
}
map.put(AjaxableUtils.getFreeTextModelName(), retValue);
return new ModelAndView("", map);
}
public ModelAndView adminOverride(HttpServletRequest request, Object commandObj, Errors error) {
StudyWrapper command=(StudyWrapper)commandObj;
String property=request.getParameter("property");
String value=request.getParameter("value");
String retValue="";
Map<String, String> map = new HashMap<String, String>();
if(!isAdmin()){
retValue = "<script>alert('You dont have admin privileges to take this action.')</script>";
map.put(AjaxableUtils.getFreeTextModelName(), retValue);
return new ModelAndView("", map);
}
if(property==null || value==null){
retValue = "<script>alert('no value specified')</script>";
map.put(AjaxableUtils.getFreeTextModelName(), retValue);
return new ModelAndView("", map);
}
if (property.contains("changedSiteStudyStatus")) {
int studySiteIndex = Integer.parseInt(property.split("_")[1]);
SiteStudyStatus statusObject = SiteStudyStatus.getByCode(value);
command.getStudy().getStudySites().get(
studySiteIndex).setSiteStudyStatus(statusObject);
retValue = command.getStudy().getStudySites().get(studySiteIndex).getSiteStudyStatus()
.getCode();
} else if (property.contains("changedCoordinatingCenterStudyStatus")) {
CoordinatingCenterStudyStatus statusObject = CoordinatingCenterStudyStatus
.getByCode(value);
command.getStudy().setCoordinatingCenterStudyStatus(statusObject);
retValue = command.getStudy().getCoordinatingCenterStudyStatus().getCode();
}
map.put(AjaxableUtils.getFreeTextModelName(), retValue);
return new ModelAndView("", map);
}
/* public void validate(StudyWrapper wrapper, Errors errors) {
super.validate(wrapper, errors);
try {
wrapper.getStudy().updateDataEntryStatus();
studyRepository.openStudy(wrapper.getStudy().getIdentifiers());
}
catch (Exception e) {
errors.rejectValue("study.coordinatingCenterStudyStatus", "dummyCode", e.getMessage());
}
}
*/
protected boolean suppressValidation(HttpServletRequest request, Object study) {
if (request.getParameter("_activate") != null
&& request.getParameter("_activate").equals("true")) {
return false;
}
return true;
}
private boolean isCCTSEnv() {
return this.configuration.get(Configuration.ESB_ENABLE).equalsIgnoreCase("true");
}
public StudyService getStudyService() {
return studyService;
}
public void setStudyService(StudyService studyService) {
this.studyService = studyService;
}
public ModelAndView reloadCompanion(HttpServletRequest request, Object command , Errors error) {
return new ModelAndView(AjaxableUtils.getAjaxViewName(request));
}
}
| codebase/projects/web/src/java/edu/duke/cabig/c3pr/web/study/tabs/StudyOverviewTab.java | package edu.duke.cabig.c3pr.web.study.tabs;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.validation.Errors;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;
import edu.duke.cabig.c3pr.domain.CoordinatingCenterStudyStatus;
import edu.duke.cabig.c3pr.domain.SiteStudyStatus;
import edu.duke.cabig.c3pr.domain.Study;
import edu.duke.cabig.c3pr.domain.StudySite;
import edu.duke.cabig.c3pr.exception.C3PRBaseException;
import edu.duke.cabig.c3pr.exception.C3PRCodedException;
import edu.duke.cabig.c3pr.exception.C3PRCodedRuntimeException;
import edu.duke.cabig.c3pr.service.StudyService;
import edu.duke.cabig.c3pr.tools.Configuration;
import edu.duke.cabig.c3pr.utils.StudyStatusHelper;
import edu.duke.cabig.c3pr.utils.web.spring.tabbedflow.AjaxableUtils;
import edu.duke.cabig.c3pr.web.study.StudyWrapper;
/**
* Tab for Study Overview/Summary page <p/> Created by IntelliJ IDEA. User: kherm Date: Jun 15, 2007
* Time: 3:38:59 PM To change this template use File | Settings | File Templates.
*/
public class StudyOverviewTab extends StudyTab {
protected StudyService studyService;
protected Configuration configuration;
public void setConfiguration(Configuration configuration) {
this.configuration = configuration;
}
public StudyOverviewTab(String longTitle, String shortTitle, String viewName) {
super(longTitle, shortTitle, viewName);
}
public StudyOverviewTab(String longTitle, String shortTitle, String viewName, Boolean willSave) {
super(longTitle, shortTitle, viewName,willSave);
}
@Override
public void postProcessOnValidation(HttpServletRequest request, StudyWrapper wrapper,
Errors errors) {
Study study = wrapper.getStudy();
if(WebUtils.hasSubmitParameter(request, "statusChange")){
if(request.getParameter("statusChange").equals("readyToOpen")){
study = studyRepository.createStudy(study.getIdentifiers());
}else if(request.getParameter("statusChange").equals("open")){
study = studyRepository.openStudy(study.getIdentifiers());
}else if(request.getParameter("statusChange").equals("close")){
study = studyRepository.closeStudy(study.getIdentifiers());
}
wrapper.setStudy(study);
}
}
public ModelAndView getMessageBroadcastStatus(HttpServletRequest request, Object commandObj,
Errors error) {
Study study = ((StudyWrapper) commandObj).getStudy();
String responseMessage = null;
try {
log.debug("Getting status for study");
responseMessage = studyService.getCCTSWofkflowStatus(study).getDisplayName();
}
catch (Exception e) {
log.error(e);
responseMessage = "error";
}
Map<String, Object> map = new HashMap<String, Object>();
map.put("responseMessage", responseMessage);
return new ModelAndView(AjaxableUtils.getAjaxViewName(request), map);
}
public ModelAndView sendMessageToESB(HttpServletRequest request, Object commandObj, Errors error) {
try {
log.debug("Sending message to CCTS esb");
Study study = ((StudyWrapper) commandObj).getStudy();
studyService.broadcastMessage(study);
return getMessageBroadcastStatus(request, commandObj, error);
}
catch (C3PRBaseException e) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("responseMessage", e.getMessage());
return new ModelAndView(AjaxableUtils.getAjaxViewName(request), map);
}
}
@Override
public Map referenceData(HttpServletRequest request, StudyWrapper command) {
request.setAttribute("isCCTSEnv", isCCTSEnv());
try {
command.getStudy().setDataEntryStatus(command.getStudy().evaluateDataEntryStatus());
} catch (Exception e) {
log.error(e.getMessage());
}
return super.referenceData(request, command);
}
private String handleInPlaceEditing(HttpServletRequest request, StudyWrapper command,
String property, String value) throws Exception{
if (property.contains("changedSiteStudy")) {
int studySiteIndex = Integer.parseInt(property.split("_")[1]);
if (property.contains("changedSiteStudyStatus")) {
SiteStudyStatus statusObject = SiteStudyStatus.getByCode(value);
if(statusObject==SiteStudyStatus.ACTIVE){
StudySite studySite=studyRepository.activateStudySite(command.getStudy().getIdentifiers(), command.getStudy().getStudySites().get(studySiteIndex).getHealthcareSite().getNciInstituteCode());
}else if(statusObject==SiteStudyStatus.APPROVED_FOR_ACTIVTION){
StudySite studySite=studyRepository.approveStudySiteForActivation(command.getStudy().getIdentifiers(), command.getStudy().getStudySites().get(studySiteIndex).getHealthcareSite().getNciInstituteCode());
}else if(statusObject==SiteStudyStatus.CLOSED_TO_ACCRUAL){
StudySite studySite=studyRepository.closeStudySite(command.getStudy().getIdentifiers(), command.getStudy().getStudySites().get(studySiteIndex).getHealthcareSite().getNciInstituteCode());
}else if(statusObject==SiteStudyStatus.CLOSED_TO_ACCRUAL_AND_TREATMENT){
StudySite studySite=studyRepository.closeStudySiteToAccrualAndTreatment(command.getStudy().getIdentifiers(), command.getStudy().getStudySites().get(studySiteIndex).getHealthcareSite().getNciInstituteCode());
}else if(statusObject==SiteStudyStatus.TEMPORARILY_CLOSED_TO_ACCRUAL){
StudySite studySite=studyRepository.temporarilyCloseStudySite(command.getStudy().getIdentifiers(), command.getStudy().getStudySites().get(studySiteIndex).getHealthcareSite().getNciInstituteCode());
}else if(statusObject==SiteStudyStatus.TEMPORARILY_CLOSED_TO_ACCRUAL_AND_TREATMENT){
StudySite studySite=studyRepository.temporarilyCloseStudySiteToAccrualAndTreatment(command.getStudy().getIdentifiers(), command.getStudy().getStudySites().get(studySiteIndex).getHealthcareSite().getNciInstituteCode());
}
return command.getStudy().getStudySites().get(studySiteIndex).getSiteStudyStatus()
.getCode();
} else if (property.contains("changedSiteStudyStartDate")) {
Date startDate = new SimpleDateFormat("MM/dd/yyyy").parse(value);
command.getStudy().getStudySites().get(studySiteIndex).setStartDate(startDate);
return command.getStudy().getStudySites().get(studySiteIndex).getStartDateStr();
} else if (property.contains("changedSiteStudyIrbApprovalDate")) {
Date irbApprovalDate = new SimpleDateFormat("MM/dd/yyyy").parse(value);
command.getStudy().getStudySites().get(studySiteIndex).setIrbApprovalDate(irbApprovalDate);
return command.getStudy().getStudySites().get(studySiteIndex).getIrbApprovalDateStr();
}
} else if (property.contains("changedCoordinatingCenterStudyStatus")) {
CoordinatingCenterStudyStatus statusObject = CoordinatingCenterStudyStatus
.getByCode(value);
if(statusObject==CoordinatingCenterStudyStatus.OPEN){
Study study=studyRepository.openStudy(command.getStudy().getIdentifiers());
command.setStudy(study);
}else if(statusObject==CoordinatingCenterStudyStatus.CLOSED_TO_ACCRUAL){
Study study=studyRepository.closeStudy(command.getStudy().getIdentifiers());
command.setStudy(study);
}else if(statusObject==CoordinatingCenterStudyStatus.CLOSED_TO_ACCRUAL_AND_TREATMENT){
Study study=studyRepository.closeStudyToAccrualAndTreatment(command.getStudy().getIdentifiers());
command.setStudy(study);
}else if(statusObject==CoordinatingCenterStudyStatus.TEMPORARILY_CLOSED_TO_ACCRUAL){
Study study=studyRepository.temporarilyCloseStudy(command.getStudy().getIdentifiers());
command.setStudy(study);
}else if(statusObject==CoordinatingCenterStudyStatus.TEMPORARILY_CLOSED_TO_ACCRUAL_AND_TREATMENT){
Study study=studyRepository.temporarilyCloseStudyToAccrualAndTreatment(command.getStudy().getIdentifiers());
command.setStudy(study);
}else if(statusObject==CoordinatingCenterStudyStatus.READY_TO_OPEN){
Study study=studyRepository.createStudy(command.getStudy().getIdentifiers());
command.setStudy(study);
}
return command.getStudy().getCoordinatingCenterStudyStatus().getCode();
} else if (property.contains("changedTargetAccrualNumber")) {
command.getStudy().setTargetAccrualNumber(new Integer(value));
return command.getStudy().getTargetAccrualNumber().toString();
} else {
return command.getStudy().getCoordinatingCenterStudyStatus().getCode();
}
return value;
}
@SuppressWarnings("finally")
@Override
protected ModelAndView postProcessInPlaceEditing(HttpServletRequest request, StudyWrapper command,
String property, String value) {
Map<String, String> map = new HashMap<String, String>();
String retValue = "";
try {
retValue=handleInPlaceEditing(request, command, property, value);
}
catch (Exception e) {
retValue = "<script>alert('" + e.getMessage() + "')</script>";
}
map.put(AjaxableUtils.getFreeTextModelName(), retValue);
return new ModelAndView("", map);
}
public ModelAndView adminOverride(HttpServletRequest request, Object commandObj, Errors error) {
StudyWrapper command=(StudyWrapper)commandObj;
String property=request.getParameter("property");
String value=request.getParameter("value");
String retValue="";
Map<String, String> map = new HashMap<String, String>();
if(!isAdmin()){
retValue = "<script>alert('You dont have admin privileges to take this action.')</script>";
map.put(AjaxableUtils.getFreeTextModelName(), retValue);
return new ModelAndView("", map);
}
if(property==null || value==null){
retValue = "<script>alert('no value specified')</script>";
map.put(AjaxableUtils.getFreeTextModelName(), retValue);
return new ModelAndView("", map);
}
if (property.contains("changedSiteStudyStatus")) {
int studySiteIndex = Integer.parseInt(property.split("_")[1]);
SiteStudyStatus statusObject = SiteStudyStatus.getByCode(value);
command.getStudy().getStudySites().get(
studySiteIndex).setSiteStudyStatus(statusObject);
retValue = command.getStudy().getStudySites().get(studySiteIndex).getSiteStudyStatus()
.getCode();
} else if (property.contains("changedCoordinatingCenterStudyStatus")) {
CoordinatingCenterStudyStatus statusObject = CoordinatingCenterStudyStatus
.getByCode(value);
command.getStudy().setCoordinatingCenterStudyStatus(statusObject);
retValue = command.getStudy().getCoordinatingCenterStudyStatus().getCode();
}
map.put(AjaxableUtils.getFreeTextModelName(), retValue);
return new ModelAndView("", map);
}
/* public void validate(StudyWrapper wrapper, Errors errors) {
super.validate(wrapper, errors);
try {
wrapper.getStudy().updateDataEntryStatus();
studyRepository.openStudy(wrapper.getStudy().getIdentifiers());
}
catch (Exception e) {
errors.rejectValue("study.coordinatingCenterStudyStatus", "dummyCode", e.getMessage());
}
}
*/
protected boolean suppressValidation(HttpServletRequest request, Object study) {
if (request.getParameter("_activate") != null
&& request.getParameter("_activate").equals("true")) {
return false;
}
return true;
}
private boolean isCCTSEnv() {
return this.configuration.get(Configuration.ESB_ENABLE).equalsIgnoreCase("true");
}
public StudyService getStudyService() {
return studyService;
}
public void setStudyService(StudyService studyService) {
this.studyService = studyService;
}
public ModelAndView reloadCompanion(HttpServletRequest request, Object command , Errors error) {
return new ModelAndView(AjaxableUtils.getAjaxViewName(request));
}
}
| study status change: putting errors in refdata
| codebase/projects/web/src/java/edu/duke/cabig/c3pr/web/study/tabs/StudyOverviewTab.java | study status change: putting errors in refdata |
|
Java | bsd-3-clause | 4197f82aaa029bf326aba7c9d14b20642af7e631 | 0 | doubleyoung/kryo,magro/kryo,kidaa/kryo,hepin1989/kryo,hierynomus/kryo,magro/kryo,doubleyoung/kryo,kidaa/kryo,irudyak/kryo,EsotericSoftware/kryo,mikee805/kryo,hierynomus/kryo,tomdkt/kryo,tomdkt/kryo,mikee805/kryo,childRon/kryo,narahari92/kryo,xfrendx/kryo,EsotericSoftware/kryo,hepin1989/kryo,EsotericSoftware/kryo,xfrendx/kryo,narahari92/kryo,romix/kryo,irudyak/kryo,EsotericSoftware/kryo,childRon/kryo |
package com.esotericsoftware.kryo.serialize;
import java.nio.ByteBuffer;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.KryoTestCase;
import com.esotericsoftware.kryo.NotNull;
import com.esotericsoftware.kryo.SerializationException;
public class FieldSerializerTest extends KryoTestCase {
public void testFieldSerializer () {
Kryo kryo = new Kryo();
kryo.register(TestClass.class);
kryo.register(HasStringField.class);
HasStringField hasStringField = new HasStringField();
hasStringField.text = "moo";
roundTrip(kryo, 6, hasStringField);
roundTrip(new FieldSerializer(kryo, HasStringField.class), 6, hasStringField);
TestClass test = new TestClass();
test.optional = 12;
test.nullField = "value";
test.text = "123";
test.child = new TestClass();
roundTrip(kryo, 39, test);
test.nullField = null;
roundTrip(kryo, 33, test);
FieldSerializer serializer = (FieldSerializer)kryo.getSerializer(TestClass.class);
serializer.removeField("optional");
roundTrip(kryo, 31, test);
}
public void testNonNull () {
Kryo kryo = new Kryo();
kryo.register(HasNonNull.class);
HasNonNull nonNullValue = new HasNonNull();
nonNullValue.nonNullText = "moo";
roundTrip(kryo, 5, nonNullValue);
}
public void testRegistrationOrder () {
A a = new A();
a.value = 100;
a.b = new B();
a.b.value = 200;
a.b.a = new A();
a.b.a.value = 300;
Kryo kryo = new Kryo();
kryo.register(A.class);
kryo.register(B.class);
roundTrip(kryo, 9, a);
kryo = new Kryo();
kryo.register(B.class);
kryo.register(A.class);
roundTrip(kryo, 9, a);
}
public void testNoDefaultConstructor () {
SimpleNoDefaultConstructor object1 = new SimpleNoDefaultConstructor(2);
roundTrip(new SimpleSerializer<SimpleNoDefaultConstructor>() {
public SimpleNoDefaultConstructor read (ByteBuffer buffer) {
return new SimpleNoDefaultConstructor(IntSerializer.get(buffer, true));
}
public void write (ByteBuffer buffer, SimpleNoDefaultConstructor object) {
IntSerializer.put(buffer, object.constructorValue, true);
}
}, 2, object1);
Kryo kryo = new Kryo();
FieldSerializer complexSerializer = new FieldSerializer(kryo, ComplexNoDefaultConstructor.class) {
public ComplexNoDefaultConstructor readObjectData (ByteBuffer buffer, Class type) {
String name = StringSerializer.get(buffer);
ComplexNoDefaultConstructor object = new ComplexNoDefaultConstructor(name);
readObjectData(object, buffer, type);
return object;
}
public void writeObjectData (ByteBuffer buffer, Object object) {
ComplexNoDefaultConstructor complexObject = (ComplexNoDefaultConstructor)object;
StringSerializer.put(buffer, complexObject.name);
super.writeObjectData(buffer, complexObject);
}
};
ComplexNoDefaultConstructor object2 = new ComplexNoDefaultConstructor("has no zero arg constructor!");
object2.anotherField1 = 1234;
object2.anotherField2 = "abcd";
roundTrip(complexSerializer, 38, object2);
}
public void testSerializationExceptionTraceInfo () {
C c = new C();
c.a = new A();
c.a.value = 123;
c.a.b = new B();
c.a.b.value = 456;
c.d = new D();
c.d.e = new E();
c.d.e.f = new F();
Kryo kryoWithoutF = new Kryo();
kryoWithoutF.register(A.class);
kryoWithoutF.register(B.class);
kryoWithoutF.register(C.class);
kryoWithoutF.register(D.class);
kryoWithoutF.register(E.class);
buffer.clear();
try {
kryoWithoutF.writeClassAndObject(buffer, c);
fail("Should have failed because F is not registered.");
} catch (SerializationException ignored) {
}
Kryo kryo = new Kryo();
kryo.register(A.class);
kryo.register(B.class);
kryo.register(C.class);
kryo.register(D.class);
kryo.register(E.class);
kryo.register(F.class);
buffer.clear();
kryo.writeClassAndObject(buffer, c);
buffer.flip();
assertEquals(11, buffer.limit());
try {
kryoWithoutF.readClassAndObject(buffer);
fail("Should have failed because F is not registered.");
} catch (SerializationException ignored) {
}
}
static public class HasStringField {
public String text = "something";
public boolean equals (Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
HasStringField other = (HasStringField)obj;
if (text == null) {
if (other.text != null) return false;
} else if (!text.equals(other.text)) return false;
return true;
}
}
static public class HasNonNull {
@NotNull
public String nonNullText;
public boolean equals (Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
HasNonNull other = (HasNonNull)obj;
if (nonNullText == null) {
if (other.nonNullText != null) return false;
} else if (!nonNullText.equals(other.nonNullText)) return false;
return true;
}
}
static public class TestClass {
public String text = "something";
public String nullField;
TestClass child;
TestClass child2;
private float abc = 1.2f;
public int optional;
public boolean equals (Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
TestClass other = (TestClass)obj;
if (Float.floatToIntBits(abc) != Float.floatToIntBits(other.abc)) return false;
if (child == null) {
if (other.child != null) return false;
} else if (child != this && !child.equals(other.child)) return false;
if (child2 == null) {
if (other.child2 != null) return false;
} else if (child2 != this && !child2.equals(other.child2)) return false;
if (nullField == null) {
if (other.nullField != null) return false;
} else if (!nullField.equals(other.nullField)) return false;
if (text == null) {
if (other.text != null) return false;
} else if (!text.equals(other.text)) return false;
return true;
}
}
static public final class A {
public int value;
public B b;
public boolean equals (Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
A other = (A)obj;
if (b == null) {
if (other.b != null) return false;
} else if (!b.equals(other.b)) return false;
if (value != other.value) return false;
return true;
}
}
static public final class B {
public int value;
public A a;
public boolean equals (Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
B other = (B)obj;
if (a == null) {
if (other.a != null) return false;
} else if (!a.equals(other.a)) return false;
if (value != other.value) return false;
return true;
}
}
static public final class C {
public A a;
public D d;
}
static public final class D {
public E e;
}
static public final class E {
public F f;
}
static public final class F {
public int value;
}
static public class SimpleNoDefaultConstructor {
int constructorValue;
public SimpleNoDefaultConstructor (int constructorValue) {
this.constructorValue = constructorValue;
}
public int getConstructorValue () {
return constructorValue;
}
public int hashCode () {
final int prime = 31;
int result = 1;
result = prime * result + constructorValue;
return result;
}
public boolean equals (Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
SimpleNoDefaultConstructor other = (SimpleNoDefaultConstructor)obj;
if (constructorValue != other.constructorValue) return false;
return true;
}
}
static public class ComplexNoDefaultConstructor {
public transient String name;
public int anotherField1;
public String anotherField2;
public ComplexNoDefaultConstructor (String name) {
this.name = name;
}
public int hashCode () {
final int prime = 31;
int result = 1;
result = prime * result + anotherField1;
result = prime * result + ((anotherField2 == null) ? 0 : anotherField2.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
public boolean equals (Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
ComplexNoDefaultConstructor other = (ComplexNoDefaultConstructor)obj;
if (anotherField1 != other.anotherField1) return false;
if (anotherField2 == null) {
if (other.anotherField2 != null) return false;
} else if (!anotherField2.equals(other.anotherField2)) return false;
if (name == null) {
if (other.name != null) return false;
} else if (!name.equals(other.name)) return false;
return true;
}
}
}
| test/com/esotericsoftware/kryo/serialize/FieldSerializerTest.java |
package com.esotericsoftware.kryo.serialize;
import java.nio.ByteBuffer;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.KryoTestCase;
import com.esotericsoftware.kryo.NotNull;
import com.esotericsoftware.kryo.SerializationException;
public class FieldSerializerTest extends KryoTestCase {
public void testFieldSerializer () {
Kryo kryo = new Kryo();
kryo.register(TestClass.class);
kryo.register(HasStringField.class);
HasStringField hasStringField = new HasStringField();
hasStringField.text = "moo";
roundTrip(kryo, 6, hasStringField);
roundTrip(new FieldSerializer(kryo, HasStringField.class), 6, hasStringField);
TestClass test = new TestClass();
test.optional = 12;
test.nullField = "value";
test.text = "123";
test.child = new TestClass();
roundTrip(kryo, 39, test);
test.nullField = null;
roundTrip(kryo, 33, test);
FieldSerializer serializer = (FieldSerializer)kryo.getSerializer(TestClass.class);
serializer.removeField("optional");
roundTrip(kryo, 31, test);
}
public void testNonNull () {
Kryo kryo = new Kryo();
kryo.register(HasNonNull.class);
HasNonNull nonNullValue = new HasNonNull();
nonNullValue.nonNullText = "moo";
roundTrip(kryo, 5, nonNullValue);
}
public void testRegistrationOrder () {
A a = new A();
a.value = 100;
a.b = new B();
a.b.value = 200;
a.b.a = new A();
a.b.a.value = 300;
Kryo kryo = new Kryo();
kryo.register(A.class);
kryo.register(B.class);
roundTrip(kryo, 9, a);
kryo = new Kryo();
kryo.register(B.class);
kryo.register(A.class);
roundTrip(kryo, 9, a);
}
public void testNoDefaultConstructor () {
SimpleNoDefaultConstructor object1 = new SimpleNoDefaultConstructor(2);
roundTrip(new SimpleSerializer<SimpleNoDefaultConstructor>() {
public SimpleNoDefaultConstructor read (ByteBuffer buffer) {
return new SimpleNoDefaultConstructor(IntSerializer.get(buffer, true));
}
public void write (ByteBuffer buffer, SimpleNoDefaultConstructor object) {
IntSerializer.put(buffer, object.constructorValue, true);
}
}, 2, object1);
Kryo kryo = new Kryo();
FieldSerializer complexSerializer = new FieldSerializer(kryo, ComplexNoDefaultConstructor.class) {
public ComplexNoDefaultConstructor readObjectData (ByteBuffer buffer, Class type) {
String name = StringSerializer.get(buffer);
ComplexNoDefaultConstructor object = new ComplexNoDefaultConstructor(name);
readObjectData(object, buffer, type);
return object;
}
public void writeObjectData (ByteBuffer buffer, Object object) {
ComplexNoDefaultConstructor complexObject = (ComplexNoDefaultConstructor)object;
StringSerializer.put(buffer, complexObject.name);
super.writeObjectData(buffer, complexObject);
}
};
ComplexNoDefaultConstructor object2 = new ComplexNoDefaultConstructor("has no zero arg constructor!");
object2.anotherField1 = 1234;
object2.anotherField2 = "abcd";
roundTrip(complexSerializer, 38, object2);
}
public void testSerializationExceptionTraceInfo () {
C c = new C();
c.a = new A();
c.a.value = 123;
c.a.b = new B();
c.a.b.value = 456;
c.d = new D();
c.d.e = new E();
c.d.e.f = new F();
Kryo kryoWithoutF = new Kryo();
kryoWithoutF.register(A.class);
kryoWithoutF.register(B.class);
kryoWithoutF.register(C.class);
kryoWithoutF.register(D.class);
kryoWithoutF.register(E.class);
buffer.clear();
try {
// Fail because F is not registered.
kryoWithoutF.writeClassAndObject(buffer, c);
} catch (SerializationException ex) {
ex.printStackTrace();
}
Kryo kryo = new Kryo();
kryo.register(A.class);
kryo.register(B.class);
kryo.register(C.class);
kryo.register(D.class);
kryo.register(E.class);
kryo.register(F.class);
buffer.clear();
kryo.writeClassAndObject(buffer, c);
buffer.flip();
assertEquals(11, buffer.limit());
try {
// Fail because F is not registered.
kryoWithoutF.readClassAndObject(buffer);
} catch (SerializationException ex) {
ex.printStackTrace();
}
}
static public class HasStringField {
public String text = "something";
public boolean equals (Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
HasStringField other = (HasStringField)obj;
if (text == null) {
if (other.text != null) return false;
} else if (!text.equals(other.text)) return false;
return true;
}
}
static public class HasNonNull {
@NotNull
public String nonNullText;
public boolean equals (Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
HasNonNull other = (HasNonNull)obj;
if (nonNullText == null) {
if (other.nonNullText != null) return false;
} else if (!nonNullText.equals(other.nonNullText)) return false;
return true;
}
}
static public class TestClass {
public String text = "something";
public String nullField;
TestClass child;
TestClass child2;
private float abc = 1.2f;
public int optional;
public boolean equals (Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
TestClass other = (TestClass)obj;
if (Float.floatToIntBits(abc) != Float.floatToIntBits(other.abc)) return false;
if (child == null) {
if (other.child != null) return false;
} else if (child != this && !child.equals(other.child)) return false;
if (child2 == null) {
if (other.child2 != null) return false;
} else if (child2 != this && !child2.equals(other.child2)) return false;
if (nullField == null) {
if (other.nullField != null) return false;
} else if (!nullField.equals(other.nullField)) return false;
if (text == null) {
if (other.text != null) return false;
} else if (!text.equals(other.text)) return false;
return true;
}
}
static public final class A {
public int value;
public B b;
public boolean equals (Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
A other = (A)obj;
if (b == null) {
if (other.b != null) return false;
} else if (!b.equals(other.b)) return false;
if (value != other.value) return false;
return true;
}
}
static public final class B {
public int value;
public A a;
public boolean equals (Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
B other = (B)obj;
if (a == null) {
if (other.a != null) return false;
} else if (!a.equals(other.a)) return false;
if (value != other.value) return false;
return true;
}
}
static public final class C {
public A a;
public D d;
}
static public final class D {
public E e;
}
static public final class E {
public F f;
}
static public final class F {
public int value;
}
static public class SimpleNoDefaultConstructor {
int constructorValue;
public SimpleNoDefaultConstructor (int constructorValue) {
this.constructorValue = constructorValue;
}
public int getConstructorValue () {
return constructorValue;
}
public int hashCode () {
final int prime = 31;
int result = 1;
result = prime * result + constructorValue;
return result;
}
public boolean equals (Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
SimpleNoDefaultConstructor other = (SimpleNoDefaultConstructor)obj;
if (constructorValue != other.constructorValue) return false;
return true;
}
}
static public class ComplexNoDefaultConstructor {
public transient String name;
public int anotherField1;
public String anotherField2;
public ComplexNoDefaultConstructor (String name) {
this.name = name;
}
public int hashCode () {
final int prime = 31;
int result = 1;
result = prime * result + anotherField1;
result = prime * result + ((anotherField2 == null) ? 0 : anotherField2.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
public boolean equals (Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
ComplexNoDefaultConstructor other = (ComplexNoDefaultConstructor)obj;
if (anotherField1 != other.anotherField1) return false;
if (anotherField2 == null) {
if (other.anotherField2 != null) return false;
} else if (!anotherField2.equals(other.anotherField2)) return false;
if (name == null) {
if (other.name != null) return false;
} else if (!name.equals(other.name)) return false;
return true;
}
}
}
| Got rid of exception when test is passing.
| test/com/esotericsoftware/kryo/serialize/FieldSerializerTest.java | Got rid of exception when test is passing. |
|
Java | mit | e629c84652f38c283d6ae2f7b8500974cd05cdd3 | 0 | openforis/collect,openforis/collect,openforis/collect,openforis/collect | package org.openforis.collect.io.metadata.collectearth;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import org.apache.commons.lang3.StringEscapeUtils;
import org.openforis.collect.earth.core.rdb.RelationalSchemaContext;
import org.openforis.collect.model.CollectSurvey;
import org.openforis.collect.relational.model.RelationalSchemaConfig;
import org.openforis.idm.metamodel.AttributeDefinition;
import org.openforis.idm.metamodel.CodeAttributeDefinition;
import org.openforis.idm.metamodel.CodeList;
import org.openforis.idm.metamodel.CodeListLevel;
import org.openforis.idm.metamodel.CoordinateAttributeDefinition;
import org.openforis.idm.metamodel.DateAttributeDefinition;
import org.openforis.idm.metamodel.EntityDefinition;
import org.openforis.idm.metamodel.KeyAttributeDefinition;
import org.openforis.idm.metamodel.NodeDefinition;
import org.openforis.idm.metamodel.NodeLabel;
import org.openforis.idm.metamodel.NumberAttributeDefinition;
import org.openforis.idm.metamodel.NumericAttributeDefinition;
import org.openforis.idm.metamodel.NumericAttributeDefinition.Type;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
/**
*
* @author S. Ricci
* @author A. Sanchez-Paus Diaz
*
*/
public class MondrianCubeGenerator {
private static final String SAIKU_SCHEMA_PLACEHOLDER = "${saikuDbSchema}";
private static final String[] MEASURE_AGGREGATORS = new String[] {"min", "max", "avg"};
private CollectSurvey survey;
private RelationalSchemaConfig rdbConfig;
private String language;
public MondrianCubeGenerator(CollectSurvey survey, String language) {
this.survey = survey;
this.language = language;
this.rdbConfig = new RelationalSchemaContext().getRdbConfig();
}
public Schema generateSchema() {
Schema schema = new Schema(survey.getName());
Cube cube = generateCube();
schema.cube = cube;
return schema;
}
public String generateXMLSchema() {
org.openforis.collect.io.metadata.collectearth.MondrianCubeGenerator.Schema mondrianSchema = generateSchema();
XStream xStream = new XStream();
xStream.processAnnotations(MondrianCubeGenerator.Schema.class);
String xmlSchema = xStream.toXML(mondrianSchema);
return xmlSchema;
}
private Cube generateCube() {
Cube cube = new Cube("Collect Earth Plot");
EntityDefinition rootEntityDef = survey.getSchema().getRootEntityDefinitions().get(0);
Table table = new Table(rootEntityDef.getName());
cube.table = table;
List<NodeDefinition> children = rootEntityDef.getChildDefinitions();
for (NodeDefinition nodeDef : children) {
String nodeName = nodeDef.getName();
if (nodeDef instanceof AttributeDefinition) {
Dimension dimension = generateDimension(nodeDef, rootEntityDef );
if (nodeDef instanceof KeyAttributeDefinition && ((KeyAttributeDefinition) nodeDef).isKey()) {
Measure measure = new Measure(rootEntityDef.getName() + "_count");
measure.column = "_" + rootEntityDef.getName() + "_" + nodeName;
measure.caption = StringEscapeUtils.escapeHtml4( extractLabel(rootEntityDef) + " Count" );
measure.aggregator = "distinct count";
measure.datatype = "Integer";
cube.measures.add(measure);
} else if (nodeDef instanceof NumberAttributeDefinition) {
for (String aggregator : MEASURE_AGGREGATORS) {
Measure measure = new Measure(nodeName + "_" + aggregator);
measure.column = nodeName;
measure.caption = StringEscapeUtils.escapeHtml4( extractLabel(nodeDef) + " " + aggregator );
measure.aggregator = aggregator;
measure.datatype = "Numeric";
measure.formatString = "#.##";
cube.measures.add(measure);
}
}
cube.dimensions.add(dimension);
} else {
String rootEntityIdColumnName = getRootEntityIdColumnName(rootEntityDef);
String entityName = nodeName;
String entityLabel = extractLabel(nodeDef);
for (NodeDefinition childDef : ((EntityDefinition) nodeDef).getChildDefinitions()) {
String childLabel = entityLabel + " - " + extractLabel(childDef);
Dimension dimension = new Dimension(childLabel);
Hierarchy hierarchy = new Hierarchy(childLabel);
if( nodeDef.isMultiple() ){
dimension.foreignKey = rootEntityIdColumnName;
hierarchy.primaryKey = rootEntityIdColumnName;
hierarchy.primaryKeyTable = entityName;
if (childDef instanceof CodeAttributeDefinition) {
Join join = new Join(null);
String codeListName = ((CodeAttributeDefinition) childDef).getList().getName();
join.leftKey = childDef.getName() + rdbConfig.getCodeListTableSuffix() + rdbConfig.getIdColumnSuffix();
join.rightKey = codeListName + rdbConfig.getCodeListTableSuffix() + rdbConfig.getIdColumnSuffix();
join.tables = Arrays.asList(
new Table(entityName),
new Table(codeListName + rdbConfig.getCodeListTableSuffix())
);
hierarchy.join = join;
}else{
hierarchy.table = new Table(entityName);
}
hierarchy.levels.add(generateLevel(childDef));
dimension.hierarchy = hierarchy;
}else{
dimension = generateDimension(childDef, rootEntityDef);
}
cube.dimensions.add(dimension);
}
}
}
//add predefined dimensions
// DEPRECATED 07/08/2015 : From now on all the operations to calculate the aspect,elevation,slope and initial land use class are made through Calculated Members
// cube.dimensions.addAll(generatePredefinedDimensions());
//add predefined measures
// Add the measures AFTER the 1st measure, which shouyld be Plot Count
cube.measures.addAll(1, generatePredefinedMeasures());
return cube;
}
public String getRootEntityIdColumnName(EntityDefinition rootEntityDef) {
return rdbConfig.getIdColumnPrefix() + rootEntityDef.getName() + rdbConfig.getIdColumnSuffix();
}
private List<Measure> generatePredefinedMeasures() {
List<Measure> measures = new ArrayList<Measure>();
//Expansion factor - Area
{
Measure measure = new Measure("area");
measure.column = "expansion_factor";
measure.caption = "Area (HA)";
measure.aggregator = "sum";
measure.datatype = "Integer";
measure.formatString = "###,###";
measures.add(measure);
}
// Plot weight
{
Measure measure = new Measure("plot_weight");
measure.column = "plot_weight";
measure.caption = "Plot Weight";
measure.aggregator = "sum";
measure.datatype = "Integer";
measure.formatString = "#,###";
measures.add(measure);
}
return measures;
}
/* private List<Dimension> generatePredefinedDimensions() {
List<Dimension> dimensions = new ArrayList<Dimension>();
//Slope category
{
Dimension d = new Dimension("Slope category");
d.foreignKey = "slope_id";
d.highCardinality = "false";
Hierarchy h = new Hierarchy();
h.table = new Table("slope_category");
Level l = new Level("Slope_category");
l.table = "slope_category";
l.column = "slope_id";
l.nameColumn = "slope_caption";
l.type = "String";
l.levelType = "Regular";
l.uniqueMembers = "false";
h.levels.add(l);
d.hierarchy = h;
dimensions.add(d);
}
//Initial Land Use
{
Dimension d = new Dimension("Initial Land Use");
d.foreignKey = "dynamics_id";
d.highCardinality = "false";
Hierarchy h = new Hierarchy();
h.table = new Table("dynamics_category");
Level l = new Level("Initial_land_use");
l.table = "dynamics_category";
l.column = "dynamics_id";
l.nameColumn = "dynamics_caption";
l.type = "String";
l.levelType = "Regular";
l.uniqueMembers = "false";
l.hideMemberIf = "Never";
h.levels.add(l);
d.hierarchy = h;
dimensions.add(d);
}
//Elevation Range
{
Dimension d = new Dimension("Elevation range");
d.foreignKey = "elevation_id";
d.highCardinality = "false";
Hierarchy h = new Hierarchy();
h.table = new Table("elevation_category");
Level l = new Level("Elevation_range");
l.table = "elevation_category";
l.column = "elevation_id";
l.nameColumn = "elevation_caption";
l.type = "String";
l.levelType = "Regular";
l.uniqueMembers = "false";
l.hideMemberIf = "Never";
h.levels.add(l);
d.hierarchy = h;
dimensions.add(d);
}
return dimensions;
}
*/
private Dimension generateDimension(NodeDefinition nodeDef, EntityDefinition rootEntityDef ) {
String attrName = nodeDef.getName();
String attrLabel = extractLabel(nodeDef);
Dimension dimension = new Dimension(attrLabel);
Hierarchy hierarchy = dimension.hierarchy;
if (nodeDef instanceof CodeAttributeDefinition) {
String rootEntityIdColumnName = getRootEntityIdColumnName(rootEntityDef);
String entityName = attrName;
if( nodeDef.isMultiple() ){
dimension.foreignKey = rootEntityIdColumnName;
hierarchy.primaryKey = rootEntityIdColumnName;
hierarchy.primaryKeyTable = entityName;
Join join = new Join(null);
String codeListName = ((CodeAttributeDefinition) nodeDef).getList().getName();
join.leftKey = codeListName + rdbConfig.getCodeListTableSuffix() + rdbConfig.getIdColumnSuffix();
join.rightKey = codeListName + rdbConfig.getCodeListTableSuffix() + rdbConfig.getIdColumnSuffix();
join.tables = Arrays.asList(
new Table(entityName),
new Table(codeListName + rdbConfig.getCodeListTableSuffix())
);
hierarchy.join = join;
}else{
CodeAttributeDefinition codeAttrDef = (CodeAttributeDefinition) nodeDef;
String codeTableName = extractCodeListTableName(codeAttrDef);
dimension.foreignKey = attrName + rdbConfig.getCodeListTableSuffix() + rdbConfig.getIdColumnSuffix();
hierarchy.table = new Table(codeTableName);
}
}
if (nodeDef instanceof DateAttributeDefinition) {
dimension.type = "";
hierarchy.type = "TimeDimension";
hierarchy.allMemberName = "attrLabel";
String[] levelNames = new String[] {"Year", "Month", "Day"};
for (String levelName : levelNames) {
Level level = new Level(attrLabel + " - " + levelName);
level.column = nodeDef.getName() + "_" + levelName.toLowerCase(Locale.ENGLISH);
level.levelType = String.format("Time%ss", levelName);
level.type = "Numeric";
hierarchy.levels.add(level);
}
} else if (nodeDef instanceof CoordinateAttributeDefinition) {
dimension.type = "";
hierarchy.type = "StandardDimension";
Level level = new Level(attrLabel + " - Latitude");
level.column = nodeDef.getName() + "_y";
hierarchy.levels.add(level);
Level level2 = new Level(attrLabel + " - Longitude");
level2.column = nodeDef.getName() + "_x";
hierarchy.levels.add(level2);
} else {
Level level = generateLevel(nodeDef);
hierarchy.levels.add(level);
}
return dimension;
}
private String extractCodeListTableName(CodeAttributeDefinition codeAttrDef) {
StringBuffer codeListName = new StringBuffer( codeAttrDef.getList().getName() );
int levelIdx = codeAttrDef.getLevelIndex();
if ( levelIdx != -1 ) {
CodeList codeList = codeAttrDef.getList();
List<CodeListLevel> codeHierarchy = codeList.getHierarchy();
if( !codeHierarchy.isEmpty() ){
CodeListLevel currentLevel = codeHierarchy.get(levelIdx);
codeListName.append("_");
codeListName.append(currentLevel.getName());
}
}
return codeListName.append(rdbConfig.getCodeListTableSuffix()).toString();
}
private Level generateLevel(NodeDefinition nodeDef) {
String attrName = nodeDef.getName();
String attrLabel = extractLabel(nodeDef);
Level level = new Level(attrLabel);
if (nodeDef instanceof NumericAttributeDefinition) {
level.type = ((NumericAttributeDefinition) nodeDef).getType() == Type.INTEGER ? "Integer": "Numeric";
} else {
level.type = "String";
}
level.levelType = "Regular";
if (nodeDef instanceof CodeAttributeDefinition) {
CodeAttributeDefinition codeDef = (CodeAttributeDefinition) nodeDef;
String codeTableName = extractCodeListTableName(codeDef);
level.table = codeTableName;
level.column = codeTableName + rdbConfig.getIdColumnSuffix();
level.nameColumn = codeTableName.substring(0, codeTableName.length() - rdbConfig.getCodeListTableSuffix().length()) + "_label_" + language ;
} else {
level.column = attrName;
}
return level;
}
private String extractLabel(NodeDefinition nodeDef) {
String attrLabel = nodeDef.getLabel(NodeLabel.Type.INSTANCE, language);
if (attrLabel == null) {
attrLabel = nodeDef.getName();
}
return attrLabel;
}
private static class MondrianSchemaObject {
@XStreamAsAttribute
private String name;
public MondrianSchemaObject(String name) {
super();
this.name = StringEscapeUtils.escapeHtml4(name);
}
}
@XStreamAlias("Schema")
private static class Schema extends MondrianSchemaObject {
@XStreamAlias("Cube")
private Cube cube;
public Schema(String name) {
super(name);
}
}
@XStreamAlias("Cube")
private static class Cube extends MondrianSchemaObject {
@XStreamAsAttribute
private String cache = "true";
@XStreamAsAttribute
private String enabled = "true";
@XStreamAlias("Table")
private Table table;
@XStreamImplicit
private List<Dimension> dimensions = new ArrayList<Dimension>();
@XStreamImplicit
private List<Measure> measures = new ArrayList<Measure>();
public Cube(String name) {
super(name);
}
}
@XStreamAlias("Table")
private static class Table extends MondrianSchemaObject {
@XStreamAsAttribute
private final String schema = SAIKU_SCHEMA_PLACEHOLDER;
public Table(String name) {
super(name);
}
}
@XStreamAlias("Dimension")
private static class Dimension extends MondrianSchemaObject {
@XStreamAsAttribute
private String foreignKey;
@XStreamAsAttribute
public String type = "StandardDimension";
@XStreamAsAttribute
public String visible = "true";
@XStreamAsAttribute
public String highCardinality;
@XStreamAlias("Hierarchy")
private Hierarchy hierarchy = new Hierarchy(null);
public Dimension(String name) {
super(name);
}
}
@XStreamAlias("Hierarchy")
private static class Hierarchy extends MondrianSchemaObject {
@XStreamAsAttribute
public String type;
@XStreamAsAttribute
public String allMemberName;
@XStreamAsAttribute
private String primaryKey;
@XStreamAsAttribute
private String primaryKeyTable;
@XStreamAlias("Table")
private Table table;
@XStreamAlias("Join")
private Join join;
@XStreamAsAttribute
private String visible = "true";
@XStreamAsAttribute
private String hasAll = "true";
@XStreamImplicit
private List<Level> levels = new ArrayList<Level>();
public Hierarchy(String name) {
super(name);
}
}
@XStreamAlias("Level")
private static class Level extends MondrianSchemaObject {
@XStreamAsAttribute
private String table;
@XStreamAsAttribute
private String column;
@XStreamAsAttribute
private String nameColumn;
@XStreamAsAttribute
private String uniqueMembers ="true";
@XStreamAsAttribute
private String levelType;
@XStreamAsAttribute
private String type;
@XStreamAsAttribute
public String hideMemberIf;
public Level(String name) {
super(name);
}
}
@XStreamAlias("Measure")
private static class Measure extends MondrianSchemaObject {
@XStreamAsAttribute
private String column;
@XStreamAsAttribute
private String datatype;
@XStreamAsAttribute
private String aggregator;
@XStreamAsAttribute
private String caption;
@XStreamAsAttribute
private String formatString;
public Measure(String name) {
super(name);
}
}
@XStreamAlias("Join")
private static class Join extends MondrianSchemaObject {
@XStreamAsAttribute
private String leftKey;
@XStreamAsAttribute
private String rightKey;
@XStreamImplicit
private List<Table> tables;
public Join(String name) {
super(name);
}
}
}
| collect-server/src/main/java/org/openforis/collect/io/metadata/collectearth/MondrianCubeGenerator.java | package org.openforis.collect.io.metadata.collectearth;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import org.apache.commons.lang3.StringEscapeUtils;
import org.openforis.collect.earth.core.rdb.RelationalSchemaContext;
import org.openforis.collect.model.CollectSurvey;
import org.openforis.collect.relational.model.RelationalSchemaConfig;
import org.openforis.idm.metamodel.AttributeDefinition;
import org.openforis.idm.metamodel.CodeAttributeDefinition;
import org.openforis.idm.metamodel.CodeList;
import org.openforis.idm.metamodel.CodeListLevel;
import org.openforis.idm.metamodel.DateAttributeDefinition;
import org.openforis.idm.metamodel.EntityDefinition;
import org.openforis.idm.metamodel.KeyAttributeDefinition;
import org.openforis.idm.metamodel.NodeDefinition;
import org.openforis.idm.metamodel.NodeLabel;
import org.openforis.idm.metamodel.NumberAttributeDefinition;
import org.openforis.idm.metamodel.NumericAttributeDefinition;
import org.openforis.idm.metamodel.NumericAttributeDefinition.Type;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
/**
*
* @author S. Ricci
* @author A. Sanchez-Paus Diaz
*
*/
public class MondrianCubeGenerator {
private static final String SAIKU_SCHEMA_PLACEHOLDER = "${saikuDbSchema}";
private static final String[] MEASURE_AGGREGATORS = new String[] {"min", "max", "avg"};
private CollectSurvey survey;
private RelationalSchemaConfig rdbConfig;
private String language;
public MondrianCubeGenerator(CollectSurvey survey, String language) {
this.survey = survey;
this.language = language;
this.rdbConfig = new RelationalSchemaContext().getRdbConfig();
}
public Schema generateSchema() {
Schema schema = new Schema(survey.getName());
Cube cube = generateCube();
schema.cube = cube;
return schema;
}
public String generateXMLSchema() {
org.openforis.collect.io.metadata.collectearth.MondrianCubeGenerator.Schema mondrianSchema = generateSchema();
XStream xStream = new XStream();
xStream.processAnnotations(MondrianCubeGenerator.Schema.class);
String xmlSchema = xStream.toXML(mondrianSchema);
return xmlSchema;
}
private Cube generateCube() {
Cube cube = new Cube("Collect Earth Plot");
EntityDefinition rootEntityDef = survey.getSchema().getRootEntityDefinitions().get(0);
Table table = new Table(rootEntityDef.getName());
cube.table = table;
List<NodeDefinition> children = rootEntityDef.getChildDefinitions();
for (NodeDefinition nodeDef : children) {
String nodeName = nodeDef.getName();
if (nodeDef instanceof AttributeDefinition) {
Dimension dimension = generateDimension(nodeDef, rootEntityDef );
if (nodeDef instanceof KeyAttributeDefinition && ((KeyAttributeDefinition) nodeDef).isKey()) {
Measure measure = new Measure(rootEntityDef.getName() + "_count");
measure.column = "_" + rootEntityDef.getName() + "_" + nodeName;
measure.caption = StringEscapeUtils.escapeHtml4( extractLabel(rootEntityDef) + " Count" );
measure.aggregator = "distinct count";
measure.datatype = "Integer";
cube.measures.add(measure);
} else if (nodeDef instanceof NumberAttributeDefinition) {
for (String aggregator : MEASURE_AGGREGATORS) {
Measure measure = new Measure(nodeName + "_" + aggregator);
measure.column = nodeName;
measure.caption = StringEscapeUtils.escapeHtml4( extractLabel(nodeDef) + " " + aggregator );
measure.aggregator = aggregator;
measure.datatype = "Numeric";
measure.formatString = "#.##";
cube.measures.add(measure);
}
}
cube.dimensions.add(dimension);
} else {
String rootEntityIdColumnName = getRootEntityIdColumnName(rootEntityDef);
String entityName = nodeName;
String entityLabel = extractLabel(nodeDef);
for (NodeDefinition childDef : ((EntityDefinition) nodeDef).getChildDefinitions()) {
String childLabel = entityLabel + " - " + extractLabel(childDef);
Dimension dimension = new Dimension(childLabel);
Hierarchy hierarchy = new Hierarchy(childLabel);
if( nodeDef.isMultiple() ){
dimension.foreignKey = rootEntityIdColumnName;
hierarchy.primaryKey = rootEntityIdColumnName;
hierarchy.primaryKeyTable = entityName;
if (childDef instanceof CodeAttributeDefinition) {
Join join = new Join(null);
String codeListName = ((CodeAttributeDefinition) childDef).getList().getName();
join.leftKey = childDef.getName() + rdbConfig.getCodeListTableSuffix() + rdbConfig.getIdColumnSuffix();
join.rightKey = codeListName + rdbConfig.getCodeListTableSuffix() + rdbConfig.getIdColumnSuffix();
join.tables = Arrays.asList(
new Table(entityName),
new Table(codeListName + rdbConfig.getCodeListTableSuffix())
);
hierarchy.join = join;
}else{
hierarchy.table = new Table(entityName);
}
hierarchy.levels.add(generateLevel(childDef));
dimension.hierarchy = hierarchy;
}else{
dimension = generateDimension(childDef, rootEntityDef);
}
cube.dimensions.add(dimension);
}
}
}
//add predefined dimensions
// DEPRECATED 07/08/2015 : From now on all the operations to calculate the aspect,elevation,slope and initial land use class are made through Calculated Members
// cube.dimensions.addAll(generatePredefinedDimensions());
//add predefined measures
// Add the measures AFTER the 1st measure, which shouyld be Plot Count
cube.measures.addAll(1, generatePredefinedMeasures());
return cube;
}
public String getRootEntityIdColumnName(EntityDefinition rootEntityDef) {
return rdbConfig.getIdColumnPrefix() + rootEntityDef.getName() + rdbConfig.getIdColumnSuffix();
}
private List<Measure> generatePredefinedMeasures() {
List<Measure> measures = new ArrayList<Measure>();
//Expansion factor - Area
{
Measure measure = new Measure("area");
measure.column = "expansion_factor";
measure.caption = "Area (HA)";
measure.aggregator = "sum";
measure.datatype = "Integer";
measure.formatString = "###,###";
measures.add(measure);
}
// Plot weight
{
Measure measure = new Measure("plot_weight");
measure.column = "plot_weight";
measure.caption = "Plot Weight";
measure.aggregator = "sum";
measure.datatype = "Integer";
measure.formatString = "#,###";
measures.add(measure);
}
return measures;
}
/* private List<Dimension> generatePredefinedDimensions() {
List<Dimension> dimensions = new ArrayList<Dimension>();
//Slope category
{
Dimension d = new Dimension("Slope category");
d.foreignKey = "slope_id";
d.highCardinality = "false";
Hierarchy h = new Hierarchy();
h.table = new Table("slope_category");
Level l = new Level("Slope_category");
l.table = "slope_category";
l.column = "slope_id";
l.nameColumn = "slope_caption";
l.type = "String";
l.levelType = "Regular";
l.uniqueMembers = "false";
h.levels.add(l);
d.hierarchy = h;
dimensions.add(d);
}
//Initial Land Use
{
Dimension d = new Dimension("Initial Land Use");
d.foreignKey = "dynamics_id";
d.highCardinality = "false";
Hierarchy h = new Hierarchy();
h.table = new Table("dynamics_category");
Level l = new Level("Initial_land_use");
l.table = "dynamics_category";
l.column = "dynamics_id";
l.nameColumn = "dynamics_caption";
l.type = "String";
l.levelType = "Regular";
l.uniqueMembers = "false";
l.hideMemberIf = "Never";
h.levels.add(l);
d.hierarchy = h;
dimensions.add(d);
}
//Elevation Range
{
Dimension d = new Dimension("Elevation range");
d.foreignKey = "elevation_id";
d.highCardinality = "false";
Hierarchy h = new Hierarchy();
h.table = new Table("elevation_category");
Level l = new Level("Elevation_range");
l.table = "elevation_category";
l.column = "elevation_id";
l.nameColumn = "elevation_caption";
l.type = "String";
l.levelType = "Regular";
l.uniqueMembers = "false";
l.hideMemberIf = "Never";
h.levels.add(l);
d.hierarchy = h;
dimensions.add(d);
}
return dimensions;
}
*/
private Dimension generateDimension(NodeDefinition nodeDef, EntityDefinition rootEntityDef ) {
String attrName = nodeDef.getName();
String attrLabel = extractLabel(nodeDef);
Dimension dimension = new Dimension(attrLabel);
Hierarchy hierarchy = dimension.hierarchy;
if (nodeDef instanceof CodeAttributeDefinition) {
String rootEntityIdColumnName = getRootEntityIdColumnName(rootEntityDef);
String entityName = attrName;
if( nodeDef.isMultiple() ){
dimension.foreignKey = rootEntityIdColumnName;
hierarchy.primaryKey = rootEntityIdColumnName;
hierarchy.primaryKeyTable = entityName;
Join join = new Join(null);
String codeListName = ((CodeAttributeDefinition) nodeDef).getList().getName();
join.leftKey = codeListName + rdbConfig.getCodeListTableSuffix() + rdbConfig.getIdColumnSuffix();
join.rightKey = codeListName + rdbConfig.getCodeListTableSuffix() + rdbConfig.getIdColumnSuffix();
join.tables = Arrays.asList(
new Table(entityName),
new Table(codeListName + rdbConfig.getCodeListTableSuffix())
);
hierarchy.join = join;
}else{
CodeAttributeDefinition codeAttrDef = (CodeAttributeDefinition) nodeDef;
String codeTableName = extractCodeListTableName(codeAttrDef);
dimension.foreignKey = attrName + rdbConfig.getCodeListTableSuffix() + rdbConfig.getIdColumnSuffix();
hierarchy.table = new Table(codeTableName);
}
}
if (nodeDef instanceof DateAttributeDefinition) {
dimension.type = "";
hierarchy.type = "TimeDimension";
hierarchy.allMemberName = "attrLabel";
String[] levelNames = new String[] {"Year", "Month", "Day"};
for (String levelName : levelNames) {
Level level = new Level(attrLabel + " - " + levelName);
level.column = nodeDef.getName() + "_" + levelName.toLowerCase(Locale.ENGLISH);
level.levelType = String.format("Time%ss", levelName);
level.type = "Numeric";
hierarchy.levels.add(level);
}
} else {
Level level = generateLevel(nodeDef);
hierarchy.levels.add(level);
}
return dimension;
}
private String extractCodeListTableName(CodeAttributeDefinition codeAttrDef) {
StringBuffer codeListName = new StringBuffer( codeAttrDef.getList().getName() );
int levelIdx = codeAttrDef.getLevelIndex();
if ( levelIdx != -1 ) {
CodeList codeList = codeAttrDef.getList();
List<CodeListLevel> codeHierarchy = codeList.getHierarchy();
if( !codeHierarchy.isEmpty() ){
CodeListLevel currentLevel = codeHierarchy.get(levelIdx);
codeListName.append("_");
codeListName.append(currentLevel.getName());
}
}
return codeListName.append(rdbConfig.getCodeListTableSuffix()).toString();
}
private Level generateLevel(NodeDefinition nodeDef) {
String attrName = nodeDef.getName();
String attrLabel = extractLabel(nodeDef);
Level level = new Level(attrLabel);
if (nodeDef instanceof NumericAttributeDefinition) {
level.type = ((NumericAttributeDefinition) nodeDef).getType() == Type.INTEGER ? "Integer": "Numeric";
} else {
level.type = "String";
}
level.levelType = "Regular";
if (nodeDef instanceof CodeAttributeDefinition) {
CodeAttributeDefinition codeDef = (CodeAttributeDefinition) nodeDef;
String codeTableName = extractCodeListTableName(codeDef);
level.table = codeTableName;
level.column = codeTableName + rdbConfig.getIdColumnSuffix();
level.nameColumn = codeTableName.substring(0, codeTableName.length() - rdbConfig.getCodeListTableSuffix().length()) + "_label_" + language ;
} else {
level.column = attrName;
}
return level;
}
private String extractLabel(NodeDefinition nodeDef) {
String attrLabel = nodeDef.getLabel(NodeLabel.Type.INSTANCE, language);
if (attrLabel == null) {
attrLabel = nodeDef.getName();
}
return attrLabel;
}
private static class MondrianSchemaObject {
@XStreamAsAttribute
private String name;
public MondrianSchemaObject(String name) {
super();
this.name = StringEscapeUtils.escapeHtml4(name);
}
}
@XStreamAlias("Schema")
private static class Schema extends MondrianSchemaObject {
@XStreamAlias("Cube")
private Cube cube;
public Schema(String name) {
super(name);
}
}
@XStreamAlias("Cube")
private static class Cube extends MondrianSchemaObject {
@XStreamAsAttribute
private String cache = "true";
@XStreamAsAttribute
private String enabled = "true";
@XStreamAlias("Table")
private Table table;
@XStreamImplicit
private List<Dimension> dimensions = new ArrayList<Dimension>();
@XStreamImplicit
private List<Measure> measures = new ArrayList<Measure>();
public Cube(String name) {
super(name);
}
}
@XStreamAlias("Table")
private static class Table extends MondrianSchemaObject {
@XStreamAsAttribute
private final String schema = SAIKU_SCHEMA_PLACEHOLDER;
public Table(String name) {
super(name);
}
}
@XStreamAlias("Dimension")
private static class Dimension extends MondrianSchemaObject {
@XStreamAsAttribute
private String foreignKey;
@XStreamAsAttribute
public String type = "StandardDimension";
@XStreamAsAttribute
public String visible = "true";
@XStreamAsAttribute
public String highCardinality;
@XStreamAlias("Hierarchy")
private Hierarchy hierarchy = new Hierarchy(null);
public Dimension(String name) {
super(name);
}
}
@XStreamAlias("Hierarchy")
private static class Hierarchy extends MondrianSchemaObject {
@XStreamAsAttribute
public String type;
@XStreamAsAttribute
public String allMemberName;
@XStreamAsAttribute
private String primaryKey;
@XStreamAsAttribute
private String primaryKeyTable;
@XStreamAlias("Table")
private Table table;
@XStreamAlias("Join")
private Join join;
@XStreamAsAttribute
private String visible = "true";
@XStreamAsAttribute
private String hasAll = "true";
@XStreamImplicit
private List<Level> levels = new ArrayList<Level>();
public Hierarchy(String name) {
super(name);
}
}
@XStreamAlias("Level")
private static class Level extends MondrianSchemaObject {
@XStreamAsAttribute
private String table;
@XStreamAsAttribute
private String column;
@XStreamAsAttribute
private String nameColumn;
@XStreamAsAttribute
private String uniqueMembers ="true";
@XStreamAsAttribute
private String levelType;
@XStreamAsAttribute
private String type;
@XStreamAsAttribute
public String hideMemberIf;
public Level(String name) {
super(name);
}
}
@XStreamAlias("Measure")
private static class Measure extends MondrianSchemaObject {
@XStreamAsAttribute
private String column;
@XStreamAsAttribute
private String datatype;
@XStreamAsAttribute
private String aggregator;
@XStreamAsAttribute
private String caption;
@XStreamAsAttribute
private String formatString;
public Measure(String name) {
super(name);
}
}
@XStreamAlias("Join")
private static class Join extends MondrianSchemaObject {
@XStreamAsAttribute
private String leftKey;
@XStreamAsAttribute
private String rightKey;
@XStreamImplicit
private List<Table> tables;
public Join(String name) {
super(name);
}
}
}
| Added coordinate export to Saiku (latitude and longitude levels) | collect-server/src/main/java/org/openforis/collect/io/metadata/collectearth/MondrianCubeGenerator.java | Added coordinate export to Saiku (latitude and longitude levels) |
|
Java | mit | 71428c6ad29f1a9b69db97335c1ba34cdcc7bf6e | 0 | yidongnan/grpc-spring-boot-starter,yidongnan/grpc-spring-boot-starter,yidongnan/grpc-spring-boot-starter | /*
* Copyright (c) 2016-2021 Michael Zhang <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package net.devh.boot.grpc.client.inject;
import static java.util.Objects.requireNonNull;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.springframework.beans.BeanInstantiationException;
import org.springframework.beans.BeansException;
import org.springframework.beans.InvalidPropertyException;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.ReflectionUtils;
import com.google.common.collect.Lists;
import io.grpc.Channel;
import io.grpc.ClientInterceptor;
import io.grpc.stub.AbstractStub;
import net.devh.boot.grpc.client.channelfactory.GrpcChannelFactory;
import net.devh.boot.grpc.client.nameresolver.NameResolverRegistration;
import net.devh.boot.grpc.client.stubfactory.FallbackStubFactory;
import net.devh.boot.grpc.client.stubfactory.StubFactory;
/**
* This {@link BeanPostProcessor} searches for fields and methods in beans that are annotated with {@link GrpcClient}
* and sets them.
*
* @author Michael ([email protected])
* @author Daniel Theuke ([email protected])
*/
public class GrpcClientBeanPostProcessor implements BeanPostProcessor {
private final ApplicationContext applicationContext;
// Is only retrieved when needed to avoid too early initialization of these components,
// which could lead to problems with the correct bean setup.
private GrpcChannelFactory channelFactory = null;
private List<StubTransformer> stubTransformers = null;
private List<StubFactory> stubFactories = null;
// For bean registration via @GrpcClientBean
private ConfigurableListableBeanFactory configurableBeanFactory;
/**
* Creates a new GrpcClientBeanPostProcessor with the given ApplicationContext.
*
* @param applicationContext The application context that will be used to get lazy access to the
* {@link GrpcChannelFactory} and {@link StubTransformer}s.
*/
public GrpcClientBeanPostProcessor(final ApplicationContext applicationContext) {
this.applicationContext = requireNonNull(applicationContext, "applicationContext");
}
@Override
public Object postProcessBeforeInitialization(final Object bean, final String beanName) throws BeansException {
Class<?> clazz = bean.getClass();
do {
for (final Field field : clazz.getDeclaredFields()) {
final GrpcClient annotation = AnnotationUtils.findAnnotation(field, GrpcClient.class);
if (annotation != null) {
ReflectionUtils.makeAccessible(field);
ReflectionUtils.setField(field, bean, processInjectionPoint(field, field.getType(), annotation));
}
}
for (final Method method : clazz.getDeclaredMethods()) {
final GrpcClient annotation = AnnotationUtils.findAnnotation(method, GrpcClient.class);
if (annotation != null) {
final Class<?>[] paramTypes = method.getParameterTypes();
if (paramTypes.length != 1) {
throw new BeanDefinitionStoreException(
"Method " + method + " doesn't have exactly one parameter.");
}
ReflectionUtils.makeAccessible(method);
ReflectionUtils.invokeMethod(method, bean,
processInjectionPoint(method, paramTypes[0], annotation));
}
}
if (isAnnotatedWithConfiguration(clazz)) {
for (final GrpcClientBean annotation : clazz.getAnnotationsByType(GrpcClientBean.class)) {
final String beanNameToCreate = getBeanName(annotation);
try {
final ConfigurableListableBeanFactory beanFactory = getConfigurableBeanFactory();
final Object beanValue =
processInjectionPoint(null, annotation.clazz(), annotation.client());
beanFactory.registerSingleton(beanNameToCreate, beanValue);
} catch (final Exception e) {
throw new BeanCreationException(
"Could not create and register grpc client bean " + beanNameToCreate + " from class " +
clazz.getSimpleName(),
e);
}
}
}
clazz = clazz.getSuperclass();
} while (clazz != null);
return bean;
}
/**
* Processes the given injection point and computes the appropriate value for the injection.
*
* @param <T> The type of the value to be injected.
* @param injectionTarget The target of the injection.
* @param injectionType The class that will be used to compute injection.
* @param annotation The annotation on the target with the metadata for the injection.
* @return The value to be injected for the given injection point.
*/
protected <T> T processInjectionPoint(final Member injectionTarget, final Class<T> injectionType,
final GrpcClient annotation) {
final List<ClientInterceptor> interceptors = interceptorsFromAnnotation(annotation);
final String name = annotation.value();
final Channel channel;
try {
channel = getChannelFactory().createChannel(name, interceptors, annotation.sortInterceptors());
if (channel == null) {
throw new IllegalStateException("Channel factory created a null channel for " + name);
}
} catch (final RuntimeException e) {
throw new IllegalStateException("Failed to create channel: " + name, e);
}
final T value = valueForMember(name, injectionTarget, injectionType, channel);
if (value == null) {
throw new IllegalStateException(
"Injection value is null unexpectedly for " + name + " at " + injectionTarget);
}
return value;
}
/**
* Lazy getter for the {@link GrpcChannelFactory}.
*
* @return The grpc channel factory to use.
*/
private GrpcChannelFactory getChannelFactory() {
if (this.channelFactory == null) {
// Ensure that the NameResolverProviders have been registered
this.applicationContext.getBean(NameResolverRegistration.class);
final GrpcChannelFactory factory = this.applicationContext.getBean(GrpcChannelFactory.class);
this.channelFactory = factory;
return factory;
}
return this.channelFactory;
}
/**
* Lazy getter for the {@link StubTransformer}s.
*
* @return The stub transformers to use.
*/
private List<StubTransformer> getStubTransformers() {
if (this.stubTransformers == null) {
final Collection<StubTransformer> transformers =
this.applicationContext.getBeansOfType(StubTransformer.class).values();
this.stubTransformers = new ArrayList<>(transformers);
return this.stubTransformers;
}
return this.stubTransformers;
}
/**
* Gets or creates the {@link ClientInterceptor}s that are referenced in the given annotation.
*
* <p>
* <b>Note:</b> This methods return value does not contain the global client interceptors because they are handled
* by the {@link GrpcChannelFactory}.
* </p>
*
* @param annotation The annotation to get the interceptors for.
* @return A list containing the interceptors for the given annotation.
* @throws BeansException If the referenced interceptors weren't found or could not be created.
*/
protected List<ClientInterceptor> interceptorsFromAnnotation(final GrpcClient annotation) throws BeansException {
final List<ClientInterceptor> list = Lists.newArrayList();
for (final Class<? extends ClientInterceptor> interceptorClass : annotation.interceptors()) {
final ClientInterceptor clientInterceptor;
if (this.applicationContext.getBeanNamesForType(interceptorClass).length > 0) {
clientInterceptor = this.applicationContext.getBean(interceptorClass);
} else {
try {
clientInterceptor = interceptorClass.getConstructor().newInstance();
} catch (final Exception e) {
throw new BeanCreationException("Failed to create interceptor instance", e);
}
}
list.add(clientInterceptor);
}
for (final String interceptorName : annotation.interceptorNames()) {
list.add(this.applicationContext.getBean(interceptorName, ClientInterceptor.class));
}
return list;
}
/**
* Creates the instance to be injected for the given member.
*
* @param <T> The type of the instance to be injected.
* @param name The name that was used to create the channel.
* @param injectionTarget The target member for the injection.
* @param injectionType The class that should injected.
* @param channel The channel that should be used to create the instance.
* @return The value that matches the type of the given field.
* @throws BeansException If the value of the field could not be created or the type of the field is unsupported.
*/
protected <T> T valueForMember(final String name, final Member injectionTarget,
final Class<T> injectionType,
final Channel channel) throws BeansException {
if (Channel.class.equals(injectionType)) {
return injectionType.cast(channel);
} else if (AbstractStub.class.isAssignableFrom(injectionType)) {
@SuppressWarnings("unchecked") // Eclipse incorrectly marks this as not required
AbstractStub<?> stub = createStub(
(Class<? extends AbstractStub<?>>) injectionType.asSubclass(AbstractStub.class), channel);
for (final StubTransformer stubTransformer : getStubTransformers()) {
stub = stubTransformer.transform(name, stub);
}
return injectionType.cast(stub);
} else {
if (injectionTarget != null) {
throw new InvalidPropertyException(injectionTarget.getDeclaringClass(), injectionTarget.getName(),
"Unsupported type " + injectionType.getName());
} else {
throw new InvalidPropertyException(injectionType.getDeclaringClass(), injectionType.getName(),
"Unsupported type " + injectionType.getName());
}
}
}
/**
* Creates a stub instance for the specified stub type using the resolved {@link StubFactory}.
*
* @param stubClass The stub class that needs to be created.
* @param channel The gRPC channel associated with the created stub, passed as a parameter to the stub factory.
* @return A newly created gRPC stub.
* @throws BeanInstantiationException If the stub couldn't be created, either because the type isn't supported or
* because of a failure in creation.
*/
private AbstractStub<?> createStub(final Class<? extends AbstractStub<?>> stubClass, final Channel channel) {
final StubFactory factory = getStubFactories().stream()
.filter(stubFactory -> stubFactory.isApplicable(stubClass))
.findFirst()
.orElseThrow(() -> new BeanInstantiationException(stubClass,
"Unsupported stub type: " + stubClass.getName() + " -> Please report this issue."));
try {
return factory.createStub(stubClass, channel);
} catch (final Exception exception) {
throw new BeanInstantiationException(stubClass, "Failed to create gRPC stub of type " + stubClass.getName(),
exception);
}
}
/**
* Lazy getter for the list of defined {@link StubFactory} beans.
*
* @return A list of all defined {@link StubFactory} beans.
*/
private List<StubFactory> getStubFactories() {
if (this.stubFactories == null) {
this.stubFactories = new ArrayList<>(this.applicationContext.getBeansOfType(StubFactory.class).values());
this.stubFactories.add(new FallbackStubFactory());
}
return this.stubFactories;
}
/**
* Lazy factory getter from the context for bean registration with {@link GrpcClientBean} annotations.
*
* @return configurable bean factory
*/
private ConfigurableListableBeanFactory getConfigurableBeanFactory() {
if (this.configurableBeanFactory == null) {
this.configurableBeanFactory = ((ConfigurableApplicationContext) this.applicationContext).getBeanFactory();
}
return this.configurableBeanFactory;
}
/**
* Gets the bean name from the given annotation.
*
* @param grpcClientBean The annotation to extract it from.
* @return The extracted name.
*/
private String getBeanName(final GrpcClientBean grpcClientBean) {
if (!grpcClientBean.beanName().isEmpty()) {
return grpcClientBean.beanName();
} else {
return grpcClientBean.client().value() + grpcClientBean.clazz().getSimpleName();
}
}
/**
* Checks whether the given class is annotated with {@link Configuration}.
*
* @param clazz The class to check.
* @return True, if the given class is annotated with {@link Configuration}. False otherwise.
*/
private boolean isAnnotatedWithConfiguration(final Class<?> clazz) {
final Configuration configurationAnnotation = AnnotationUtils.findAnnotation(clazz, Configuration.class);
return configurationAnnotation != null;
}
}
| grpc-client-spring-boot-autoconfigure/src/main/java/net/devh/boot/grpc/client/inject/GrpcClientBeanPostProcessor.java | /*
* Copyright (c) 2016-2021 Michael Zhang <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package net.devh.boot.grpc.client.inject;
import static java.util.Objects.requireNonNull;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.springframework.beans.BeanInstantiationException;
import org.springframework.beans.BeansException;
import org.springframework.beans.InvalidPropertyException;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.ReflectionUtils;
import com.google.common.collect.Lists;
import io.grpc.Channel;
import io.grpc.ClientInterceptor;
import io.grpc.stub.AbstractStub;
import net.devh.boot.grpc.client.channelfactory.GrpcChannelFactory;
import net.devh.boot.grpc.client.nameresolver.NameResolverRegistration;
import net.devh.boot.grpc.client.stubfactory.FallbackStubFactory;
import net.devh.boot.grpc.client.stubfactory.StubFactory;
/**
* This {@link BeanPostProcessor} searches for fields and methods in beans that are annotated with {@link GrpcClient}
* and sets them.
*
* @author Michael ([email protected])
* @author Daniel Theuke ([email protected])
*/
public class GrpcClientBeanPostProcessor implements BeanPostProcessor {
private final ApplicationContext applicationContext;
// Is only retrieved when needed to avoid too early initialization of these components,
// which could lead to problems with the correct bean setup.
private GrpcChannelFactory channelFactory = null;
private List<StubTransformer> stubTransformers = null;
private List<StubFactory> stubFactories = null;
// For bean registration via @GrpcClientBean
private ConfigurableListableBeanFactory configurableBeanFactory;
/**
* Creates a new GrpcClientBeanPostProcessor with the given ApplicationContext.
*
* @param applicationContext The application context that will be used to get lazy access to the
* {@link GrpcChannelFactory} and {@link StubTransformer}s.
*/
public GrpcClientBeanPostProcessor(final ApplicationContext applicationContext) {
this.applicationContext = requireNonNull(applicationContext, "applicationContext");
}
@Override
public Object postProcessBeforeInitialization(final Object bean, final String beanName) throws BeansException {
Class<?> clazz = bean.getClass();
do {
for (final Field field : clazz.getDeclaredFields()) {
final GrpcClient annotation = AnnotationUtils.findAnnotation(field, GrpcClient.class);
if (annotation != null) {
ReflectionUtils.makeAccessible(field);
ReflectionUtils.setField(field, bean, processInjectionPoint(field, field.getType(), annotation));
}
}
for (final Method method : clazz.getDeclaredMethods()) {
final GrpcClient annotation = AnnotationUtils.findAnnotation(method, GrpcClient.class);
if (annotation != null) {
final Class<?>[] paramTypes = method.getParameterTypes();
if (paramTypes.length != 1) {
throw new BeanDefinitionStoreException(
"Method " + method + " doesn't have exactly one parameter.");
}
ReflectionUtils.makeAccessible(method);
ReflectionUtils.invokeMethod(method, bean,
processInjectionPoint(method, paramTypes[0], annotation));
}
}
if (isAnnotatedWithConfiguration(clazz)) {
for (final GrpcClientBean beanClientIterator : clazz.getAnnotationsByType(GrpcClientBean.class)) {
final String beanNameToCreate = getBeanName(beanClientIterator);
try {
final ConfigurableListableBeanFactory beanFactory = getConfigurableBeanFactory();
final Object beanValue =
processInjectionPoint(null, beanClientIterator.clazz(), beanClientIterator.client());
beanFactory.registerSingleton(beanNameToCreate, beanValue);
} catch (final Exception e) {
throw new BeanCreationException(
"Could not create and register grpc client bean " + beanNameToCreate + " from class " +
clazz.getSimpleName(),
e);
}
}
}
clazz = clazz.getSuperclass();
} while (clazz != null);
return bean;
}
/**
* Processes the given injection point and computes the appropriate value for the injection.
*
* @param <T> The type of the value to be injected.
* @param injectionTarget The target of the injection.
* @param injectionType The class that will be used to compute injection.
* @param annotation The annotation on the target with the metadata for the injection.
* @return The value to be injected for the given injection point.
*/
protected <T> T processInjectionPoint(final Member injectionTarget, final Class<T> injectionType,
final GrpcClient annotation) {
final List<ClientInterceptor> interceptors = interceptorsFromAnnotation(annotation);
final String name = annotation.value();
final Channel channel;
try {
channel = getChannelFactory().createChannel(name, interceptors, annotation.sortInterceptors());
if (channel == null) {
throw new IllegalStateException("Channel factory created a null channel for " + name);
}
} catch (final RuntimeException e) {
throw new IllegalStateException("Failed to create channel: " + name, e);
}
final T value = valueForMember(name, injectionTarget, injectionType, channel);
if (value == null) {
throw new IllegalStateException(
"Injection value is null unexpectedly for " + name + " at " + injectionTarget);
}
return value;
}
/**
* Lazy getter for the {@link GrpcChannelFactory}.
*
* @return The grpc channel factory to use.
*/
private GrpcChannelFactory getChannelFactory() {
if (this.channelFactory == null) {
// Ensure that the NameResolverProviders have been registered
this.applicationContext.getBean(NameResolverRegistration.class);
final GrpcChannelFactory factory = this.applicationContext.getBean(GrpcChannelFactory.class);
this.channelFactory = factory;
return factory;
}
return this.channelFactory;
}
/**
* Lazy getter for the {@link StubTransformer}s.
*
* @return The stub transformers to use.
*/
private List<StubTransformer> getStubTransformers() {
if (this.stubTransformers == null) {
final Collection<StubTransformer> transformers =
this.applicationContext.getBeansOfType(StubTransformer.class).values();
this.stubTransformers = new ArrayList<>(transformers);
return this.stubTransformers;
}
return this.stubTransformers;
}
/**
* Gets or creates the {@link ClientInterceptor}s that are referenced in the given annotation.
*
* <p>
* <b>Note:</b> This methods return value does not contain the global client interceptors because they are handled
* by the {@link GrpcChannelFactory}.
* </p>
*
* @param annotation The annotation to get the interceptors for.
* @return A list containing the interceptors for the given annotation.
* @throws BeansException If the referenced interceptors weren't found or could not be created.
*/
protected List<ClientInterceptor> interceptorsFromAnnotation(final GrpcClient annotation) throws BeansException {
final List<ClientInterceptor> list = Lists.newArrayList();
for (final Class<? extends ClientInterceptor> interceptorClass : annotation.interceptors()) {
final ClientInterceptor clientInterceptor;
if (this.applicationContext.getBeanNamesForType(interceptorClass).length > 0) {
clientInterceptor = this.applicationContext.getBean(interceptorClass);
} else {
try {
clientInterceptor = interceptorClass.getConstructor().newInstance();
} catch (final Exception e) {
throw new BeanCreationException("Failed to create interceptor instance", e);
}
}
list.add(clientInterceptor);
}
for (final String interceptorName : annotation.interceptorNames()) {
list.add(this.applicationContext.getBean(interceptorName, ClientInterceptor.class));
}
return list;
}
/**
* Creates the instance to be injected for the given member.
*
* @param <T> The type of the instance to be injected.
* @param name The name that was used to create the channel.
* @param injectionTarget The target member for the injection.
* @param injectionType The class that should injected.
* @param channel The channel that should be used to create the instance.
* @return The value that matches the type of the given field.
* @throws BeansException If the value of the field could not be created or the type of the field is unsupported.
*/
protected <T> T valueForMember(final String name, final Member injectionTarget,
final Class<T> injectionType,
final Channel channel) throws BeansException {
if (Channel.class.equals(injectionType)) {
return injectionType.cast(channel);
} else if (AbstractStub.class.isAssignableFrom(injectionType)) {
@SuppressWarnings("unchecked") // Eclipse incorrectly marks this as not required
AbstractStub<?> stub = createStub(
(Class<? extends AbstractStub<?>>) injectionType.asSubclass(AbstractStub.class), channel);
for (final StubTransformer stubTransformer : getStubTransformers()) {
stub = stubTransformer.transform(name, stub);
}
return injectionType.cast(stub);
} else {
if (injectionTarget != null) {
throw new InvalidPropertyException(injectionTarget.getDeclaringClass(), injectionTarget.getName(),
"Unsupported type " + injectionType.getName());
} else {
throw new InvalidPropertyException(injectionType.getDeclaringClass(), injectionType.getName(),
"Unsupported type " + injectionType.getName());
}
}
}
/**
* Creates a stub instance for the specified stub type using the resolved {@link StubFactory}.
*
* @param stubClass The stub class that needs to be created.
* @param channel The gRPC channel associated with the created stub, passed as a parameter to the stub factory.
* @return A newly created gRPC stub.
* @throws BeanInstantiationException If the stub couldn't be created, either because the type isn't supported or
* because of a failure in creation.
*/
private AbstractStub<?> createStub(final Class<? extends AbstractStub<?>> stubClass, final Channel channel) {
final StubFactory factory = getStubFactories().stream()
.filter(stubFactory -> stubFactory.isApplicable(stubClass))
.findFirst()
.orElseThrow(() -> new BeanInstantiationException(stubClass,
"Unsupported stub type: " + stubClass.getName() + " -> Please report this issue."));
try {
return factory.createStub(stubClass, channel);
} catch (final Exception exception) {
throw new BeanInstantiationException(stubClass, "Failed to create gRPC stub of type " + stubClass.getName(),
exception);
}
}
/**
* Lazy getter for the list of defined {@link StubFactory} beans.
*
* @return A list of all defined {@link StubFactory} beans.
*/
private List<StubFactory> getStubFactories() {
if (this.stubFactories == null) {
this.stubFactories = new ArrayList<>(this.applicationContext.getBeansOfType(StubFactory.class).values());
this.stubFactories.add(new FallbackStubFactory());
}
return this.stubFactories;
}
/**
* Lazy factory getter from the context for bean registration with {@link GrpcClientBean} annotations.
*
* @return configurable bean factory
*/
private ConfigurableListableBeanFactory getConfigurableBeanFactory() {
if (this.configurableBeanFactory == null) {
this.configurableBeanFactory = ((ConfigurableApplicationContext) this.applicationContext).getBeanFactory();
}
return this.configurableBeanFactory;
}
/**
* Gets the bean name from the given annotation.
*
* @param grpcClientBean The annotation to extract it from.
* @return The extracted name.
*/
private String getBeanName(final GrpcClientBean grpcClientBean) {
if (!grpcClientBean.beanName().isEmpty()) {
return grpcClientBean.beanName();
} else {
return grpcClientBean.client().value() + grpcClientBean.clazz().getSimpleName();
}
}
/**
* Checks whether the given class is annotated with {@link Configuration}.
*
* @param clazz The class to check.
* @return True, if the given class is annotated with {@link Configuration}. False otherwise.
*/
private boolean isAnnotatedWithConfiguration(final Class<?> clazz) {
final Configuration configurationAnnotation = AnnotationUtils.findAnnotation(clazz, Configuration.class);
return configurationAnnotation != null;
}
}
| Renamed field in a more readable form
| grpc-client-spring-boot-autoconfigure/src/main/java/net/devh/boot/grpc/client/inject/GrpcClientBeanPostProcessor.java | Renamed field in a more readable form |
|
Java | mit | 35ed4fbe9b311c4b54c74ffa05f91a377f7761de | 0 | englishtown/vertx-jersey,christianbellinaef/vertx-jersey,englishtown/vertx-jersey,ef-labs/vertx-jersey,vnadgir-ef/vertx-jersey,ef-labs/vertx-jersey,vnadgir-ef/vertx-jersey,christianbellinaef/vertx-jersey | /*
* The MIT License (MIT)
* Copyright © 2013 Englishtown <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the “Software”), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.englishtown.vertx.jersey.metrics;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import com.englishtown.vertx.jersey.inject.VertxRequestProcessor;
import org.glassfish.jersey.server.ContainerRequest;
import org.vertx.java.core.Handler;
import org.vertx.java.core.http.HttpServerRequest;
import javax.inject.Inject;
import static com.codahale.metrics.MetricRegistry.name;
/**
* Adds metrics for vert.x requests
*/
public class RequestProcessor implements VertxRequestProcessor {
public static final String FIRST_BYTE_TIMER_CONTEXT = "et.timer.firstByte.context";
public static final String LAST_BYTE_TIMER_CONTEXT = "et.timer.lastByte.context";
public static final String FIRST_BYTE_TIMER_NAME = "et.metrics.jersey.firstByte";
public static final String LAST_BYTE_TIMER_NAME = "et.metrics.jersey.lastByte";
private final Timer firstByteTimer;
private final Timer lastByteTimer;
@Inject
public RequestProcessor(MetricRegistry registry) {
firstByteTimer = registry.timer(FIRST_BYTE_TIMER_NAME);
lastByteTimer = registry.timer(LAST_BYTE_TIMER_NAME);
}
/**
* Provide additional async request processing
*
* @param vertxRequest the vert.x http server request
* @param jerseyRequest the jersey container request
* @param done the done async callback handler
*/
@Override
public void process(HttpServerRequest vertxRequest, ContainerRequest jerseyRequest, Handler<Void> done) {
jerseyRequest.setProperty(FIRST_BYTE_TIMER_CONTEXT, firstByteTimer.time());
jerseyRequest.setProperty(LAST_BYTE_TIMER_CONTEXT, lastByteTimer.time());
done.handle(null);
}
}
| vertx-mod-jerseymetrics/src/main/java/com/englishtown/vertx/jersey/metrics/RequestProcessor.java | /*
* The MIT License (MIT)
* Copyright © 2013 Englishtown <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the “Software”), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.englishtown.vertx.jersey.metrics;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import com.englishtown.vertx.jersey.inject.VertxRequestProcessor;
import org.glassfish.jersey.server.ContainerRequest;
import org.vertx.java.core.Handler;
import org.vertx.java.core.http.HttpServerRequest;
import javax.inject.Inject;
import static com.codahale.metrics.MetricRegistry.name;
/**
* Adds metrics for vert.x requests
*/
public class RequestProcessor implements VertxRequestProcessor {
public static final String FIRST_BYTE_TIMER_CONTEXT = "et.timer.firstByte.context";
public static final String LAST_BYTE_TIMER_CONTEXT = "et.timer.lastByte.context";
public static final String FIRST_BYTE_TIMER_NAME = "com.englishtown.vertx.jersey.metrics.firstByte";
public static final String LAST_BYTE_TIMER_NAME = "com.englishtown.vertx.jersey.metrics.lastByte";
private final Timer firstByteTimer;
private final Timer lastByteTimer;
@Inject
public RequestProcessor(MetricRegistry registry) {
firstByteTimer = registry.timer(FIRST_BYTE_TIMER_NAME);
lastByteTimer = registry.timer(LAST_BYTE_TIMER_NAME);
}
/**
* Provide additional async request processing
*
* @param vertxRequest the vert.x http server request
* @param jerseyRequest the jersey container request
* @param done the done async callback handler
*/
@Override
public void process(HttpServerRequest vertxRequest, ContainerRequest jerseyRequest, Handler<Void> done) {
jerseyRequest.setProperty(FIRST_BYTE_TIMER_CONTEXT, firstByteTimer.time());
jerseyRequest.setProperty(LAST_BYTE_TIMER_CONTEXT, lastByteTimer.time());
done.handle(null);
}
}
| Shortened metric names
| vertx-mod-jerseymetrics/src/main/java/com/englishtown/vertx/jersey/metrics/RequestProcessor.java | Shortened metric names |
|
Java | mit | b2e829ed42b6fd0bd76bdb44b95d818075071a6e | 0 | raoulvdberge/refinedstorage,raoulvdberge/refinedstorage | package com.refinedmods.refinedstorage.integration.jei;
import com.mojang.blaze3d.matrix.MatrixStack;
import mezz.jei.api.gui.IRecipeLayout;
import mezz.jei.api.recipe.transfer.IRecipeTransferError;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.item.ItemStack;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraftforge.fml.client.gui.GuiUtils;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
public class RecipeTransferCraftingGridError implements IRecipeTransferError {
private static final Color MISSING_HIGHLIGHT_COLOR = new Color(1.0f, 0.0f, 0.0f, 0.4f);
protected static final Color AUTOCRAFTING_HIGHLIGHT_COLOR = new Color(0.0f, 0.0f, 1.0f, 0.4f);
protected final IngredientTracker tracker;
public RecipeTransferCraftingGridError(IngredientTracker tracker) {
this.tracker = tracker;
}
@Override
public Type getType() {
return Type.COSMETIC;
}
@Override
public void showError(MatrixStack stack, int mouseX, int mouseY, IRecipeLayout recipeLayout, int recipeX, int recipeY) {
List<ITextComponent> message = drawIngredientHighlights(stack, recipeX, recipeY);
Screen currentScreen = Minecraft.getInstance().currentScreen;
GuiUtils.drawHoveringText(ItemStack.EMPTY, stack, message, mouseX, mouseY, currentScreen.width, currentScreen.height, 200, Minecraft.getInstance().fontRenderer);
}
protected List<ITextComponent> drawIngredientHighlights(MatrixStack stack, int recipeX, int recipeY) {
List<ITextComponent> message = new ArrayList<>();
message.add(new TranslationTextComponent("jei.tooltip.transfer"));
boolean craftMessage = false;
boolean missingMessage = false;
for (Ingredient ingredient : tracker.getIngredients()) {
if (!ingredient.isAvailable()) {
if (ingredient.isCraftable()) {
ingredient.getGuiIngredient().drawHighlight(stack, AUTOCRAFTING_HIGHLIGHT_COLOR.getRGB(), recipeX, recipeY);
craftMessage = true;
} else {
ingredient.getGuiIngredient().drawHighlight(stack, MISSING_HIGHLIGHT_COLOR.getRGB(), recipeX, recipeY);
missingMessage = true;
}
}
}
if (missingMessage) {
message.add(new TranslationTextComponent("jei.tooltip.error.recipe.transfer.missing").mergeStyle(TextFormatting.RED));
}
if (craftMessage) {
message.add(new TranslationTextComponent("gui.refinedstorage.jei.transfer.request_autocrafting").mergeStyle(TextFormatting.BLUE));
}
return message;
}
}
| src/main/java/com/refinedmods/refinedstorage/integration/jei/RecipeTransferCraftingGridError.java | package com.refinedmods.refinedstorage.integration.jei;
import com.mojang.blaze3d.matrix.MatrixStack;
import mezz.jei.api.gui.IRecipeLayout;
import mezz.jei.api.recipe.transfer.IRecipeTransferError;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.item.ItemStack;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraftforge.fml.client.gui.GuiUtils;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
public class RecipeTransferCraftingGridError implements IRecipeTransferError {
private static final Color MISSING_HIGHLIGHT_COLOR = new Color(1.0f, 0.0f, 0.0f, 0.4f);
protected static final Color AUTOCRAFTING_HIGHLIGHT_COLOR = new Color(0.0f, 0.0f, 1.0f, 0.4f);
protected final IngredientTracker tracker;
public RecipeTransferCraftingGridError(IngredientTracker tracker) {
this.tracker = tracker;
}
@Override
public Type getType() {
return Type.COSMETIC;
}
@Override
public void showError(MatrixStack stack, int mouseX, int mouseY, IRecipeLayout recipeLayout, int recipeX, int recipeY) {
List<ITextComponent> message = drawIngredientHighlights(stack, recipeX, recipeY);
Screen currentScreen = Minecraft.getInstance().currentScreen;
GuiUtils.drawHoveringText(ItemStack.EMPTY, stack, message, mouseX, mouseY, currentScreen.width, currentScreen.height, 150, Minecraft.getInstance().fontRenderer);
}
protected List<ITextComponent> drawIngredientHighlights(MatrixStack stack, int recipeX, int recipeY) {
List<ITextComponent> message = new ArrayList<>();
message.add(new TranslationTextComponent("jei.tooltip.transfer"));
boolean craftMessage = false;
boolean missingMessage = false;
for (Ingredient ingredient : tracker.getIngredients()) {
if (!ingredient.isAvailable()) {
if (ingredient.isCraftable()) {
ingredient.getGuiIngredient().drawHighlight(stack, AUTOCRAFTING_HIGHLIGHT_COLOR.getRGB(), recipeX, recipeY);
craftMessage = true;
} else {
ingredient.getGuiIngredient().drawHighlight(stack, MISSING_HIGHLIGHT_COLOR.getRGB(), recipeX, recipeY);
missingMessage = true;
}
}
}
if (missingMessage) {
message.add(new TranslationTextComponent("jei.tooltip.error.recipe.transfer.missing").mergeStyle(TextFormatting.RED));
}
if (craftMessage) {
message.add(new TranslationTextComponent("gui.refinedstorage.jei.transfer.request_autocrafting").mergeStyle(TextFormatting.BLUE));
}
return message;
}
}
| fix tooltip position for transfer in JEI (#2971)
| src/main/java/com/refinedmods/refinedstorage/integration/jei/RecipeTransferCraftingGridError.java | fix tooltip position for transfer in JEI (#2971) |
|
Java | epl-1.0 | 2623ae249cbcf9a15451b3009323022c0d8679a9 | 0 | rrimmana/birt-1,Charling-Huang/birt,rrimmana/birt-1,Charling-Huang/birt,Charling-Huang/birt,sguan-actuate/birt,sguan-actuate/birt,rrimmana/birt-1,sguan-actuate/birt,rrimmana/birt-1,sguan-actuate/birt,sguan-actuate/birt,Charling-Huang/birt,rrimmana/birt-1,Charling-Huang/birt | /*******************************************************************************
* Copyright (c) 2008 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.chart.device.util;
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.Stroke;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import org.eclipse.birt.chart.computation.BoundingBox;
import org.eclipse.birt.chart.computation.Methods;
import org.eclipse.birt.chart.device.IDeviceRenderer;
import org.eclipse.birt.chart.device.IDisplayServer;
import org.eclipse.birt.chart.device.IPrimitiveRenderer;
import org.eclipse.birt.chart.device.ITextMetrics;
import org.eclipse.birt.chart.device.TextRendererAdapter;
import org.eclipse.birt.chart.device.extension.i18n.Messages;
import org.eclipse.birt.chart.device.plugin.ChartDeviceExtensionPlugin;
import org.eclipse.birt.chart.device.swing.SwingRendererImpl;
import org.eclipse.birt.chart.exception.ChartException;
import org.eclipse.birt.chart.model.attribute.AttributeFactory;
import org.eclipse.birt.chart.model.attribute.Bounds;
import org.eclipse.birt.chart.model.attribute.ColorDefinition;
import org.eclipse.birt.chart.model.attribute.FontDefinition;
import org.eclipse.birt.chart.model.attribute.HorizontalAlignment;
import org.eclipse.birt.chart.model.attribute.Insets;
import org.eclipse.birt.chart.model.attribute.LineAttributes;
import org.eclipse.birt.chart.model.attribute.Location;
import org.eclipse.birt.chart.model.attribute.Text;
import org.eclipse.birt.chart.model.attribute.TextAlignment;
import org.eclipse.birt.chart.model.attribute.VerticalAlignment;
import org.eclipse.birt.chart.model.attribute.impl.LocationImpl;
import org.eclipse.birt.chart.model.component.Label;
import org.eclipse.birt.chart.util.ChartUtil;
public class ChartTextRenderer extends TextRendererAdapter
{
/**
*
*/
public ChartTextRenderer( IDisplayServer dispServer )
{
super( dispServer );
}
/**
* This method renders the 'shadow' at an offset from the text 'rotated
* rectangle' subsequently rendered.
*
* @param renderer
* @param labelPosition
* The position of the label w.r.t. the location specified by
* 'location'
* @param location
* The location (specified as a 2d point) where the text is to be
* rendered
* @param label
* The chart model structure containing the encapsulated text
* (and attributes) to be rendered
*/
public final void renderShadowAtLocation( IPrimitiveRenderer renderer,
int labelPosition, Location location, Label label )
throws ChartException
{
final ColorDefinition cdShadow = label.getShadowColor( );
if ( cdShadow == null )
{
throw new ChartException( ChartDeviceExtensionPlugin.ID,
ChartException.RENDERING,
"exception.undefined.shadow.color", //$NON-NLS-1$
Messages.getResourceBundle( _sxs.getULocale( ) ) );
}
final Graphics2D g2d = (Graphics2D) ( (IDeviceRenderer) renderer ).getGraphicsContext( );
g2d.setFont( (java.awt.Font) _sxs.createFont( label.getCaption( )
.getFont( ) ) );
switch ( labelPosition & POSITION_MASK )
{
case ABOVE :
showTopValue( renderer, location, label, labelPosition, true );
break;
case BELOW :
showBottomValue( renderer, location, label, labelPosition, true );
break;
case LEFT :
showLeftValue( renderer, location, label, labelPosition, true );
break;
case RIGHT :
showRightValue( renderer, location, label, labelPosition, true );
break;
}
}
/**
*
* @param renderer
* @param labelPosition
* IConstants. LEFT, RIGHT, ABOVE or BELOW
* @param location
* POINT WHERE THE CORNER OF THE ROTATED RECTANGLE (OR EDGE
* CENTERED) IS RENDERED
* @param label
* @throws RenderingException
*/
public final void renderTextAtLocation( IPrimitiveRenderer renderer,
int labelPosition, Location location, Label label )
throws ChartException
{
final ColorDefinition colorDef = label.getCaption( ).getColor( );
if ( colorDef == null )
{
throw new ChartException( ChartDeviceExtensionPlugin.ID,
ChartException.RENDERING,
"exception.undefined.text.color", //$NON-NLS-1$
Messages.getResourceBundle( _sxs.getULocale( ) ) );
}
final Graphics2D g2d = (Graphics2D) ( (IDeviceRenderer) renderer ).getGraphicsContext( );
g2d.setFont( (java.awt.Font) _sxs.createFont( label.getCaption( )
.getFont( ) ) );
switch ( labelPosition & POSITION_MASK )
{
case ABOVE :
if ( ChartUtil.isShadowDefined( label ) )
{
showTopValue( renderer,
location,
label,
labelPosition,
true );
}
showTopValue( renderer, location, label, labelPosition, false );
break;
case BELOW :
if ( ChartUtil.isShadowDefined( label ) )
{
showBottomValue( renderer,
location,
label,
labelPosition,
true );
}
showBottomValue( renderer,
location,
label,
labelPosition,
false );
break;
case LEFT :
if ( ChartUtil.isShadowDefined( label ) )
{
showLeftValue( renderer,
location,
label,
labelPosition,
true );
}
showLeftValue( renderer, location, label, labelPosition, false );
break;
case RIGHT :
if ( ChartUtil.isShadowDefined( label ) )
{
showRightValue( renderer,
location,
label,
labelPosition,
true );
}
showRightValue( renderer, location, label, labelPosition, false );
break;
case INSIDE :
if ( ChartUtil.isShadowDefined( label ) )
{
showCenterValue( renderer, location, label, true );
}
showCenterValue( renderer, location, label, false );
break;
}
}
/**
*
* @param renderer
* @param boBlock
* @param taBlock
* @param label
*/
public final void renderTextInBlock( IDeviceRenderer renderer,
Bounds boBlock, TextAlignment taBlock, Label label )
throws ChartException
{
Text t = label.getCaption( );
String labelText = t.getValue( );
FontDefinition fontDef = t.getFont( );
ColorDefinition cdText = t.getColor( );
if ( cdText == null )
{
throw new ChartException( ChartDeviceExtensionPlugin.ID,
ChartException.RENDERING,
"exception.undefined.text.color", //$NON-NLS-1$
Messages.getResourceBundle( _sxs.getULocale( ) ) );
}
IDisplayServer dispServer = renderer.getDisplayServer( );
Graphics2D g2d = (Graphics2D) renderer.getGraphicsContext( );
g2d.setFont( (java.awt.Font) dispServer.createFont( fontDef ) );
label.getCaption( ).setValue( labelText );
BoundingBox boundBox = null;
try
{
boundBox = Methods.computeBox( dispServer, ABOVE, label, 0, 0 );
}
catch ( IllegalArgumentException uiex )
{
throw new ChartException( ChartDeviceExtensionPlugin.ID,
ChartException.RENDERING,
uiex );
}
if ( taBlock == null )
{
taBlock = AttributeFactory.eINSTANCE.createTextAlignment( );
taBlock.setHorizontalAlignment( HorizontalAlignment.CENTER_LITERAL );
taBlock.setVerticalAlignment( VerticalAlignment.CENTER_LITERAL );
}
HorizontalAlignment haBlock = taBlock.getHorizontalAlignment( );
VerticalAlignment vaBlock = taBlock.getVerticalAlignment( );
switch ( haBlock.getValue( ) )
{
case HorizontalAlignment.CENTER :
boundBox.setLeft( boBlock.getLeft( )
+ ( boBlock.getWidth( ) - boundBox.getWidth( ) )
/ 2 );
break;
case HorizontalAlignment.LEFT :
boundBox.setLeft( boBlock.getLeft( ) );
break;
case HorizontalAlignment.RIGHT :
boundBox.setLeft( boBlock.getLeft( )
+ boBlock.getWidth( )
- boundBox.getWidth( ) );
break;
}
switch ( vaBlock.getValue( ) )
{
case VerticalAlignment.TOP :
boundBox.setTop( boBlock.getTop( ) );
break;
case VerticalAlignment.CENTER :
boundBox.setTop( boBlock.getTop( )
+ ( boBlock.getHeight( ) - boundBox.getHeight( ) )
/ 2 );
break;
case VerticalAlignment.BOTTOM :
boundBox.setTop( boBlock.getTop( )
+ boBlock.getHeight( )
- boundBox.getHeight( ) );
break;
}
boundBox.setLeft( boundBox.getLeft( ) + boundBox.getHotPoint( ) );
if ( ChartUtil.isShadowDefined( label ) )
{
showTopValue( renderer,
LocationImpl.create( boundBox.getLeft( ), boundBox.getTop( )
+ boundBox.getHeight( ) ),
label,
0,
true );
}
showTopValue( renderer, LocationImpl.create( boundBox.getLeft( ),
boundBox.getTop( ) + boundBox.getHeight( ) ), label, 0, false );
}
private final void showLeftValue( IPrimitiveRenderer renderer,
Location location, Label label, int labelPosition, boolean bShadow )
{
Graphics2D g2d = (Graphics2D) ( (IDeviceRenderer) renderer ).getGraphicsContext( );
FontDefinition fontDef = label.getCaption( ).getFont( );
double dAngleInDegrees = fontDef.getRotation( );
if ( bShadow ) // UPDATE TO FALSE IF SHADOW COLOR UNDEFINED BUT SHADOW
// REQUESTED FOR
{
bShadow = label.getShadowColor( ) != null;
}
Color clrText = (Color) _sxs.getColor( label.getCaption( ).getColor( ) );
Color clrBackground = null;
if ( label.getBackground( ) != null )
{
clrBackground = (Color) _sxs.getColor( (ColorDefinition) label.getBackground( ) );
}
final double dAngleInRadians = ( ( -dAngleInDegrees * Math.PI ) / 180.0 );
final double dSineTheta = ( Math.sin( dAngleInRadians ) );
final double dCosTheta = ( Math.cos( dAngleInRadians ) );
final ITextMetrics textMetrics = new ChartTextMetrics( _sxs, label );
// Tune text position if needed. Location instance may be changed
location = adjustTextPosition( labelPosition,
location,
textMetrics,
dAngleInDegrees );
double dX = location.getX( ), dY = location.getY( );
try
{
final double dFullWidth = textMetrics.getFullWidth( );
final double dHeight = textMetrics.getHeight( );
final double dDescent = textMetrics.getDescent( );
final double dFullHeight = textMetrics.getFullHeight( );
double dXOffset = 0, dWidth = 0;
final int lineCount = textMetrics.getLineCount( );
final Insets insets = label.getInsets( )
.scaledInstance( _sxs.getDpiResolution( ) / 72d );
final double shadowness = 3 * _sxs.getDpiResolution( ) / 72d;
final boolean bEmptyText = "".equals( label.getCaption( ).getValue( ) ); //$NON-NLS-1$
ChartTextLayout textLayout;
double dYDiff = dY - dFullHeight;
final HorizontalAlignment hAlign = label.getCaption( )
.getFont( )
.getAlignment( )
.getHorizontalAlignment( );
final boolean bRightAligned = hAlign.getValue( ) == HorizontalAlignment.RIGHT;
final boolean bCenterAligned = hAlign.getValue( ) == HorizontalAlignment.CENTER;
double dRotateX = ( dX - dFullWidth );
double dRotateY = ( dY + dHeight / 2 );
dX -= dFullWidth;
dY += dHeight / 2;
if ( dAngleInDegrees == 0 )
{
double dYHalfOffset = ( dFullHeight + dHeight ) / 2d;
if ( bShadow ) // RENDER THE SHADOW
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dY - dYHalfOffset ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dY - dYHalfOffset )
+ shadowness
+ dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dY - dYHalfOffset ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dY - dYHalfOffset,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < lineCount; i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( i );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( dY
- dYHalfOffset
+ insets.getTop( )
+ dHeight
* ( i + 1 ) - dDescent ) );
}
}
// RENDER THE OUTLINE
renderOutline( renderer, label.getOutline( ), r2d );
}
}
// DRAW POSITIVE ANGLE (> 0)
else if ( dAngleInDegrees > 0 && dAngleInDegrees < 90 )
{
double dDeltaX = dFullWidth - dFullWidth * dCosTheta;
double dDeltaY = dFullWidth * dSineTheta + dHeight / 2;
dX += dDeltaX;
dY -= dDeltaY;
g2d.rotate( dAngleInRadians, dRotateX + dDeltaX, dRotateY
- dDeltaY );
if ( bShadow )
{
// RENDER THE SHADOW
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dYDiff ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dYDiff ) + shadowness + dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dYDiff ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dYDiff,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < textMetrics.getLineCount( ); i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( lineCount
- i
- 1 );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( ( ( dY - dDescent ) - ( dHeight * i ) ) - insets.getBottom( ) ) );
}
}
// RENDER THE OUTLINE
renderOutline( renderer, label.getOutline( ), r2d );
}
g2d.rotate( -dAngleInRadians, dRotateX + dDeltaX, dRotateY
- dDeltaY );
}
// DRAW NEGATIVE ANGLE (< 0)
else if ( dAngleInDegrees < 0 && dAngleInDegrees > -90 )
{
double dDeltaX = dFullWidth
- dFullWidth
* dCosTheta
- dHeight
* dSineTheta;
double dDeltaY = dFullWidth
* dSineTheta
+ dHeight
/ 2
- dHeight
* dCosTheta;
dX += dDeltaX;
dY -= dDeltaY;
g2d.rotate( dAngleInRadians, dRotateX + dDeltaX, dRotateY
- dDeltaY );
if ( bShadow )
{
// RENDER THE SHADOW
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dY - dHeight ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dY - dHeight ) + shadowness + dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dY - dHeight ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dY - dHeight,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND FILL
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < lineCount; i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( i );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( ( ( dY - dDescent ) + ( dHeight * i ) ) + insets.getTop( ) ) );
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
g2d.rotate( -dAngleInRadians, dRotateX + dDeltaX, dRotateY
- dDeltaY );
}
// VERTICALLY UP
else if ( dAngleInDegrees == 90 )
{
double dDeltaX = dFullWidth;
double dDeltaY = ( dFullWidth - dHeight ) / 2;
dX += dDeltaX;
dY += dDeltaY;
g2d.rotate( dAngleInRadians, dX, dY );
if ( bShadow )
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dYDiff ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dYDiff ) + shadowness + dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dYDiff ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dYDiff,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND FILL
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < lineCount; i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( i );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( ( ( dY - dDescent ) - ( dHeight * ( lineCount
- i - 1 ) ) ) + insets.getTop( ) ) );
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
g2d.rotate( -dAngleInRadians, dX, dY );
}
// VERTICALLY DOWN
else if ( dAngleInDegrees == -90 )
{
double dDeltaX = dFullWidth - dHeight;
double dDeltaY = ( dFullWidth + dHeight ) / 2;
dX += dDeltaX;
dY -= dDeltaY;
g2d.rotate( dAngleInRadians, dX, dY );
if ( bShadow )
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dYDiff ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dYDiff ) + shadowness + dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dYDiff ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dY - dHeight,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND FILL
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < lineCount; i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( i );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( ( ( dY - dDescent ) + ( dHeight * i ) ) + insets.getTop( ) ) );
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
g2d.rotate( -dAngleInRadians, dX, dY );
}
}
finally
{
textMetrics.dispose( );
}
}
private final void showRightValue( IPrimitiveRenderer renderer,
Location location, Label label, int labelPosition, boolean bShadow )
{
Graphics2D g2d = (Graphics2D) ( (IDeviceRenderer) renderer ).getGraphicsContext( );
FontDefinition fontDef = label.getCaption( ).getFont( );
double dAngleInDegrees = fontDef.getRotation( );
if ( bShadow ) // UPDATE TO FALSE IF SHADOW COLOR UNDEFINED BUT SHADOW
// REQUESTED FOR
{
bShadow = label.getShadowColor( ) != null;
}
Color clrText = (Color) _sxs.getColor( label.getCaption( ).getColor( ) );
Color clrBackground = null;
if ( label.getBackground( ) != null )
{
clrBackground = (Color) _sxs.getColor( (ColorDefinition) label.getBackground( ) );
}
final ITextMetrics textMetrics = new ChartTextMetrics( _sxs, label );
// Tune text position if needed. Location instance may be changed
location = adjustTextPosition( labelPosition,
location,
textMetrics,
dAngleInDegrees );
double dX = location.getX( ), dY = location.getY( );
// dX += 2;
dY += 1;
try
{
final double dFullWidth = textMetrics.getFullWidth( );
final double dHeight = textMetrics.getHeight( );
final double dDescent = textMetrics.getDescent( );
final double dFullHeight = textMetrics.getFullHeight( );
double dXOffset = 0, dWidth = 0;
final int lineCount = textMetrics.getLineCount( );
final Insets insets = label.getInsets( )
.scaledInstance( _sxs.getDpiResolution( ) / 72d );
final double shadowness = 3 * _sxs.getDpiResolution( ) / 72d;
final boolean bEmptyText = "".equals( label.getCaption( ).getValue( ) ); //$NON-NLS-1$
ChartTextLayout textLayout;
double dYDiff = dY - dHeight;
final HorizontalAlignment hAlign = label.getCaption( )
.getFont( )
.getAlignment( )
.getHorizontalAlignment( );
final boolean bRightAligned = hAlign.getValue( ) == HorizontalAlignment.RIGHT;
final boolean bCenterAligned = hAlign.getValue( ) == HorizontalAlignment.CENTER;
double dAngleInRadians = ( ( -dAngleInDegrees * Math.PI ) / 180.0 );
int iRotateX = (int) dX;
int iRotateY = (int) ( dY + dHeight / 2 );
dY += dHeight / 2;
// HORIZONTAL TEXT
if ( dAngleInDegrees == 0 )
{
double dYHalfOffset = ( dFullHeight + dHeight ) / 2d;
if ( bShadow ) // RENDER THE SHADOW
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dY - dYHalfOffset ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dY - dYHalfOffset )
+ shadowness
+ dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dY - dYHalfOffset ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dY - dYHalfOffset,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND FILL
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < lineCount; i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( i );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( dY
- dYHalfOffset
+ insets.getTop( )
+ dHeight
* ( i + 1 ) - dDescent )
// (float)(((dY - dDescent) - ((lineCount - i) *
// dHeight - (lineCount + 1)
// *
// dHeight/2))
// + insets.getTop())
);
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
}
// DRAW POSITIVE ANGLE (> 0)
else if ( dAngleInDegrees > 0 && dAngleInDegrees < 90 )
{
double dDeltaX = dHeight * Math.sin( dAngleInRadians );
double dDeltaY = dHeight
* Math.cos( dAngleInRadians )
- dHeight
/ 2;
dX -= dDeltaX;
dY += dDeltaY;
g2d.rotate( dAngleInRadians, iRotateX - dDeltaX, iRotateY
+ dDeltaY );
if ( bShadow ) // RENDER THE SHADOW
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dYDiff ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dYDiff ) + shadowness + dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dYDiff ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
( dYDiff ),
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < lineCount; i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( i );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( ( dY - dDescent + dHeight * i ) + insets.getTop( ) ) );
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
// UNDO THE 'ROTATED' STATE OF THE GRAPHICS CONTEXT
g2d.rotate( -dAngleInRadians, iRotateX - dDeltaX, iRotateY
+ dDeltaY );
// crossHairs(g2d, (int)dX, (int)dY);
}
// DRAW NEGATIVE ANGLE (< 0)
else if ( dAngleInDegrees < 0 && dAngleInDegrees > -90 )
{
double dDeltaY = -dHeight / 2;
dY += dDeltaY;
g2d.rotate( dAngleInRadians, iRotateX, iRotateY + dDeltaY );
if ( bShadow ) // RENDER THE SHADOW
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dY - dFullHeight ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dY - dFullHeight )
+ shadowness
+ dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dY - dFullHeight ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dY - dFullHeight,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < lineCount; i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( i );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( ( dY - dDescent - dHeight
* ( lineCount - i - 1 ) ) - insets.getBottom( ) ) );
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
// UNDO THE 'ROTATED' STATE OF THE GRAPHICS CONTEXT
g2d.rotate( -dAngleInRadians, iRotateX, iRotateY + dDeltaY );
// crossHairs(g2d, (int)dX, (int)dY);
}
// VERTICALLY UP
else if ( dAngleInDegrees == 90 )
{
double dDeltaX = dHeight;
double dDeltaY = ( dFullWidth - dHeight ) / 2;
dX += dDeltaX;
dY += dDeltaY;
g2d.rotate( dAngleInRadians, dX, dY );
if ( bShadow ) // RENDER THE SHADOW
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dYDiff ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dYDiff ) + shadowness + dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dYDiff ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dYDiff,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < lineCount; i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( i );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( ( dY - dDescent + dHeight * i ) + insets.getTop( ) ) );
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
// UNDO THE 'ROTATED' STATE OF THE GRAPHICS CONTEXT
g2d.rotate( -dAngleInRadians, dX, dY );
// crossHairs(g2d, (int)dX, (int)dY);
}
// VERTICALLY DOWN
else if ( dAngleInDegrees == -90 )
{
double dDeltaX = 0;
double dDeltaY = ( dFullWidth + dHeight ) / 2;
dX += dDeltaX;
dY -= dDeltaY;
g2d.rotate( dAngleInRadians, dX, dY );
if ( bShadow ) // RENDER THE SHADOW
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dYDiff ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dYDiff ) + shadowness + dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dYDiff ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dYDiff,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < lineCount; i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( i );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( ( dY - dDescent + dHeight * i ) + insets.getTop( ) ) );
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
// UNDO THE 'ROTATED' STATE OF THE GRAPHICS CONTEXT
g2d.rotate( -dAngleInRadians, dX, dY );
// crossHairs(g2d, (int)dX, (int)dY);
}
}
finally
{
textMetrics.dispose( );
}
}
private final void showBottomValue( IPrimitiveRenderer renderer,
Location location, Label label, int labelPosition, boolean bShadow )
{
Graphics2D g2d = (Graphics2D) ( (IDeviceRenderer) renderer ).getGraphicsContext( );
FontDefinition fontDef = label.getCaption( ).getFont( );
// Color clrShadow = bShadow ? (Color)
// _sxs.getColor(label.getShadowColor()) : null;
double dAngleInDegrees = fontDef.getRotation( );
Color clrText = (Color) _sxs.getColor( label.getCaption( ).getColor( ) );
Color clrBackground = null;
if ( label.getBackground( ) != null )
{
clrBackground = (Color) _sxs.getColor( (ColorDefinition) label.getBackground( ) );
}
double dAngleInRadians = ( ( -dAngleInDegrees * Math.PI ) / 180.0 );
final ITextMetrics textMetrics = new ChartTextMetrics( _sxs, label );
// Tune text position if needed. Location instance may be changed
location = adjustTextPosition( labelPosition,
location,
textMetrics,
dAngleInDegrees );
double dX = location.getX( ), dY = location.getY( );
try
{
final double dFullWidth = textMetrics.getFullWidth( );
final double dHeight = textMetrics.getHeight( );
final double dDescent = textMetrics.getDescent( );
final double dFullHeight = textMetrics.getFullHeight( );
double dXOffset = 0, dWidth = 0;
final int lineCount = textMetrics.getLineCount( );
final Insets insets = label.getInsets( )
.scaledInstance( _sxs.getDpiResolution( ) / 72d );
final double shadowness = 3 * _sxs.getDpiResolution( ) / 72d;
final boolean bEmptyText = "".equals( label.getCaption( ).getValue( ) ); //$NON-NLS-1$
ChartTextLayout textLayout;
final HorizontalAlignment hAlignment = label.getCaption( )
.getFont( )
.getAlignment( )
.getHorizontalAlignment( );
final boolean bRightAligned = hAlignment.getValue( ) == HorizontalAlignment.RIGHT;
final boolean bCenterAligned = hAlignment.getValue( ) == HorizontalAlignment.CENTER;
dX -= dFullWidth / 2;
dY += dHeight;
// HORIZONTAL TEXT
if ( dAngleInDegrees == 0 )
{
if ( bShadow ) // RENDER THE SHADOW
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dY - dHeight ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dY - dHeight ) + shadowness + dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dY - dHeight ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dY - dHeight,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < lineCount; i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( i );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( dY - dDescent + dHeight * i + insets.getTop( ) ) );
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
// crossHairs(g2d, (int)dX, (int)dY);
}
// DRAW IT AT A POSITIVE ANGLE
else if ( dAngleInDegrees > 0 && dAngleInDegrees < 90 )
{
double dSineTheta = Math.abs( Math.sin( dAngleInRadians ) );
double dCosTheta = Math.abs( Math.cos( dAngleInRadians ) );
double dDeltaX = dFullWidth
* dCosTheta
- dHeight
* dSineTheta
- dFullWidth
/ 2.0;
double dDeltaY = dHeight
* dCosTheta
+ dFullWidth
* dSineTheta
- dHeight;
dX -= dDeltaX;
dY += dDeltaY;
g2d.rotate( dAngleInRadians, dX, dY );
if ( bShadow ) // RENDER THE SHADOW
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dY - dHeight ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dY - dHeight ) + shadowness + dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dY - dHeight ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dY - dHeight,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < lineCount; i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( i );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( dY - dDescent + dHeight * i + insets.getTop( ) ) );
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
// UNDO THE 'ROTATED' STATE OF THE GRAPHICS CONTEXT
g2d.rotate( -dAngleInRadians, dX, dY );
}
// DRAW IT AT A NEGATIVE ANGLE
else if ( dAngleInDegrees < 0 && dAngleInDegrees > -90 )
{
dX += dFullWidth / 2;
g2d.rotate( dAngleInRadians, dX, dY - dHeight );
if ( bShadow ) // RENDER THE SHADOW
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dY - dHeight ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dY - dHeight ) + shadowness + dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dY - dHeight ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dY - dHeight,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < lineCount; i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( i );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( dY - dDescent + dHeight * i + insets.getTop( ) ) );
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
// UNDO THE 'ROTATED' STATE OF THE GRAPHICS CONTEXT
g2d.rotate( -dAngleInRadians, dX, dY - dHeight );
}
// VERTICALLY UP
else if ( dAngleInDegrees == 90 )
{
double dYHalfOffset = ( dFullHeight + dHeight ) / 2.0;
double dDeltaX = ( dFullWidth + dHeight ) / 2;
double dDeltaY = ( dFullWidth - dHeight );
dX += dDeltaX;
dY += dDeltaY;
g2d.rotate( dAngleInRadians, dX, dY );
if ( bShadow ) // RENDER THE SHADOW
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dY - dYHalfOffset ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dY - dYHalfOffset )
+ shadowness
+ dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dY - dYHalfOffset ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dY - dYHalfOffset,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < lineCount; i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( i );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( ( ( dY - dDescent ) - ( ( lineCount - i )
* dHeight - ( lineCount + 1 )
* dHeight
/ 2 ) ) + insets.getTop( ) ) );
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
// UNDO THE 'ROTATED' STATE OF THE GRAPHICS CONTEXT
g2d.rotate( -dAngleInRadians, dX, dY );
// crossHairs(g2d, (int)dX, (int)dY);
}
// VERTICALLY DOWN
else if ( dAngleInDegrees == -90 )
{
dX += dFullWidth / 2;
dY -= dHeight;
double dYHalfOffset = ( dFullHeight + dHeight ) / 2d;
double dDeltaX = dYHalfOffset - dFullHeight / 2d;
dX -= dDeltaX;
g2d.rotate( dAngleInRadians, dX, dY );
if ( bShadow ) // RENDER THE SHADOW
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dY - dYHalfOffset ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dY - dYHalfOffset )
+ shadowness
+ dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dY - dYHalfOffset ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dY - dYHalfOffset,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < lineCount; i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( i );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( ( dY - dDescent )
- dYHalfOffset
+ dHeight
* ( i + 1 ) + insets.getTop( ) ) );
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
// UNDO THE 'ROTATED' STATE OF THE GRAPHICS CONTEXT
g2d.rotate( -dAngleInRadians, dX, dY );
}
}
finally
{
textMetrics.dispose( );
}
}
private final void showTopValue( IPrimitiveRenderer renderer,
Location location, Label label, int labelPosition, boolean bShadow )
{
final Graphics2D g2d = (Graphics2D) ( (IDeviceRenderer) renderer ).getGraphicsContext( );
final FontDefinition fontDef = label.getCaption( ).getFont( );
// final Color clrShadow = bShadow ? (Color)
// _sxs.getColor(la.getShadowColor()) : null;
final double dAngleInDegrees = fontDef.getRotation( );
final Color clrText = (Color) _sxs.getColor( label.getCaption( )
.getColor( ) );
Color clrBackground = null;
if ( label.getBackground( ) != null )
{
clrBackground = (Color) _sxs.getColor( (ColorDefinition) label.getBackground( ) );
}
double dAngleInRadians = ( ( -dAngleInDegrees * Math.PI ) / 180.0 );
final ITextMetrics textMetrics = new ChartTextMetrics( _sxs, label );
// Tune text position if needed. Location instance may be changed
location = adjustTextPosition( labelPosition,
location,
textMetrics,
dAngleInDegrees );
double dX = location.getX( ), dY = location.getY( );
try
{
final double dFullWidth = textMetrics.getFullWidth( );
final double dHeight = textMetrics.getHeight( );
final double dDescent = textMetrics.getDescent( );
final double dFullHeight = textMetrics.getFullHeight( );
double dXOffset = 0, dWidth = 0;
final int lineCount = textMetrics.getLineCount( );
final Insets insets = label.getInsets( )
.scaledInstance( _sxs.getDpiResolution( ) / 72d );
final double shadowness = 3 * _sxs.getDpiResolution( ) / 72d;
final boolean bEmptyText = "".equals( label.getCaption( ).getValue( ) ); //$NON-NLS-1$
ChartTextLayout textLayout;
final HorizontalAlignment hAlignment = label.getCaption( )
.getFont( )
.getAlignment( )
.getHorizontalAlignment( );
final boolean bRightAligned = hAlignment.getValue( ) == HorizontalAlignment.RIGHT;
final boolean bCenterAligned = hAlignment.getValue( ) == HorizontalAlignment.CENTER;
dX -= dFullWidth / 2;
// HORIZONTAL TEXT
if ( dAngleInDegrees == 0 )
{
if ( bShadow ) // RENDER THE SHADOW
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dY - dFullHeight ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dY - dFullHeight )
+ shadowness
+ dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dY - dFullHeight ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
( dY - dFullHeight ),
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < textMetrics.getLineCount( ); i++ )
{
// textLayout = new
// TextLayout(textMetrics.getLine(lineCount - i -
// 1),
// g2d.getFont(), g2d.getFontRenderContext());
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( lineCount
- i
- 1 );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( dY - dDescent - dHeight * i - insets.getBottom( ) ) );
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
// crossHairs(g2d, (int)dX, (int)dY);
}
// DRAW IT AT A POSITIVE ANGLE
else if ( dAngleInDegrees > 0 && dAngleInDegrees < 90 )
{
double dDeltaX = dFullWidth / 2;
dX += dDeltaX;
g2d.rotate( dAngleInRadians, dX, dY );
if ( bShadow ) // RENDER THE SHADOW
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dY - dFullHeight ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dY - dFullHeight )
+ shadowness
+ dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dY - dFullHeight ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
( dY - dFullHeight ),
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < textMetrics.getLineCount( ); i++ )
{
textLayout = new ChartTextLayout( textMetrics.getLine( lineCount
- i
- 1 ),
g2d.getFont( ).getAttributes( ),
g2d.getFontRenderContext( ) );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( dY - dDescent - dHeight * i - insets.getBottom( ) ) );
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
// UNDO THE 'ROTATED' STATE OF THE GRAPHICS CONTEXT
g2d.rotate( -dAngleInRadians, dX, dY );
// crossHairs(g2d, (int)dX, (int)dY);
}
// DRAW IT AT A NEGATIVE ANGLE
else if ( dAngleInDegrees < 0 && dAngleInDegrees > -90 )
{
double dCosTheta = Math.abs( Math.cos( dAngleInRadians ) );
double dSineTheta = Math.abs( Math.sin( dAngleInRadians ) );
dX -= dFullWidth / 2 - ( dFullWidth - dFullWidth * dCosTheta );
dY -= dFullWidth * dSineTheta;
g2d.rotate( dAngleInRadians, dX, dY );
if ( bShadow ) // RENDER THE SHADOW
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dY - dFullHeight ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dY - dFullHeight )
+ shadowness
+ dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dY - dFullHeight ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dY - dFullHeight,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < textMetrics.getLineCount( ); i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( lineCount
- i
- 1 );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( dY - dDescent - dHeight * i - insets.getBottom( ) ) );
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
// UNDO THE 'ROTATED' STATE OF THE GRAPHICS CONTEXT
g2d.rotate( -dAngleInRadians, dX, dY );
/*
* final RotatedRectangle rr = computePolygon(IConstants.ABOVE,
* label, location.getX(), location.getY());
* g2d.setColor(Color.blue); g2d.draw(rr); final BoundingBox bb =
* computeBox(IConstants.ABOVE, label, location.getX(),
* location.getY()); renderBox(g2d, bb, Color.black, null);
*/
// crossHairs(g2d, (int)dX, (int)dY);
}
// VERTICALLY UP
else if ( dAngleInDegrees == 90 )
{
double dYHalfOffset = ( dFullHeight + dHeight ) / 2.0;
double dDeltaX = ( dFullWidth + dHeight ) / 2;
dX += dDeltaX;
g2d.rotate( dAngleInRadians, dX, dY );
if ( bShadow ) // RENDER THE SHADOW
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dY - dYHalfOffset ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dY - dYHalfOffset )
+ shadowness
+ dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dY - dYHalfOffset ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dY - dYHalfOffset,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < textMetrics.getLineCount( ); i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( i );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( ( ( dY - dDescent ) - ( ( textMetrics.getLineCount( ) - i )
* dHeight - ( lineCount + 1 )
* dHeight
/ 2 ) ) + insets.getTop( ) ) );
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
// UNDO THE 'ROTATED' STATE OF THE GRAPHICS CONTEXT
g2d.rotate( -dAngleInRadians, dX, dY );
// crossHairs(g2d, (int)dX, (int)dY);
}
// VERTICALLY DOWN
else if ( dAngleInDegrees == -90 )
{
double dYHalfOffset = ( dFullHeight + dHeight ) / 2.0;
double dDeltaX = ( dFullWidth - dHeight ) / 2;
double dDeltaY = dFullWidth;
dX += dDeltaX;
dY -= dDeltaY;
g2d.rotate( dAngleInRadians, dX, dY );
if ( bShadow ) // RENDER THE SHADOW
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dY - dYHalfOffset ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dY - dYHalfOffset )
+ shadowness
+ dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dY - dYHalfOffset ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dY - dYHalfOffset,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < textMetrics.getLineCount( ); i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( i );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( ( ( dY - dDescent ) - ( ( textMetrics.getLineCount( ) - i )
* dHeight - ( lineCount + 1 )
* dHeight
/ 2 ) ) + insets.getTop( ) ) );
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
// UNDO THE 'ROTATED' STATE OF THE GRAPHICS CONTEXT
g2d.rotate( -dAngleInRadians, dX, dY );
// crossHairs(g2d, (int)dX, (int)dY);
}
}
finally
{
textMetrics.dispose( );
}
}
/**
*
* @param g2d
* @param f
* @param dX
* @param dY
* @param sText
* @param iAngleInDegrees
*/
private final void showCenterValue( IPrimitiveRenderer renderer,
Location location, Label label, boolean bShadow )
{
Graphics2D g2d = (Graphics2D) ( (IDeviceRenderer) renderer ).getGraphicsContext( );
double dX = location.getX( ), dY = location.getY( );
FontDefinition fontDef = label.getCaption( ).getFont( );
double dAngleInDegrees = fontDef.getRotation( );
if ( bShadow ) // UPDATE TO FALSE IF SHADOW COLOR UNDEFINED BUT SHADOW
// REQUESTED FOR
{
bShadow = label.getShadowColor( ) != null;
}
Color clrText = (Color) _sxs.getColor( label.getCaption( ).getColor( ) );
Color clrBackground = null;
if ( label.getBackground( ) != null )
{
clrBackground = (Color) _sxs.getColor( (ColorDefinition) label.getBackground( ) );
}
final double dAngleInRadians = ( ( -dAngleInDegrees * Math.PI ) / 180.0 );
final double dSineTheta = ( Math.sin( dAngleInRadians ) );
final double dCosTheta = ( Math.cos( dAngleInRadians ) );
final ITextMetrics textMetrics = _sxs.getTextMetrics( label );
try
{
final double dFullWidth = textMetrics.getFullWidth( );
final double dHeight = textMetrics.getHeight( );
final double dDescent = textMetrics.getDescent( );
final double dFullHeight = textMetrics.getFullHeight( );
double dXOffset = 0, dWidth = 0;
final int lineCount = textMetrics.getLineCount( );
final Insets insets = label.getInsets( )
.scaledInstance( _sxs.getDpiResolution( ) / 72d );
final double shadowness = 3 * _sxs.getDpiResolution( ) / 72d;
// Swing is not friendly to empty string, check and skip for this
// case
final boolean bEmptyText = "".equals( label.getCaption( ).getValue( ) ); //$NON-NLS-1$
ChartTextLayout textLayout;
final HorizontalAlignment hAlign = label.getCaption( )
.getFont( )
.getAlignment( )
.getHorizontalAlignment( );
final boolean bRightAligned = hAlign.getValue( ) == HorizontalAlignment.RIGHT;
final boolean bCenterAligned = hAlign.getValue( ) == HorizontalAlignment.CENTER;
double dRotateX = dX;
double dRotateY = dY;
dX -= dFullWidth / 2;
dY += dHeight / 2;
if ( dAngleInDegrees == 0 )
{
double dYHalfOffset = ( dFullHeight + dHeight ) / 2d;
if ( bShadow ) // RENDER THE SHADOW
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dY - dYHalfOffset ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dY - dYHalfOffset )
+ shadowness
+ dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dY - dYHalfOffset ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dY - dYHalfOffset,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < lineCount; i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( i );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( dY
- dYHalfOffset
+ insets.getTop( )
+ dHeight
* ( i + 1 ) - dDescent ) );
}
}
// RENDER THE OUTLINE
renderOutline( renderer, label.getOutline( ), r2d );
}
}
// DRAW POSITIVE ANGLE (> 0)
else if ( dAngleInDegrees > 0 && dAngleInDegrees < 90 )
{
double dDeltaX = dFullWidth - dFullWidth * dCosTheta;
double dDeltaY = dFullWidth * dSineTheta + dHeight / 2;
dX += dDeltaX;
dY -= dDeltaY;
g2d.rotate( dAngleInRadians, dRotateX + dDeltaX, dRotateY
- dDeltaY );
if ( bShadow )
{
// RENDER THE SHADOW
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dY - dFullHeight ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dY - dFullHeight )
+ shadowness
+ dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dY - dFullHeight ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dY - dFullHeight,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < textMetrics.getLineCount( ); i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( lineCount
- i
- 1 );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( ( ( dY - dDescent ) - ( dHeight * i ) ) - insets.getBottom( ) ) );
}
}
// RENDER THE OUTLINE
renderOutline( renderer, label.getOutline( ), r2d );
}
g2d.rotate( -dAngleInRadians, dRotateX + dDeltaX, dRotateY
- dDeltaY );
}
// DRAW NEGATIVE ANGLE (< 0)
else if ( dAngleInDegrees < 0 && dAngleInDegrees > -90 )
{
double dDeltaX = dFullWidth
- dFullWidth
* dCosTheta
- dHeight
* dSineTheta;
double dDeltaY = dFullWidth
* dSineTheta
+ dHeight
/ 2
- dHeight
* dCosTheta;
dX += dDeltaX;
dY -= dDeltaY;
g2d.rotate( dAngleInRadians, dRotateX + dDeltaX, dRotateY
- dDeltaY );
if ( bShadow )
{
// RENDER THE SHADOW
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dY - dHeight ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dY - dHeight ) + shadowness + dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dY - dHeight ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dY - dHeight,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND FILL
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < lineCount; i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( i );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( ( ( dY - dDescent ) + ( dHeight * i ) ) + insets.getTop( ) ) );
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
g2d.rotate( -dAngleInRadians, dRotateX + dDeltaX, dRotateY
- dDeltaY );
}
// VERTICALLY UP
else if ( dAngleInDegrees == 90 )
{
double dDeltaX = dFullWidth;
double dDeltaY = ( dFullWidth - dHeight ) / 2;
dX += dDeltaX;
dY += dDeltaY;
g2d.rotate( dAngleInRadians, dX, dY );
if ( bShadow )
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dY - dFullHeight ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dY - dFullHeight )
+ shadowness
+ dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dY - dFullHeight ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dY - dFullHeight,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND FILL
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < lineCount; i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( i );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( ( ( dY - dDescent ) - ( dHeight * ( lineCount
- i - 1 ) ) ) + insets.getTop( ) ) );
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
g2d.rotate( -dAngleInRadians, dX, dY );
}
// VERTICALLY DOWN
else if ( dAngleInDegrees == -90 )
{
double dDeltaX = dFullWidth - dHeight;
double dDeltaY = ( dFullWidth + dHeight ) / 2;
dX += dDeltaX;
dY -= dDeltaY;
g2d.rotate( dAngleInRadians, dX, dY );
if ( bShadow )
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dY - dFullHeight ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dY - dFullHeight )
+ shadowness
+ dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dY - dFullHeight ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dY - dHeight,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND FILL
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < lineCount; i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( i );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( ( ( dY - dDescent ) + ( dHeight * i ) ) + insets.getTop( ) ) );
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
g2d.rotate( -dAngleInRadians, dX, dY );
}
}
finally
{
textMetrics.dispose( );
}
}
// private static final void renderBox(Graphics2D g2d, BoundingBox bb, Color
// cFG, Color cBG)
// {
// if (cBG != null)
// {
// g2d.setColor(cBG);
// g2d.fillRect((int) bb.getLeft(), (int) bb.getTop(), (int) bb.getWidth(),
// (int) bb.getHeight());
// }
// g2d.setColor(cFG);
// g2d.drawRect((int) bb.getLeft(), (int) bb.getTop(), (int) bb.getWidth(),
// (int) bb.getHeight());
// }
private final void renderOutline( IPrimitiveRenderer renderer,
LineAttributes lineAttribs, Rectangle2D.Double rect )
{
if ( lineAttribs != null
&& lineAttribs.isVisible( )
&& lineAttribs.getColor( ) != null )
{
Graphics2D g2d = (Graphics2D) ( (IDeviceRenderer) renderer ).getGraphicsContext( );
Stroke sPrevious = null;
final ColorDefinition cd = lineAttribs.getColor( );
final Stroke sCurrent = ( (SwingRendererImpl) renderer ).getCachedStroke( lineAttribs );
if ( sCurrent != null ) // SOME STROKE DEFINED?
{
sPrevious = g2d.getStroke( );
g2d.setStroke( sCurrent );
}
g2d.setColor( (Color) _sxs.getColor( cd ) );
g2d.draw( rect );
// g2d.setNoFillColor( g2d.getCurrentElement( ) );
if ( sPrevious != null ) // RESTORE PREVIOUS STROKE
{
g2d.setStroke( sPrevious );
}
}
}
}
| chart/org.eclipse.birt.chart.device.extension/src/org/eclipse/birt/chart/device/util/ChartTextRenderer.java | /*******************************************************************************
* Copyright (c) 2008 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.chart.device.util;
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Stroke;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import org.eclipse.birt.chart.computation.BoundingBox;
import org.eclipse.birt.chart.computation.Methods;
import org.eclipse.birt.chart.device.IDeviceRenderer;
import org.eclipse.birt.chart.device.IDisplayServer;
import org.eclipse.birt.chart.device.IPrimitiveRenderer;
import org.eclipse.birt.chart.device.ITextMetrics;
import org.eclipse.birt.chart.device.TextRendererAdapter;
import org.eclipse.birt.chart.device.extension.i18n.Messages;
import org.eclipse.birt.chart.device.plugin.ChartDeviceExtensionPlugin;
import org.eclipse.birt.chart.device.swing.SwingRendererImpl;
import org.eclipse.birt.chart.exception.ChartException;
import org.eclipse.birt.chart.model.attribute.AttributeFactory;
import org.eclipse.birt.chart.model.attribute.Bounds;
import org.eclipse.birt.chart.model.attribute.ColorDefinition;
import org.eclipse.birt.chart.model.attribute.FontDefinition;
import org.eclipse.birt.chart.model.attribute.HorizontalAlignment;
import org.eclipse.birt.chart.model.attribute.Insets;
import org.eclipse.birt.chart.model.attribute.LineAttributes;
import org.eclipse.birt.chart.model.attribute.Location;
import org.eclipse.birt.chart.model.attribute.Text;
import org.eclipse.birt.chart.model.attribute.TextAlignment;
import org.eclipse.birt.chart.model.attribute.VerticalAlignment;
import org.eclipse.birt.chart.model.attribute.impl.LocationImpl;
import org.eclipse.birt.chart.model.component.Label;
import org.eclipse.birt.chart.util.ChartUtil;
public class ChartTextRenderer extends TextRendererAdapter
{
/**
*
*/
public ChartTextRenderer( IDisplayServer dispServer )
{
super( dispServer );
}
/**
* This method renders the 'shadow' at an offset from the text 'rotated
* rectangle' subsequently rendered.
*
* @param renderer
* @param labelPosition
* The position of the label w.r.t. the location specified by
* 'location'
* @param location
* The location (specified as a 2d point) where the text is to be
* rendered
* @param label
* The chart model structure containing the encapsulated text
* (and attributes) to be rendered
*/
public final void renderShadowAtLocation( IPrimitiveRenderer renderer,
int labelPosition, Location location, Label label )
throws ChartException
{
final ColorDefinition cdShadow = label.getShadowColor( );
if ( cdShadow == null )
{
throw new ChartException( ChartDeviceExtensionPlugin.ID,
ChartException.RENDERING,
"exception.undefined.shadow.color", //$NON-NLS-1$
Messages.getResourceBundle( _sxs.getULocale( ) ) );
}
final ChartGraphics2D g2d = (ChartGraphics2D) ( (IDeviceRenderer) renderer ).getGraphicsContext( );
g2d.setFont( (java.awt.Font) _sxs.createFont( label.getCaption( )
.getFont( ) ) );
switch ( labelPosition & POSITION_MASK )
{
case ABOVE :
showTopValue( renderer, location, label, labelPosition, true );
break;
case BELOW :
showBottomValue( renderer, location, label, labelPosition, true );
break;
case LEFT :
showLeftValue( renderer, location, label, labelPosition, true );
break;
case RIGHT :
showRightValue( renderer, location, label, labelPosition, true );
break;
}
}
/**
*
* @param renderer
* @param labelPosition
* IConstants. LEFT, RIGHT, ABOVE or BELOW
* @param location
* POINT WHERE THE CORNER OF THE ROTATED RECTANGLE (OR EDGE
* CENTERED) IS RENDERED
* @param label
* @throws RenderingException
*/
public final void renderTextAtLocation( IPrimitiveRenderer renderer,
int labelPosition, Location location, Label label )
throws ChartException
{
final ColorDefinition colorDef = label.getCaption( ).getColor( );
if ( colorDef == null )
{
throw new ChartException( ChartDeviceExtensionPlugin.ID,
ChartException.RENDERING,
"exception.undefined.text.color", //$NON-NLS-1$
Messages.getResourceBundle( _sxs.getULocale( ) ) );
}
final ChartGraphics2D g2d = (ChartGraphics2D) ( (IDeviceRenderer) renderer ).getGraphicsContext( );
g2d.setFont( (java.awt.Font) _sxs.createFont( label.getCaption( )
.getFont( ) ) );
switch ( labelPosition & POSITION_MASK )
{
case ABOVE :
if ( ChartUtil.isShadowDefined( label ) )
{
showTopValue( renderer,
location,
label,
labelPosition,
true );
}
showTopValue( renderer, location, label, labelPosition, false );
break;
case BELOW :
if ( ChartUtil.isShadowDefined( label ) )
{
showBottomValue( renderer,
location,
label,
labelPosition,
true );
}
showBottomValue( renderer,
location,
label,
labelPosition,
false );
break;
case LEFT :
if ( ChartUtil.isShadowDefined( label ) )
{
showLeftValue( renderer,
location,
label,
labelPosition,
true );
}
showLeftValue( renderer, location, label, labelPosition, false );
break;
case RIGHT :
if ( ChartUtil.isShadowDefined( label ) )
{
showRightValue( renderer,
location,
label,
labelPosition,
true );
}
showRightValue( renderer, location, label, labelPosition, false );
break;
case INSIDE :
if ( ChartUtil.isShadowDefined( label ) )
{
showCenterValue( renderer, location, label, true );
}
showCenterValue( renderer, location, label, false );
break;
}
}
/**
*
* @param renderer
* @param boBlock
* @param taBlock
* @param label
*/
public final void renderTextInBlock( IDeviceRenderer renderer,
Bounds boBlock, TextAlignment taBlock, Label label )
throws ChartException
{
Text t = label.getCaption( );
String labelText = t.getValue( );
FontDefinition fontDef = t.getFont( );
ColorDefinition cdText = t.getColor( );
if ( cdText == null )
{
throw new ChartException( ChartDeviceExtensionPlugin.ID,
ChartException.RENDERING,
"exception.undefined.text.color", //$NON-NLS-1$
Messages.getResourceBundle( _sxs.getULocale( ) ) );
}
IDisplayServer dispServer = renderer.getDisplayServer( );
ChartGraphics2D g2d = (ChartGraphics2D) renderer.getGraphicsContext( );
g2d.setFont( (java.awt.Font) dispServer.createFont( fontDef ) );
label.getCaption( ).setValue( labelText );
BoundingBox boundBox = null;
try
{
boundBox = Methods.computeBox( dispServer, ABOVE, label, 0, 0 );
}
catch ( IllegalArgumentException uiex )
{
throw new ChartException( ChartDeviceExtensionPlugin.ID,
ChartException.RENDERING,
uiex );
}
if ( taBlock == null )
{
taBlock = AttributeFactory.eINSTANCE.createTextAlignment( );
taBlock.setHorizontalAlignment( HorizontalAlignment.CENTER_LITERAL );
taBlock.setVerticalAlignment( VerticalAlignment.CENTER_LITERAL );
}
HorizontalAlignment haBlock = taBlock.getHorizontalAlignment( );
VerticalAlignment vaBlock = taBlock.getVerticalAlignment( );
switch ( haBlock.getValue( ) )
{
case HorizontalAlignment.CENTER :
boundBox.setLeft( boBlock.getLeft( )
+ ( boBlock.getWidth( ) - boundBox.getWidth( ) )
/ 2 );
break;
case HorizontalAlignment.LEFT :
boundBox.setLeft( boBlock.getLeft( ) );
break;
case HorizontalAlignment.RIGHT :
boundBox.setLeft( boBlock.getLeft( )
+ boBlock.getWidth( )
- boundBox.getWidth( ) );
break;
}
switch ( vaBlock.getValue( ) )
{
case VerticalAlignment.TOP :
boundBox.setTop( boBlock.getTop( ) );
break;
case VerticalAlignment.CENTER :
boundBox.setTop( boBlock.getTop( )
+ ( boBlock.getHeight( ) - boundBox.getHeight( ) )
/ 2 );
break;
case VerticalAlignment.BOTTOM :
boundBox.setTop( boBlock.getTop( )
+ boBlock.getHeight( )
- boundBox.getHeight( ) );
break;
}
boundBox.setLeft( boundBox.getLeft( ) + boundBox.getHotPoint( ) );
if ( ChartUtil.isShadowDefined( label ) )
{
showTopValue( renderer,
LocationImpl.create( boundBox.getLeft( ), boundBox.getTop( )
+ boundBox.getHeight( ) ),
label,
0,
true );
}
showTopValue( renderer, LocationImpl.create( boundBox.getLeft( ),
boundBox.getTop( ) + boundBox.getHeight( ) ), label, 0, false );
}
private final void showLeftValue( IPrimitiveRenderer renderer,
Location location, Label label, int labelPosition, boolean bShadow )
{
ChartGraphics2D g2d = (ChartGraphics2D) ( (IDeviceRenderer) renderer ).getGraphicsContext( );
FontDefinition fontDef = label.getCaption( ).getFont( );
double dAngleInDegrees = fontDef.getRotation( );
if ( bShadow ) // UPDATE TO FALSE IF SHADOW COLOR UNDEFINED BUT SHADOW
// REQUESTED FOR
{
bShadow = label.getShadowColor( ) != null;
}
Color clrText = (Color) _sxs.getColor( label.getCaption( ).getColor( ) );
Color clrBackground = null;
if ( label.getBackground( ) != null )
{
clrBackground = (Color) _sxs.getColor( (ColorDefinition) label.getBackground( ) );
}
final double dAngleInRadians = ( ( -dAngleInDegrees * Math.PI ) / 180.0 );
final double dSineTheta = ( Math.sin( dAngleInRadians ) );
final double dCosTheta = ( Math.cos( dAngleInRadians ) );
final ITextMetrics textMetrics = new ChartTextMetrics( _sxs, label );
// Tune text position if needed. Location instance may be changed
location = adjustTextPosition( labelPosition,
location,
textMetrics,
dAngleInDegrees );
double dX = location.getX( ), dY = location.getY( );
try
{
final double dFullWidth = textMetrics.getFullWidth( );
final double dHeight = textMetrics.getHeight( );
final double dDescent = textMetrics.getDescent( );
final double dFullHeight = textMetrics.getFullHeight( );
double dXOffset = 0, dWidth = 0;
final int lineCount = textMetrics.getLineCount( );
final Insets insets = label.getInsets( )
.scaledInstance( _sxs.getDpiResolution( ) / 72d );
final double shadowness = 3 * _sxs.getDpiResolution( ) / 72d;
final boolean bEmptyText = "".equals( label.getCaption( ).getValue( ) ); //$NON-NLS-1$
ChartTextLayout textLayout;
double dYDiff = dY - dFullHeight;
final HorizontalAlignment hAlign = label.getCaption( )
.getFont( )
.getAlignment( )
.getHorizontalAlignment( );
final boolean bRightAligned = hAlign.getValue( ) == HorizontalAlignment.RIGHT;
final boolean bCenterAligned = hAlign.getValue( ) == HorizontalAlignment.CENTER;
double dRotateX = ( dX - dFullWidth );
double dRotateY = ( dY + dHeight / 2 );
dX -= dFullWidth;
dY += dHeight / 2;
if ( dAngleInDegrees == 0 )
{
double dYHalfOffset = ( dFullHeight + dHeight ) / 2d;
if ( bShadow ) // RENDER THE SHADOW
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dY - dYHalfOffset ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dY - dYHalfOffset )
+ shadowness
+ dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dY - dYHalfOffset ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dY - dYHalfOffset,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < lineCount; i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( i );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( dY
- dYHalfOffset
+ insets.getTop( )
+ dHeight
* ( i + 1 ) - dDescent ) );
}
}
// RENDER THE OUTLINE
renderOutline( renderer, label.getOutline( ), r2d );
}
}
// DRAW POSITIVE ANGLE (> 0)
else if ( dAngleInDegrees > 0 && dAngleInDegrees < 90 )
{
double dDeltaX = dFullWidth - dFullWidth * dCosTheta;
double dDeltaY = dFullWidth * dSineTheta + dHeight / 2;
dX += dDeltaX;
dY -= dDeltaY;
g2d.rotate( dAngleInRadians, dRotateX + dDeltaX, dRotateY
- dDeltaY );
if ( bShadow )
{
// RENDER THE SHADOW
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dYDiff ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dYDiff ) + shadowness + dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dYDiff ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dYDiff,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < textMetrics.getLineCount( ); i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( lineCount
- i
- 1 );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( ( ( dY - dDescent ) - ( dHeight * i ) ) - insets.getBottom( ) ) );
}
}
// RENDER THE OUTLINE
renderOutline( renderer, label.getOutline( ), r2d );
}
g2d.rotate( -dAngleInRadians, dRotateX + dDeltaX, dRotateY
- dDeltaY );
}
// DRAW NEGATIVE ANGLE (< 0)
else if ( dAngleInDegrees < 0 && dAngleInDegrees > -90 )
{
double dDeltaX = dFullWidth
- dFullWidth
* dCosTheta
- dHeight
* dSineTheta;
double dDeltaY = dFullWidth
* dSineTheta
+ dHeight
/ 2
- dHeight
* dCosTheta;
dX += dDeltaX;
dY -= dDeltaY;
g2d.rotate( dAngleInRadians, dRotateX + dDeltaX, dRotateY
- dDeltaY );
if ( bShadow )
{
// RENDER THE SHADOW
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dY - dHeight ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dY - dHeight ) + shadowness + dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dY - dHeight ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dY - dHeight,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND FILL
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < lineCount; i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( i );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( ( ( dY - dDescent ) + ( dHeight * i ) ) + insets.getTop( ) ) );
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
g2d.rotate( -dAngleInRadians, dRotateX + dDeltaX, dRotateY
- dDeltaY );
}
// VERTICALLY UP
else if ( dAngleInDegrees == 90 )
{
double dDeltaX = dFullWidth;
double dDeltaY = ( dFullWidth - dHeight ) / 2;
dX += dDeltaX;
dY += dDeltaY;
g2d.rotate( dAngleInRadians, dX, dY );
if ( bShadow )
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dYDiff ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dYDiff ) + shadowness + dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dYDiff ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dYDiff,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND FILL
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < lineCount; i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( i );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( ( ( dY - dDescent ) - ( dHeight * ( lineCount
- i - 1 ) ) ) + insets.getTop( ) ) );
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
g2d.rotate( -dAngleInRadians, dX, dY );
}
// VERTICALLY DOWN
else if ( dAngleInDegrees == -90 )
{
double dDeltaX = dFullWidth - dHeight;
double dDeltaY = ( dFullWidth + dHeight ) / 2;
dX += dDeltaX;
dY -= dDeltaY;
g2d.rotate( dAngleInRadians, dX, dY );
if ( bShadow )
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dYDiff ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dYDiff ) + shadowness + dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dYDiff ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dY - dHeight,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND FILL
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < lineCount; i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( i );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( ( ( dY - dDescent ) + ( dHeight * i ) ) + insets.getTop( ) ) );
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
g2d.rotate( -dAngleInRadians, dX, dY );
}
}
finally
{
textMetrics.dispose( );
}
}
private final void showRightValue( IPrimitiveRenderer renderer,
Location location, Label label, int labelPosition, boolean bShadow )
{
ChartGraphics2D g2d = (ChartGraphics2D) ( (IDeviceRenderer) renderer ).getGraphicsContext( );
FontDefinition fontDef = label.getCaption( ).getFont( );
double dAngleInDegrees = fontDef.getRotation( );
if ( bShadow ) // UPDATE TO FALSE IF SHADOW COLOR UNDEFINED BUT SHADOW
// REQUESTED FOR
{
bShadow = label.getShadowColor( ) != null;
}
Color clrText = (Color) _sxs.getColor( label.getCaption( ).getColor( ) );
Color clrBackground = null;
if ( label.getBackground( ) != null )
{
clrBackground = (Color) _sxs.getColor( (ColorDefinition) label.getBackground( ) );
}
final ITextMetrics textMetrics = new ChartTextMetrics( _sxs, label );
// Tune text position if needed. Location instance may be changed
location = adjustTextPosition( labelPosition,
location,
textMetrics,
dAngleInDegrees );
double dX = location.getX( ), dY = location.getY( );
// dX += 2;
dY += 1;
try
{
final double dFullWidth = textMetrics.getFullWidth( );
final double dHeight = textMetrics.getHeight( );
final double dDescent = textMetrics.getDescent( );
final double dFullHeight = textMetrics.getFullHeight( );
double dXOffset = 0, dWidth = 0;
final int lineCount = textMetrics.getLineCount( );
final Insets insets = label.getInsets( )
.scaledInstance( _sxs.getDpiResolution( ) / 72d );
final double shadowness = 3 * _sxs.getDpiResolution( ) / 72d;
final boolean bEmptyText = "".equals( label.getCaption( ).getValue( ) ); //$NON-NLS-1$
ChartTextLayout textLayout;
double dYDiff = dY - dHeight;
final HorizontalAlignment hAlign = label.getCaption( )
.getFont( )
.getAlignment( )
.getHorizontalAlignment( );
final boolean bRightAligned = hAlign.getValue( ) == HorizontalAlignment.RIGHT;
final boolean bCenterAligned = hAlign.getValue( ) == HorizontalAlignment.CENTER;
double dAngleInRadians = ( ( -dAngleInDegrees * Math.PI ) / 180.0 );
int iRotateX = (int) dX;
int iRotateY = (int) ( dY + dHeight / 2 );
dY += dHeight / 2;
// HORIZONTAL TEXT
if ( dAngleInDegrees == 0 )
{
double dYHalfOffset = ( dFullHeight + dHeight ) / 2d;
if ( bShadow ) // RENDER THE SHADOW
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dY - dYHalfOffset ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dY - dYHalfOffset )
+ shadowness
+ dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dY - dYHalfOffset ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dY - dYHalfOffset,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND FILL
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < lineCount; i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( i );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( dY
- dYHalfOffset
+ insets.getTop( )
+ dHeight
* ( i + 1 ) - dDescent )
// (float)(((dY - dDescent) - ((lineCount - i) *
// dHeight - (lineCount + 1)
// *
// dHeight/2))
// + insets.getTop())
);
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
}
// DRAW POSITIVE ANGLE (> 0)
else if ( dAngleInDegrees > 0 && dAngleInDegrees < 90 )
{
double dDeltaX = dHeight * Math.sin( dAngleInRadians );
double dDeltaY = dHeight
* Math.cos( dAngleInRadians )
- dHeight
/ 2;
dX -= dDeltaX;
dY += dDeltaY;
g2d.rotate( dAngleInRadians, iRotateX - dDeltaX, iRotateY
+ dDeltaY );
if ( bShadow ) // RENDER THE SHADOW
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dYDiff ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dYDiff ) + shadowness + dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dYDiff ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
( dYDiff ),
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < lineCount; i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( i );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( ( dY - dDescent + dHeight * i ) + insets.getTop( ) ) );
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
// UNDO THE 'ROTATED' STATE OF THE GRAPHICS CONTEXT
g2d.rotate( -dAngleInRadians, iRotateX - dDeltaX, iRotateY
+ dDeltaY );
// crossHairs(g2d, (int)dX, (int)dY);
}
// DRAW NEGATIVE ANGLE (< 0)
else if ( dAngleInDegrees < 0 && dAngleInDegrees > -90 )
{
double dDeltaY = -dHeight / 2;
dY += dDeltaY;
g2d.rotate( dAngleInRadians, iRotateX, iRotateY + dDeltaY );
if ( bShadow ) // RENDER THE SHADOW
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dY - dFullHeight ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dY - dFullHeight )
+ shadowness
+ dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dY - dFullHeight ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dY - dFullHeight,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < lineCount; i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( i );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( ( dY - dDescent - dHeight
* ( lineCount - i - 1 ) ) - insets.getBottom( ) ) );
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
// UNDO THE 'ROTATED' STATE OF THE GRAPHICS CONTEXT
g2d.rotate( -dAngleInRadians, iRotateX, iRotateY + dDeltaY );
// crossHairs(g2d, (int)dX, (int)dY);
}
// VERTICALLY UP
else if ( dAngleInDegrees == 90 )
{
double dDeltaX = dHeight;
double dDeltaY = ( dFullWidth - dHeight ) / 2;
dX += dDeltaX;
dY += dDeltaY;
g2d.rotate( dAngleInRadians, dX, dY );
if ( bShadow ) // RENDER THE SHADOW
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dYDiff ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dYDiff ) + shadowness + dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dYDiff ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dYDiff,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < lineCount; i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( i );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( ( dY - dDescent + dHeight * i ) + insets.getTop( ) ) );
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
// UNDO THE 'ROTATED' STATE OF THE GRAPHICS CONTEXT
g2d.rotate( -dAngleInRadians, dX, dY );
// crossHairs(g2d, (int)dX, (int)dY);
}
// VERTICALLY DOWN
else if ( dAngleInDegrees == -90 )
{
double dDeltaX = 0;
double dDeltaY = ( dFullWidth + dHeight ) / 2;
dX += dDeltaX;
dY -= dDeltaY;
g2d.rotate( dAngleInRadians, dX, dY );
if ( bShadow ) // RENDER THE SHADOW
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dYDiff ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dYDiff ) + shadowness + dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dYDiff ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dYDiff,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < lineCount; i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( i );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( ( dY - dDescent + dHeight * i ) + insets.getTop( ) ) );
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
// UNDO THE 'ROTATED' STATE OF THE GRAPHICS CONTEXT
g2d.rotate( -dAngleInRadians, dX, dY );
// crossHairs(g2d, (int)dX, (int)dY);
}
}
finally
{
textMetrics.dispose( );
}
}
private final void showBottomValue( IPrimitiveRenderer renderer,
Location location, Label label, int labelPosition, boolean bShadow )
{
ChartGraphics2D g2d = (ChartGraphics2D) ( (IDeviceRenderer) renderer ).getGraphicsContext( );
FontDefinition fontDef = label.getCaption( ).getFont( );
// Color clrShadow = bShadow ? (Color)
// _sxs.getColor(label.getShadowColor()) : null;
double dAngleInDegrees = fontDef.getRotation( );
Color clrText = (Color) _sxs.getColor( label.getCaption( ).getColor( ) );
Color clrBackground = null;
if ( label.getBackground( ) != null )
{
clrBackground = (Color) _sxs.getColor( (ColorDefinition) label.getBackground( ) );
}
double dAngleInRadians = ( ( -dAngleInDegrees * Math.PI ) / 180.0 );
final ITextMetrics textMetrics = new ChartTextMetrics( _sxs, label );
// Tune text position if needed. Location instance may be changed
location = adjustTextPosition( labelPosition,
location,
textMetrics,
dAngleInDegrees );
double dX = location.getX( ), dY = location.getY( );
try
{
final double dFullWidth = textMetrics.getFullWidth( );
final double dHeight = textMetrics.getHeight( );
final double dDescent = textMetrics.getDescent( );
final double dFullHeight = textMetrics.getFullHeight( );
double dXOffset = 0, dWidth = 0;
final int lineCount = textMetrics.getLineCount( );
final Insets insets = label.getInsets( )
.scaledInstance( _sxs.getDpiResolution( ) / 72d );
final double shadowness = 3 * _sxs.getDpiResolution( ) / 72d;
final boolean bEmptyText = "".equals( label.getCaption( ).getValue( ) ); //$NON-NLS-1$
ChartTextLayout textLayout;
final HorizontalAlignment hAlignment = label.getCaption( )
.getFont( )
.getAlignment( )
.getHorizontalAlignment( );
final boolean bRightAligned = hAlignment.getValue( ) == HorizontalAlignment.RIGHT;
final boolean bCenterAligned = hAlignment.getValue( ) == HorizontalAlignment.CENTER;
dX -= dFullWidth / 2;
dY += dHeight;
// HORIZONTAL TEXT
if ( dAngleInDegrees == 0 )
{
if ( bShadow ) // RENDER THE SHADOW
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dY - dHeight ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dY - dHeight ) + shadowness + dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dY - dHeight ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dY - dHeight,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < lineCount; i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( i );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( dY - dDescent + dHeight * i + insets.getTop( ) ) );
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
// crossHairs(g2d, (int)dX, (int)dY);
}
// DRAW IT AT A POSITIVE ANGLE
else if ( dAngleInDegrees > 0 && dAngleInDegrees < 90 )
{
double dSineTheta = Math.abs( Math.sin( dAngleInRadians ) );
double dCosTheta = Math.abs( Math.cos( dAngleInRadians ) );
double dDeltaX = dFullWidth
* dCosTheta
- dHeight
* dSineTheta
- dFullWidth
/ 2.0;
double dDeltaY = dHeight
* dCosTheta
+ dFullWidth
* dSineTheta
- dHeight;
dX -= dDeltaX;
dY += dDeltaY;
g2d.rotate( dAngleInRadians, dX, dY );
if ( bShadow ) // RENDER THE SHADOW
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dY - dHeight ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dY - dHeight ) + shadowness + dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dY - dHeight ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dY - dHeight,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < lineCount; i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( i );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( dY - dDescent + dHeight * i + insets.getTop( ) ) );
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
// UNDO THE 'ROTATED' STATE OF THE GRAPHICS CONTEXT
g2d.rotate( -dAngleInRadians, dX, dY );
}
// DRAW IT AT A NEGATIVE ANGLE
else if ( dAngleInDegrees < 0 && dAngleInDegrees > -90 )
{
dX += dFullWidth / 2;
g2d.rotate( dAngleInRadians, dX, dY - dHeight );
if ( bShadow ) // RENDER THE SHADOW
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dY - dHeight ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dY - dHeight ) + shadowness + dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dY - dHeight ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dY - dHeight,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < lineCount; i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( i );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( dY - dDescent + dHeight * i + insets.getTop( ) ) );
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
// UNDO THE 'ROTATED' STATE OF THE GRAPHICS CONTEXT
g2d.rotate( -dAngleInRadians, dX, dY - dHeight );
}
// VERTICALLY UP
else if ( dAngleInDegrees == 90 )
{
double dYHalfOffset = ( dFullHeight + dHeight ) / 2.0;
double dDeltaX = ( dFullWidth + dHeight ) / 2;
double dDeltaY = ( dFullWidth - dHeight );
dX += dDeltaX;
dY += dDeltaY;
g2d.rotate( dAngleInRadians, dX, dY );
if ( bShadow ) // RENDER THE SHADOW
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dY - dYHalfOffset ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dY - dYHalfOffset )
+ shadowness
+ dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dY - dYHalfOffset ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dY - dYHalfOffset,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < lineCount; i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( i );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( ( ( dY - dDescent ) - ( ( lineCount - i )
* dHeight - ( lineCount + 1 )
* dHeight
/ 2 ) ) + insets.getTop( ) ) );
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
// UNDO THE 'ROTATED' STATE OF THE GRAPHICS CONTEXT
g2d.rotate( -dAngleInRadians, dX, dY );
// crossHairs(g2d, (int)dX, (int)dY);
}
// VERTICALLY DOWN
else if ( dAngleInDegrees == -90 )
{
dX += dFullWidth / 2;
dY -= dHeight;
double dYHalfOffset = ( dFullHeight + dHeight ) / 2d;
double dDeltaX = dYHalfOffset - dFullHeight / 2d;
dX -= dDeltaX;
g2d.rotate( dAngleInRadians, dX, dY );
if ( bShadow ) // RENDER THE SHADOW
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dY - dYHalfOffset ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dY - dYHalfOffset )
+ shadowness
+ dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dY - dYHalfOffset ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dY - dYHalfOffset,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < lineCount; i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( i );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( ( dY - dDescent )
- dYHalfOffset
+ dHeight
* ( i + 1 ) + insets.getTop( ) ) );
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
// UNDO THE 'ROTATED' STATE OF THE GRAPHICS CONTEXT
g2d.rotate( -dAngleInRadians, dX, dY );
}
}
finally
{
textMetrics.dispose( );
}
}
private final void showTopValue( IPrimitiveRenderer renderer,
Location location, Label label, int labelPosition, boolean bShadow )
{
final ChartGraphics2D g2d = (ChartGraphics2D) ( (IDeviceRenderer) renderer ).getGraphicsContext( );
final FontDefinition fontDef = label.getCaption( ).getFont( );
// final Color clrShadow = bShadow ? (Color)
// _sxs.getColor(la.getShadowColor()) : null;
final double dAngleInDegrees = fontDef.getRotation( );
final Color clrText = (Color) _sxs.getColor( label.getCaption( )
.getColor( ) );
Color clrBackground = null;
if ( label.getBackground( ) != null )
{
clrBackground = (Color) _sxs.getColor( (ColorDefinition) label.getBackground( ) );
}
double dAngleInRadians = ( ( -dAngleInDegrees * Math.PI ) / 180.0 );
final ITextMetrics textMetrics = new ChartTextMetrics( _sxs, label );
// Tune text position if needed. Location instance may be changed
location = adjustTextPosition( labelPosition,
location,
textMetrics,
dAngleInDegrees );
double dX = location.getX( ), dY = location.getY( );
try
{
final double dFullWidth = textMetrics.getFullWidth( );
final double dHeight = textMetrics.getHeight( );
final double dDescent = textMetrics.getDescent( );
final double dFullHeight = textMetrics.getFullHeight( );
double dXOffset = 0, dWidth = 0;
final int lineCount = textMetrics.getLineCount( );
final Insets insets = label.getInsets( )
.scaledInstance( _sxs.getDpiResolution( ) / 72d );
final double shadowness = 3 * _sxs.getDpiResolution( ) / 72d;
final boolean bEmptyText = "".equals( label.getCaption( ).getValue( ) ); //$NON-NLS-1$
ChartTextLayout textLayout;
final HorizontalAlignment hAlignment = label.getCaption( )
.getFont( )
.getAlignment( )
.getHorizontalAlignment( );
final boolean bRightAligned = hAlignment.getValue( ) == HorizontalAlignment.RIGHT;
final boolean bCenterAligned = hAlignment.getValue( ) == HorizontalAlignment.CENTER;
dX -= dFullWidth / 2;
// HORIZONTAL TEXT
if ( dAngleInDegrees == 0 )
{
if ( bShadow ) // RENDER THE SHADOW
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dY - dFullHeight ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dY - dFullHeight )
+ shadowness
+ dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dY - dFullHeight ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
( dY - dFullHeight ),
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < textMetrics.getLineCount( ); i++ )
{
// textLayout = new
// TextLayout(textMetrics.getLine(lineCount - i -
// 1),
// g2d.getFont(), g2d.getFontRenderContext());
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( lineCount
- i
- 1 );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( dY - dDescent - dHeight * i - insets.getBottom( ) ) );
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
// crossHairs(g2d, (int)dX, (int)dY);
}
// DRAW IT AT A POSITIVE ANGLE
else if ( dAngleInDegrees > 0 && dAngleInDegrees < 90 )
{
double dDeltaX = dFullWidth / 2;
dX += dDeltaX;
g2d.rotate( dAngleInRadians, dX, dY );
if ( bShadow ) // RENDER THE SHADOW
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dY - dFullHeight ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dY - dFullHeight )
+ shadowness
+ dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dY - dFullHeight ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
( dY - dFullHeight ),
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < textMetrics.getLineCount( ); i++ )
{
textLayout = new ChartTextLayout( textMetrics.getLine( lineCount
- i
- 1 ),
g2d.getFont( ).getAttributes( ),
g2d.getFontRenderContext( ) );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( dY - dDescent - dHeight * i - insets.getBottom( ) ) );
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
// UNDO THE 'ROTATED' STATE OF THE GRAPHICS CONTEXT
g2d.rotate( -dAngleInRadians, dX, dY );
// crossHairs(g2d, (int)dX, (int)dY);
}
// DRAW IT AT A NEGATIVE ANGLE
else if ( dAngleInDegrees < 0 && dAngleInDegrees > -90 )
{
double dCosTheta = Math.abs( Math.cos( dAngleInRadians ) );
double dSineTheta = Math.abs( Math.sin( dAngleInRadians ) );
dX -= dFullWidth / 2 - ( dFullWidth - dFullWidth * dCosTheta );
dY -= dFullWidth * dSineTheta;
g2d.rotate( dAngleInRadians, dX, dY );
if ( bShadow ) // RENDER THE SHADOW
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dY - dFullHeight ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dY - dFullHeight )
+ shadowness
+ dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dY - dFullHeight ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dY - dFullHeight,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < textMetrics.getLineCount( ); i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( lineCount
- i
- 1 );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( dY - dDescent - dHeight * i - insets.getBottom( ) ) );
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
// UNDO THE 'ROTATED' STATE OF THE GRAPHICS CONTEXT
g2d.rotate( -dAngleInRadians, dX, dY );
/*
* final RotatedRectangle rr = computePolygon(IConstants.ABOVE,
* label, location.getX(), location.getY());
* g2d.setColor(Color.blue); g2d.draw(rr); final BoundingBox bb =
* computeBox(IConstants.ABOVE, label, location.getX(),
* location.getY()); renderBox(g2d, bb, Color.black, null);
*/
// crossHairs(g2d, (int)dX, (int)dY);
}
// VERTICALLY UP
else if ( dAngleInDegrees == 90 )
{
double dYHalfOffset = ( dFullHeight + dHeight ) / 2.0;
double dDeltaX = ( dFullWidth + dHeight ) / 2;
dX += dDeltaX;
g2d.rotate( dAngleInRadians, dX, dY );
if ( bShadow ) // RENDER THE SHADOW
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dY - dYHalfOffset ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dY - dYHalfOffset )
+ shadowness
+ dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dY - dYHalfOffset ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dY - dYHalfOffset,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < textMetrics.getLineCount( ); i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( i );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( ( ( dY - dDescent ) - ( ( textMetrics.getLineCount( ) - i )
* dHeight - ( lineCount + 1 )
* dHeight
/ 2 ) ) + insets.getTop( ) ) );
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
// UNDO THE 'ROTATED' STATE OF THE GRAPHICS CONTEXT
g2d.rotate( -dAngleInRadians, dX, dY );
// crossHairs(g2d, (int)dX, (int)dY);
}
// VERTICALLY DOWN
else if ( dAngleInDegrees == -90 )
{
double dYHalfOffset = ( dFullHeight + dHeight ) / 2.0;
double dDeltaX = ( dFullWidth - dHeight ) / 2;
double dDeltaY = dFullWidth;
dX += dDeltaX;
dY -= dDeltaY;
g2d.rotate( dAngleInRadians, dX, dY );
if ( bShadow ) // RENDER THE SHADOW
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dY - dYHalfOffset ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dY - dYHalfOffset )
+ shadowness
+ dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dY - dYHalfOffset ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dY - dYHalfOffset,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < textMetrics.getLineCount( ); i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( i );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( ( ( dY - dDescent ) - ( ( textMetrics.getLineCount( ) - i )
* dHeight - ( lineCount + 1 )
* dHeight
/ 2 ) ) + insets.getTop( ) ) );
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
// UNDO THE 'ROTATED' STATE OF THE GRAPHICS CONTEXT
g2d.rotate( -dAngleInRadians, dX, dY );
// crossHairs(g2d, (int)dX, (int)dY);
}
}
finally
{
textMetrics.dispose( );
}
}
/**
*
* @param g2d
* @param f
* @param dX
* @param dY
* @param sText
* @param iAngleInDegrees
*/
private final void showCenterValue( IPrimitiveRenderer renderer,
Location location, Label label, boolean bShadow )
{
ChartGraphics2D g2d = (ChartGraphics2D) ( (IDeviceRenderer) renderer ).getGraphicsContext( );
double dX = location.getX( ), dY = location.getY( );
FontDefinition fontDef = label.getCaption( ).getFont( );
double dAngleInDegrees = fontDef.getRotation( );
if ( bShadow ) // UPDATE TO FALSE IF SHADOW COLOR UNDEFINED BUT SHADOW
// REQUESTED FOR
{
bShadow = label.getShadowColor( ) != null;
}
Color clrText = (Color) _sxs.getColor( label.getCaption( ).getColor( ) );
Color clrBackground = null;
if ( label.getBackground( ) != null )
{
clrBackground = (Color) _sxs.getColor( (ColorDefinition) label.getBackground( ) );
}
final double dAngleInRadians = ( ( -dAngleInDegrees * Math.PI ) / 180.0 );
final double dSineTheta = ( Math.sin( dAngleInRadians ) );
final double dCosTheta = ( Math.cos( dAngleInRadians ) );
final ITextMetrics textMetrics = _sxs.getTextMetrics( label );
try
{
final double dFullWidth = textMetrics.getFullWidth( );
final double dHeight = textMetrics.getHeight( );
final double dDescent = textMetrics.getDescent( );
final double dFullHeight = textMetrics.getFullHeight( );
double dXOffset = 0, dWidth = 0;
final int lineCount = textMetrics.getLineCount( );
final Insets insets = label.getInsets( )
.scaledInstance( _sxs.getDpiResolution( ) / 72d );
final double shadowness = 3 * _sxs.getDpiResolution( ) / 72d;
// Swing is not friendly to empty string, check and skip for this
// case
final boolean bEmptyText = "".equals( label.getCaption( ).getValue( ) ); //$NON-NLS-1$
ChartTextLayout textLayout;
final HorizontalAlignment hAlign = label.getCaption( )
.getFont( )
.getAlignment( )
.getHorizontalAlignment( );
final boolean bRightAligned = hAlign.getValue( ) == HorizontalAlignment.RIGHT;
final boolean bCenterAligned = hAlign.getValue( ) == HorizontalAlignment.CENTER;
double dRotateX = dX;
double dRotateY = dY;
dX -= dFullWidth / 2;
dY += dHeight / 2;
if ( dAngleInDegrees == 0 )
{
double dYHalfOffset = ( dFullHeight + dHeight ) / 2d;
if ( bShadow ) // RENDER THE SHADOW
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dY - dYHalfOffset ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dY - dYHalfOffset )
+ shadowness
+ dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dY - dYHalfOffset ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dY - dYHalfOffset,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < lineCount; i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( i );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( dY
- dYHalfOffset
+ insets.getTop( )
+ dHeight
* ( i + 1 ) - dDescent ) );
}
}
// RENDER THE OUTLINE
renderOutline( renderer, label.getOutline( ), r2d );
}
}
// DRAW POSITIVE ANGLE (> 0)
else if ( dAngleInDegrees > 0 && dAngleInDegrees < 90 )
{
double dDeltaX = dFullWidth - dFullWidth * dCosTheta;
double dDeltaY = dFullWidth * dSineTheta + dHeight / 2;
dX += dDeltaX;
dY -= dDeltaY;
g2d.rotate( dAngleInRadians, dRotateX + dDeltaX, dRotateY
- dDeltaY );
if ( bShadow )
{
// RENDER THE SHADOW
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dY - dFullHeight ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dY - dFullHeight )
+ shadowness
+ dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dY - dFullHeight ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dY - dFullHeight,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < textMetrics.getLineCount( ); i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( lineCount
- i
- 1 );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( ( ( dY - dDescent ) - ( dHeight * i ) ) - insets.getBottom( ) ) );
}
}
// RENDER THE OUTLINE
renderOutline( renderer, label.getOutline( ), r2d );
}
g2d.rotate( -dAngleInRadians, dRotateX + dDeltaX, dRotateY
- dDeltaY );
}
// DRAW NEGATIVE ANGLE (< 0)
else if ( dAngleInDegrees < 0 && dAngleInDegrees > -90 )
{
double dDeltaX = dFullWidth
- dFullWidth
* dCosTheta
- dHeight
* dSineTheta;
double dDeltaY = dFullWidth
* dSineTheta
+ dHeight
/ 2
- dHeight
* dCosTheta;
dX += dDeltaX;
dY -= dDeltaY;
g2d.rotate( dAngleInRadians, dRotateX + dDeltaX, dRotateY
- dDeltaY );
if ( bShadow )
{
// RENDER THE SHADOW
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dY - dHeight ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dY - dHeight ) + shadowness + dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dY - dHeight ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dY - dHeight,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND FILL
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < lineCount; i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( i );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( ( ( dY - dDescent ) + ( dHeight * i ) ) + insets.getTop( ) ) );
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
g2d.rotate( -dAngleInRadians, dRotateX + dDeltaX, dRotateY
- dDeltaY );
}
// VERTICALLY UP
else if ( dAngleInDegrees == 90 )
{
double dDeltaX = dFullWidth;
double dDeltaY = ( dFullWidth - dHeight ) / 2;
dX += dDeltaX;
dY += dDeltaY;
g2d.rotate( dAngleInRadians, dX, dY );
if ( bShadow )
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dY - dFullHeight ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dY - dFullHeight )
+ shadowness
+ dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dY - dFullHeight ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dY - dFullHeight,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND FILL
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < lineCount; i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( i );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( ( ( dY - dDescent ) - ( dHeight * ( lineCount
- i - 1 ) ) ) + insets.getTop( ) ) );
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
g2d.rotate( -dAngleInRadians, dX, dY );
}
// VERTICALLY DOWN
else if ( dAngleInDegrees == -90 )
{
double dDeltaX = dFullWidth - dHeight;
double dDeltaY = ( dFullWidth + dHeight ) / 2;
dX += dDeltaX;
dY -= dDeltaY;
g2d.rotate( dAngleInRadians, dX, dY );
if ( bShadow )
{
g2d.setPaint( new GradientPaint( new Point2D.Double( dX
+ shadowness, ( dY - dFullHeight ) + shadowness ),
(Color) _sxs.getColor( label.getShadowColor( ) ),
new Point2D.Double( dX + shadowness + dFullWidth,
( dY - dFullHeight )
+ shadowness
+ dFullHeight ),
(Color) _sxs.getColor( label.getShadowColor( )
.translucent( ) ) ) );
g2d.fill( new Rectangle2D.Double( dX + shadowness,
( dY - dFullHeight ) + shadowness,
dFullWidth,
dFullHeight ) );
}
else
{
final Rectangle2D.Double r2d = new Rectangle2D.Double( dX,
dY - dHeight,
dFullWidth,
dFullHeight );
// RENDER THE BACKGROUND FILL
if ( clrBackground != null )
{
g2d.setColor( clrBackground );
g2d.fill( r2d );
}
// RENDER THE TEXT
if ( !bEmptyText )
{
g2d.setColor( clrText );
for ( int i = 0; i < lineCount; i++ )
{
textLayout = ( (ChartTextMetrics) textMetrics ).getLayout( i );
if ( bRightAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ dFullWidth
- dWidth
- insets.getRight( );
}
else if ( bCenterAligned )
{
dWidth = textLayout.getBounds( ).getWidth( );
dXOffset = -insets.getLeft( )
+ ( dFullWidth - dWidth )
/ 2;
}
textLayout.draw( g2d,
(float) ( dX + dXOffset + insets.getLeft( ) ),
(float) ( ( ( dY - dDescent ) + ( dHeight * i ) ) + insets.getTop( ) ) );
}
}
// RENDER THE OUTLINE/BORDER
renderOutline( renderer, label.getOutline( ), r2d );
}
g2d.rotate( -dAngleInRadians, dX, dY );
}
}
finally
{
textMetrics.dispose( );
}
}
// private static final void renderBox(Graphics2D g2d, BoundingBox bb, Color
// cFG, Color cBG)
// {
// if (cBG != null)
// {
// g2d.setColor(cBG);
// g2d.fillRect((int) bb.getLeft(), (int) bb.getTop(), (int) bb.getWidth(),
// (int) bb.getHeight());
// }
// g2d.setColor(cFG);
// g2d.drawRect((int) bb.getLeft(), (int) bb.getTop(), (int) bb.getWidth(),
// (int) bb.getHeight());
// }
private final void renderOutline( IPrimitiveRenderer renderer,
LineAttributes lineAttribs, Rectangle2D.Double rect )
{
if ( lineAttribs != null
&& lineAttribs.isVisible( )
&& lineAttribs.getColor( ) != null )
{
ChartGraphics2D g2d = (ChartGraphics2D) ( (IDeviceRenderer) renderer ).getGraphicsContext( );
Stroke sPrevious = null;
final ColorDefinition cd = lineAttribs.getColor( );
final Stroke sCurrent = ( (SwingRendererImpl) renderer ).getCachedStroke( lineAttribs );
if ( sCurrent != null ) // SOME STROKE DEFINED?
{
sPrevious = g2d.getStroke( );
g2d.setStroke( sCurrent );
}
g2d.setColor( (Color) _sxs.getColor( cd ) );
g2d.draw( rect );
// g2d.setNoFillColor( g2d.getCurrentElement( ) );
if ( sPrevious != null ) // RESTORE PREVIOUS STROKE
{
g2d.setStroke( sPrevious );
}
}
}
}
| Since SwfGraphics2D doesn't extend from ChartGraphics2D, so the Graphics2D shjould be used to declare graphics variable instead of ChartGraphics2D.
| chart/org.eclipse.birt.chart.device.extension/src/org/eclipse/birt/chart/device/util/ChartTextRenderer.java | Since SwfGraphics2D doesn't extend from ChartGraphics2D, so the Graphics2D shjould be used to declare graphics variable instead of ChartGraphics2D. |
|
Java | agpl-3.0 | a9828337f5b47f428e436a7421799843c1621c35 | 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 | 16bcbe60-2e62-11e5-9284-b827eb9e62be | hello.java | 16b72f68-2e62-11e5-9284-b827eb9e62be | 16bcbe60-2e62-11e5-9284-b827eb9e62be | hello.java | 16bcbe60-2e62-11e5-9284-b827eb9e62be |
|
Java | lgpl-2.1 | a1b51d4c16c58da304d34b3d6ad6dcbc5bb563db | 0 | languagetool-org/languagetool,jimregan/languagetool,jimregan/languagetool,jimregan/languagetool,languagetool-org/languagetool,languagetool-org/languagetool,languagetool-org/languagetool,languagetool-org/languagetool,jimregan/languagetool,jimregan/languagetool | /* LanguageTool, a natural language style checker
* Copyright (C) 2014 Daniel Naber (http://www.danielnaber.de)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.rules.en;
import org.jetbrains.annotations.Nullable;
import org.languagetool.*;
import org.languagetool.language.English;
import org.languagetool.languagemodel.LanguageModel;
import org.languagetool.rules.Example;
import org.languagetool.rules.RuleMatch;
import org.languagetool.rules.SuggestedReplacement;
import org.languagetool.rules.spelling.morfologik.MorfologikSpellerRule;
import org.languagetool.synthesis.en.EnglishSynthesizer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.*;
public abstract class AbstractEnglishSpellerRule extends MorfologikSpellerRule {
private static final EnglishSynthesizer synthesizer = new EnglishSynthesizer(new English());
public AbstractEnglishSpellerRule(ResourceBundle messages, Language language) throws IOException {
this(messages, language, null, Collections.emptyList());
}
/**
* @since 4.4
*/
public AbstractEnglishSpellerRule(ResourceBundle messages, Language language, UserConfig userConfig, List<Language> altLanguages) throws IOException {
this(messages, language, userConfig, altLanguages, null);
}
protected static Map<String,String> loadWordlist(String path, int column) {
if (column != 0 && column != 1) {
throw new IllegalArgumentException("Only column 0 and 1 are supported: " + column);
}
Map<String,String> words = new HashMap<>();
try (
InputStreamReader isr = new InputStreamReader(JLanguageTool.getDataBroker().getFromResourceDirAsStream(path), StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(isr);
) {
String line;
while ((line = br.readLine()) != null) {
line = line.trim();
if (line.isEmpty() || line.startsWith("#")) {
continue;
}
String[] parts = line.split(";");
if (parts.length != 2) {
throw new IOException("Unexpected format in " + path + ": " + line + " - expected two parts delimited by ';'");
}
words.put(parts[column], parts[column == 1 ? 0 : 1]);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return words;
}
/**
* @since 4.5
* optional: language model for better suggestions
*/
@Experimental
public AbstractEnglishSpellerRule(ResourceBundle messages, Language language, UserConfig userConfig,
List<Language> altLanguages, LanguageModel languageModel) throws IOException {
super(messages, language, userConfig, altLanguages, languageModel);
super.ignoreWordsWithLength = 1;
setCheckCompound(true);
addExamplePair(Example.wrong("This <marker>sentenc</marker> contains a spelling mistake."),
Example.fixed("This <marker>sentence</marker> contains a spelling mistake."));
String languageSpecificIgnoreFile = getSpellingFileName().replace(".txt", "_"+language.getShortCodeWithCountryAndVariant()+".txt");
for (String ignoreWord : wordListLoader.loadWords(languageSpecificIgnoreFile)) {
addIgnoreWords(ignoreWord);
}
}
@Override
protected List<RuleMatch> getRuleMatches(String word, int startPos, AnalyzedSentence sentence, List<RuleMatch> ruleMatchesSoFar, int idx, AnalyzedTokenReadings[] tokens) throws IOException {
List<RuleMatch> ruleMatches = super.getRuleMatches(word, startPos, sentence, ruleMatchesSoFar, idx, tokens);
if (ruleMatches.size() > 0) {
// so 'word' is misspelled:
IrregularForms forms = getIrregularFormsOrNull(word);
if (forms != null) {
String message = "Possible spelling mistake. Did you mean <suggestion>" + forms.forms.get(0) +
"</suggestion>, the " + forms.formName + " form of the " + forms.posName +
" '" + forms.baseform + "'?";
addFormsToFirstMatch(message, sentence, ruleMatches, forms.forms);
} else {
VariantInfo variantInfo = isValidInOtherVariant(word);
if (variantInfo != null) {
String message = "Possible spelling mistake. '" + word + "' is " + variantInfo.getVariantName() + ".";
replaceFormsOfFirstMatch(message, sentence, ruleMatches, variantInfo.otherVariant());
}
}
}
return ruleMatches;
}
/**
* @since 4.5
*/
@Nullable
protected VariantInfo isValidInOtherVariant(String word) {
return null;
}
private void addFormsToFirstMatch(String message, AnalyzedSentence sentence, List<RuleMatch> ruleMatches, List<String> forms) {
// recreating match, might overwrite information by SuggestionsRanker;
// this has precedence
RuleMatch oldMatch = ruleMatches.get(0);
RuleMatch newMatch = new RuleMatch(this, sentence, oldMatch.getFromPos(), oldMatch.getToPos(), message);
List<String> allSuggestions = new ArrayList<>(forms);
for (String repl : oldMatch.getSuggestedReplacements()) {
if (!allSuggestions.contains(repl)) {
allSuggestions.add(repl);
}
}
newMatch.setSuggestedReplacements(allSuggestions);
ruleMatches.set(0, newMatch);
}
private void replaceFormsOfFirstMatch(String message, AnalyzedSentence sentence, List<RuleMatch> ruleMatches, String suggestion) {
// recreating match, might overwrite information by SuggestionsRanker;
// this has precedence
RuleMatch oldMatch = ruleMatches.get(0);
RuleMatch newMatch = new RuleMatch(this, sentence, oldMatch.getFromPos(), oldMatch.getToPos(), message);
SuggestedReplacement sugg = new SuggestedReplacement(suggestion);
sugg.setShortDescription(language.getName());
newMatch.setSuggestedReplacementObjects(Collections.singletonList(sugg));
ruleMatches.set(0, newMatch);
}
@SuppressWarnings({"ReuseOfLocalVariable", "ControlFlowStatementWithoutBraces"})
@Nullable
private IrregularForms getIrregularFormsOrNull(String word) {
IrregularForms irregularFormsOrNull = getIrregularFormsOrNull(word, "ed", Arrays.asList("ed"), "VBD", "verb", "past tense");
if (irregularFormsOrNull != null) return irregularFormsOrNull;
irregularFormsOrNull = getIrregularFormsOrNull(word, "ed", Arrays.asList("d" /* e.g. awaked */), "VBD", "verb", "past tense");
if (irregularFormsOrNull != null) return irregularFormsOrNull;
irregularFormsOrNull = getIrregularFormsOrNull(word, "s", Arrays.asList("s"), "NNS", "noun", "plural");
if (irregularFormsOrNull != null) return irregularFormsOrNull;
irregularFormsOrNull = getIrregularFormsOrNull(word, "es", Arrays.asList("es"/* e.g. 'analysises' */), "NNS", "noun", "plural");
if (irregularFormsOrNull != null) return irregularFormsOrNull;
irregularFormsOrNull = getIrregularFormsOrNull(word, "er", Arrays.asList("er"/* e.g. 'farer' */), "JJR", "adjective", "comparative");
if (irregularFormsOrNull != null) return irregularFormsOrNull;
irregularFormsOrNull = getIrregularFormsOrNull(word, "est", Arrays.asList("est"/* e.g. 'farest' */), "JJS", "adjective", "superlative");
return irregularFormsOrNull;
}
@Nullable
private IrregularForms getIrregularFormsOrNull(String word, String wordSuffix, List<String> suffixes, String posTag, String posName, String formName) {
try {
for (String suffix : suffixes) {
if (word.endsWith(wordSuffix)) {
String baseForm = word.substring(0, word.length() - suffix.length());
String[] forms = synthesizer.synthesize(new AnalyzedToken(word, null, baseForm), posTag);
List<String> result = new ArrayList<>();
for (String form : forms) {
if (!speller1.isMisspelled(form)) {
// only accept suggestions that the spellchecker will accept
result.add(form);
}
}
// the internal dict might contain forms that the spell checker doesn't accept (e.g. 'criterions'),
// but we trust the spell checker in this case:
result.remove(word);
result.remove("badder"); // non-standard usage
result.remove("baddest"); // non-standard usage
result.remove("spake"); // can be removed after dict update
if (result.size() > 0) {
return new IrregularForms(baseForm, posName, formName, result);
}
}
}
return null;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* @since 2.7
*/
@Override
protected List<String> getAdditionalTopSuggestions(List<String> suggestions, String word) throws IOException {
if ("Alot".equals(word)) {
return Arrays.asList("A lot");
} else if ("alot".equals(word)) {
return Arrays.asList("a lot");
} else if ("thru".equals(word)) {
return Arrays.asList("through");
} else if ("speach".equals(word)) { // the replacement pairs would prefer "speak"
return Arrays.asList("speech");
} else if ("icecreem".equals(word)) {
return Arrays.asList("ice cream");
} else if ("fora".equals(word)) {
return Arrays.asList("for a");
} else if ("Boing".equals(word)) {
return Arrays.asList("Boeing");
} else if ("te".equals(word)) {
return Arrays.asList("the");
} else if ("todays".equals(word)) {
return Arrays.asList("today's");
} else if ("Todays".equals(word)) {
return Arrays.asList("Today's");
} else if ("todo".equals(word)) {
return Arrays.asList("to-do", "to do");
} else if ("Todo".equals(word)) {
return Arrays.asList("To-do", "To do");
} else if ("heres".equals(word)) {
return Arrays.asList("here's");
} else if ("Heres".equals(word)) {
return Arrays.asList("Here's");
} else if ("McDonalds".equals(word)) {
return Arrays.asList("McDonald's");
} else if ("ecommerce".equals(word)) {
return Arrays.asList("e-commerce");
} else if ("Ecommerce".equals(word)) {
return Arrays.asList("E-Commerce");
} else if ("eCommerce".equals(word)) {
return Arrays.asList("e-commerce");
} else if ("elearning".equals(word)) {
return Arrays.asList("e-learning");
} else if ("eLearning".equals(word)) {
return Arrays.asList("e-learning");
} else if ("ebook".equals(word)) {
return Arrays.asList("e-book");
} else if ("eBook".equals(word)) {
return Arrays.asList("e-book");
} else if ("Ebook".equals(word)) {
return Arrays.asList("E-Book");
} else if ("ie".equals(word)) {
return Arrays.asList("i.e.");
} else if ("eg".equals(word)) {
return Arrays.asList("e.g.");
} else if ("Thx".equals(word)) {
return Arrays.asList("Thanks");
} else if ("thx".equals(word)) {
return Arrays.asList("thanks");
} else if ("Sry".equals(word)) {
return Arrays.asList("Sorry");
} else if ("sry".equals(word)) {
return Arrays.asList("sorry");
} else if ("Lil".equals(word)) {
return Arrays.asList("Little");
} else if ("lil".equals(word)) {
return Arrays.asList("little");
} else if ("Sucka".equals(word)) {
return Arrays.asList("Sucker");
} else if ("sucka".equals(word)) {
return Arrays.asList("sucker");
} else if ("center".equals(word)) {
// For non-US English
return Arrays.asList("centre");
} else if ("ur".equals(word)) {
return Arrays.asList("your", "you are");
} else if ("Ur".equals(word)) {
return Arrays.asList("Your", "You are");
} else if ("ure".equals(word)) {
return Arrays.asList("your", "you are");
} else if ("Ure".equals(word)) {
return Arrays.asList("Your", "You are");
} else if ("mins".equals(word)) {
return Arrays.asList("minutes", "min");
} else if ("addon".equals(word)) {
return Arrays.asList("add-on");
} else if ("addons".equals(word)) {
return Arrays.asList("add-ons");
} else if ("afterparty".equals(word)) {
return Arrays.asList("after-party");
} else if ("Afterparty".equals(word)) {
return Arrays.asList("After-party");
} else if ("wellbeing".equals(word)) {
return Arrays.asList("well-being");
} else if ("cuz".equals(word)) {
return Arrays.asList("because");
} else if ("prio".equals(word)) {
return Arrays.asList("priority");
} else if ("prios".equals(word)) {
return Arrays.asList("priorities");
} else if ("gmail".equals(word)) {
return Arrays.asList("Gmail");
// AtD irregular plurals - START
} else if ("addendums".equals(word)) {
return Arrays.asList("addenda");
} else if ("algas".equals(word)) {
return Arrays.asList("algae");
} else if ("alumnas".equals(word)) {
return Arrays.asList("alumnae");
} else if ("alumnuses".equals(word)) {
return Arrays.asList("alumni");
} else if ("analysises".equals(word)) {
return Arrays.asList("analyses");
} else if ("appendixs".equals(word)) {
return Arrays.asList("appendices");
} else if ("axises".equals(word)) {
return Arrays.asList("axes");
} else if ("bacilluses".equals(word)) {
return Arrays.asList("bacilli");
} else if ("bacteriums".equals(word)) {
return Arrays.asList("bacteria");
} else if ("basises".equals(word)) {
return Arrays.asList("bases");
} else if ("beaus".equals(word)) {
return Arrays.asList("beaux");
} else if ("bisons".equals(word)) {
return Arrays.asList("bison");
} else if ("buffalos".equals(word)) {
return Arrays.asList("buffaloes");
} else if ("calfs".equals(word)) {
return Arrays.asList("calves");
} else if ("childs".equals(word)) {
return Arrays.asList("children");
} else if ("crisises".equals(word)) {
return Arrays.asList("crises");
} else if ("criterions".equals(word)) {
return Arrays.asList("criteria");
} else if ("curriculums".equals(word)) {
return Arrays.asList("curricula");
} else if ("datums".equals(word)) {
return Arrays.asList("data");
} else if ("deers".equals(word)) {
return Arrays.asList("deer");
} else if ("diagnosises".equals(word)) {
return Arrays.asList("diagnoses");
} else if ("echos".equals(word)) {
return Arrays.asList("echoes");
} else if ("elfs".equals(word)) {
return Arrays.asList("elves");
} else if ("ellipsises".equals(word)) {
return Arrays.asList("ellipses");
} else if ("embargos".equals(word)) {
return Arrays.asList("embargoes");
} else if ("erratums".equals(word)) {
return Arrays.asList("errata");
} else if ("firemans".equals(word)) {
return Arrays.asList("firemen");
} else if ("fishs".equals(word)) {
return Arrays.asList("fishes", "fish");
} else if ("genuses".equals(word)) {
return Arrays.asList("genera");
} else if ("gooses".equals(word)) {
return Arrays.asList("geese");
} else if ("halfs".equals(word)) {
return Arrays.asList("halves");
} else if ("heros".equals(word)) {
return Arrays.asList("heroes");
} else if ("indexs".equals(word)) {
return Arrays.asList("indices", "indexes");
} else if ("lifes".equals(word)) {
return Arrays.asList("lives");
} else if ("mans".equals(word)) {
return Arrays.asList("men");
} else if ("matrixs".equals(word)) {
return Arrays.asList("matrices");
} else if ("meanses".equals(word)) {
return Arrays.asList("means");
} else if ("mediums".equals(word)) {
return Arrays.asList("media");
} else if ("memorandums".equals(word)) {
return Arrays.asList("memoranda");
} else if ("mooses".equals(word)) {
return Arrays.asList("moose");
} else if ("mosquitos".equals(word)) {
return Arrays.asList("mosquitoes");
} else if ("neurosises".equals(word)) {
return Arrays.asList("neuroses");
} else if ("nucleuses".equals(word)) {
return Arrays.asList("nuclei");
} else if ("oasises".equals(word)) {
return Arrays.asList("oases");
} else if ("ovums".equals(word)) {
return Arrays.asList("ova");
} else if ("oxs".equals(word)) {
return Arrays.asList("oxen");
} else if ("oxes".equals(word)) {
return Arrays.asList("oxen");
} else if ("paralysises".equals(word)) {
return Arrays.asList("paralyses");
} else if ("potatos".equals(word)) {
return Arrays.asList("potatoes");
} else if ("radiuses".equals(word)) {
return Arrays.asList("radii");
} else if ("selfs".equals(word)) {
return Arrays.asList("selves");
} else if ("serieses".equals(word)) {
return Arrays.asList("series");
} else if ("sheeps".equals(word)) {
return Arrays.asList("sheep");
} else if ("shelfs".equals(word)) {
return Arrays.asList("shelves");
} else if ("scissorses".equals(word)) {
return Arrays.asList("scissors");
} else if ("specieses".equals(word)) {
return Arrays.asList("species");
} else if ("stimuluses".equals(word)) {
return Arrays.asList("stimuli");
} else if ("stratums".equals(word)) {
return Arrays.asList("strata");
} else if ("tableaus".equals(word)) {
return Arrays.asList("tableaux");
} else if ("thats".equals(word)) {
return Arrays.asList("those");
} else if ("thesises".equals(word)) {
return Arrays.asList("theses");
} else if ("thiefs".equals(word)) {
return Arrays.asList("thieves");
} else if ("thises".equals(word)) {
return Arrays.asList("these");
} else if ("tomatos".equals(word)) {
return Arrays.asList("tomatoes");
} else if ("tooths".equals(word)) {
return Arrays.asList("teeth");
} else if ("torpedos".equals(word)) {
return Arrays.asList("torpedoes");
} else if ("vertebras".equals(word)) {
return Arrays.asList("vertebrae");
} else if ("vetos".equals(word)) {
return Arrays.asList("vetoes");
} else if ("vitas".equals(word)) {
return Arrays.asList("vitae");
} else if ("watchs".equals(word)) {
return Arrays.asList("watches");
} else if ("wifes".equals(word)) {
return Arrays.asList("wives");
} else if ("womans".equals(word)) {
return Arrays.asList("women");
// AtD irregular plurals - END
} else if ("tippy-top".equals(word) || "tippytop".equals(word)) {
// "tippy-top" is an often used word by Donald Trump
return Arrays.asList("tip-top", "top most");
} else if ("imma".equals(word)) {
return Arrays.asList("I'm going to", "I'm a");
} else if ("Imma".equals(word)) {
return Arrays.asList("I'm going to", "I'm a");
} else if (word.endsWith("ys")) {
String suggestion = word.replaceFirst("ys$", "ies");
if (!speller1.isMisspelled(suggestion)) {
return Arrays.asList(suggestion);
}
}
return super.getAdditionalTopSuggestions(suggestions, word);
}
private static class IrregularForms {
final String baseform;
final String posName;
final String formName;
final List<String> forms;
private IrregularForms(String baseform, String posName, String formName, List<String> forms) {
this.baseform = baseform;
this.posName = posName;
this.formName = formName;
this.forms = forms;
}
}
}
| languagetool-language-modules/en/src/main/java/org/languagetool/rules/en/AbstractEnglishSpellerRule.java | /* LanguageTool, a natural language style checker
* Copyright (C) 2014 Daniel Naber (http://www.danielnaber.de)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.rules.en;
import org.jetbrains.annotations.Nullable;
import org.languagetool.*;
import org.languagetool.language.English;
import org.languagetool.languagemodel.LanguageModel;
import org.languagetool.rules.Example;
import org.languagetool.rules.RuleMatch;
import org.languagetool.rules.SuggestedReplacement;
import org.languagetool.rules.spelling.morfologik.MorfologikSpellerRule;
import org.languagetool.synthesis.en.EnglishSynthesizer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.*;
public abstract class AbstractEnglishSpellerRule extends MorfologikSpellerRule {
private static final EnglishSynthesizer synthesizer = new EnglishSynthesizer(new English());
public AbstractEnglishSpellerRule(ResourceBundle messages, Language language) throws IOException {
this(messages, language, null, Collections.emptyList());
}
/**
* @since 4.4
*/
public AbstractEnglishSpellerRule(ResourceBundle messages, Language language, UserConfig userConfig, List<Language> altLanguages) throws IOException {
this(messages, language, userConfig, altLanguages, null);
}
protected static Map<String,String> loadWordlist(String path, int column) {
if (column != 0 && column != 1) {
throw new IllegalArgumentException("Only column 0 and 1 are supported: " + column);
}
Map<String,String> words = new HashMap<>();
try (
InputStreamReader isr = new InputStreamReader(JLanguageTool.getDataBroker().getFromResourceDirAsStream(path), StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(isr);
) {
String line;
while ((line = br.readLine()) != null) {
line = line.trim();
if (line.isEmpty() || line.startsWith("#")) {
continue;
}
String[] parts = line.split(";");
if (parts.length != 2) {
throw new IOException("Unexpected format in " + path + ": " + line + " - expected two parts delimited by ';'");
}
words.put(parts[column], parts[column == 1 ? 0 : 1]);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return words;
}
/**
* @since 4.5
* optional: language model for better suggestions
*/
@Experimental
public AbstractEnglishSpellerRule(ResourceBundle messages, Language language, UserConfig userConfig,
List<Language> altLanguages, LanguageModel languageModel) throws IOException {
super(messages, language, userConfig, altLanguages, languageModel);
super.ignoreWordsWithLength = 1;
setCheckCompound(true);
addExamplePair(Example.wrong("This <marker>sentenc</marker> contains a spelling mistake."),
Example.fixed("This <marker>sentence</marker> contains a spelling mistake."));
String languageSpecificIgnoreFile = getSpellingFileName().replace(".txt", "_"+language.getShortCodeWithCountryAndVariant()+".txt");
for (String ignoreWord : wordListLoader.loadWords(languageSpecificIgnoreFile)) {
addIgnoreWords(ignoreWord);
}
}
@Override
protected List<RuleMatch> getRuleMatches(String word, int startPos, AnalyzedSentence sentence, List<RuleMatch> ruleMatchesSoFar, int idx, AnalyzedTokenReadings[] tokens) throws IOException {
List<RuleMatch> ruleMatches = super.getRuleMatches(word, startPos, sentence, ruleMatchesSoFar, idx, tokens);
if (ruleMatches.size() > 0) {
// so 'word' is misspelled:
IrregularForms forms = getIrregularFormsOrNull(word);
if (forms != null) {
String message = "Possible spelling mistake. Did you mean <suggestion>" + forms.forms.get(0) +
"</suggestion>, the " + forms.formName + " form of the " + forms.posName +
" '" + forms.baseform + "'?";
addFormsToFirstMatch(message, sentence, ruleMatches, forms.forms);
} else {
VariantInfo variantInfo = isValidInOtherVariant(word);
if (variantInfo != null) {
String message = "Possible spelling mistake. '" + word + "' is " + variantInfo.getVariantName() + ".";
replaceFormsOfFirstMatch(message, sentence, ruleMatches, variantInfo.otherVariant());
}
}
}
return ruleMatches;
}
/**
* @since 4.5
*/
@Nullable
protected VariantInfo isValidInOtherVariant(String word) {
return null;
}
private void addFormsToFirstMatch(String message, AnalyzedSentence sentence, List<RuleMatch> ruleMatches, List<String> forms) {
// recreating match, might overwrite information by SuggestionsRanker;
// this has precedence
RuleMatch oldMatch = ruleMatches.get(0);
RuleMatch newMatch = new RuleMatch(this, sentence, oldMatch.getFromPos(), oldMatch.getToPos(), message);
List<String> allSuggestions = new ArrayList<>(forms);
for (String repl : oldMatch.getSuggestedReplacements()) {
if (!allSuggestions.contains(repl)) {
allSuggestions.add(repl);
}
}
newMatch.setSuggestedReplacements(allSuggestions);
ruleMatches.set(0, newMatch);
}
private void replaceFormsOfFirstMatch(String message, AnalyzedSentence sentence, List<RuleMatch> ruleMatches, String suggestion) {
// recreating match, might overwrite information by SuggestionsRanker;
// this has precedence
RuleMatch oldMatch = ruleMatches.get(0);
RuleMatch newMatch = new RuleMatch(this, sentence, oldMatch.getFromPos(), oldMatch.getToPos(), message);
SuggestedReplacement sugg = new SuggestedReplacement(suggestion);
sugg.setShortDescription(language.getName());
newMatch.setSuggestedReplacementObjects(Collections.singletonList(sugg));
ruleMatches.set(0, newMatch);
}
@SuppressWarnings({"ReuseOfLocalVariable", "ControlFlowStatementWithoutBraces"})
@Nullable
private IrregularForms getIrregularFormsOrNull(String word) {
IrregularForms irregularFormsOrNull = getIrregularFormsOrNull(word, "ed", Arrays.asList("ed"), "VBD", "verb", "past tense");
if (irregularFormsOrNull != null) return irregularFormsOrNull;
irregularFormsOrNull = getIrregularFormsOrNull(word, "ed", Arrays.asList("d" /* e.g. awaked */), "VBD", "verb", "past tense");
if (irregularFormsOrNull != null) return irregularFormsOrNull;
irregularFormsOrNull = getIrregularFormsOrNull(word, "s", Arrays.asList("s"), "NNS", "noun", "plural");
if (irregularFormsOrNull != null) return irregularFormsOrNull;
irregularFormsOrNull = getIrregularFormsOrNull(word, "es", Arrays.asList("es"/* e.g. 'analysises' */), "NNS", "noun", "plural");
if (irregularFormsOrNull != null) return irregularFormsOrNull;
irregularFormsOrNull = getIrregularFormsOrNull(word, "er", Arrays.asList("er"/* e.g. 'farer' */), "JJR", "adjective", "comparative");
if (irregularFormsOrNull != null) return irregularFormsOrNull;
irregularFormsOrNull = getIrregularFormsOrNull(word, "est", Arrays.asList("est"/* e.g. 'farest' */), "JJS", "adjective", "superlative");
return irregularFormsOrNull;
}
@Nullable
private IrregularForms getIrregularFormsOrNull(String word, String wordSuffix, List<String> suffixes, String posTag, String posName, String formName) {
try {
for (String suffix : suffixes) {
if (word.endsWith(wordSuffix)) {
String baseForm = word.substring(0, word.length() - suffix.length());
String[] forms = synthesizer.synthesize(new AnalyzedToken(word, null, baseForm), posTag);
List<String> result = new ArrayList<>();
for (String form : forms) {
if (!speller1.isMisspelled(form)) {
// only accept suggestions that the spellchecker will accept
result.add(form);
}
}
// the internal dict might contain forms that the spell checker doesn't accept (e.g. 'criterions'),
// but we trust the spell checker in this case:
result.remove(word);
result.remove("badder"); // non-standard usage
result.remove("baddest"); // non-standard usage
result.remove("spake"); // can be removed after dict update
if (result.size() > 0) {
return new IrregularForms(baseForm, posName, formName, result);
}
}
}
return null;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* @since 2.7
*/
@Override
protected List<String> getAdditionalTopSuggestions(List<String> suggestions, String word) throws IOException {
if ("Alot".equals(word)) {
return Arrays.asList("A lot");
} else if ("alot".equals(word)) {
return Arrays.asList("a lot");
} else if ("thru".equals(word)) {
return Arrays.asList("through");
} else if ("speach".equals(word)) { // the replacement pairs would prefer "speak"
return Arrays.asList("speech");
} else if ("icecreem".equals(word)) {
return Arrays.asList("ice cream");
} else if ("fora".equals(word)) {
return Arrays.asList("for a");
} else if ("Boing".equals(word)) {
return Arrays.asList("Boeing");
} else if ("te".equals(word)) {
return Arrays.asList("the");
} else if ("todays".equals(word)) {
return Arrays.asList("today's");
} else if ("Todays".equals(word)) {
return Arrays.asList("Today's");
} else if ("todo".equals(word)) {
return Arrays.asList("to-do", "to do");
} else if ("Todo".equals(word)) {
return Arrays.asList("To-do", "To do");
} else if ("heres".equals(word)) {
return Arrays.asList("here's");
} else if ("Heres".equals(word)) {
return Arrays.asList("Here's");
} else if ("McDonalds".equals(word)) {
return Arrays.asList("McDonald's");
} else if ("ecommerce".equals(word)) {
return Arrays.asList("e-commerce");
} else if ("Ecommerce".equals(word)) {
return Arrays.asList("E-Commerce");
} else if ("eCommerce".equals(word)) {
return Arrays.asList("e-commerce");
} else if ("elearning".equals(word)) {
return Arrays.asList("e-learning");
} else if ("eLearning".equals(word)) {
return Arrays.asList("e-learning");
} else if ("ebook".equals(word)) {
return Arrays.asList("e-book");
} else if ("eBook".equals(word)) {
return Arrays.asList("e-book");
} else if ("Ebook".equals(word)) {
return Arrays.asList("E-Book");
} else if ("ie".equals(word)) {
return Arrays.asList("i.e.");
} else if ("eg".equals(word)) {
return Arrays.asList("e.g.");
} else if ("Thx".equals(word)) {
return Arrays.asList("Thanks");
} else if ("thx".equals(word)) {
return Arrays.asList("thanks");
} else if ("Sry".equals(word)) {
return Arrays.asList("Sorry");
} else if ("sry".equals(word)) {
return Arrays.asList("sorry");
} else if ("Lil".equals(word)) {
return Arrays.asList("Little");
} else if ("lil".equals(word)) {
return Arrays.asList("little");
} else if ("Sucka".equals(word)) {
return Arrays.asList("Sucker");
} else if ("sucka".equals(word)) {
return Arrays.asList("sucker");
} else if ("center".equals(word)) {
// For non-US English
return Arrays.asList("centre");
} else if ("ur".equals(word)) {
return Arrays.asList("your", "you are");
} else if ("Ur".equals(word)) {
return Arrays.asList("Your", "You are");
} else if ("ure".equals(word)) {
return Arrays.asList("your", "you are");
} else if ("Ure".equals(word)) {
return Arrays.asList("Your", "You are");
} else if ("mins".equals(word)) {
return Arrays.asList("minutes", "min");
} else if ("addon".equals(word)) {
return Arrays.asList("add-on");
} else if ("addons".equals(word)) {
return Arrays.asList("add-ons");
} else if ("afterparty".equals(word)) {
return Arrays.asList("after-party");
} else if ("Afterparty".equals(word)) {
return Arrays.asList("After-party");
} else if ("wellbeing".equals(word)) {
return Arrays.asList("well-being");
} else if ("cuz".equals(word)) {
return Arrays.asList("because");
} else if ("prio".equals(word)) {
return Arrays.asList("priority");
} else if ("prios".equals(word)) {
return Arrays.asList("priorities");
} else if ("gmail".equals(word)) {
return Arrays.asList("Gmail");
// AtD irregular plurals - START
} else if ("addendums".equals(word)) {
return Arrays.asList("addenda");
} else if ("algas".equals(word)) {
return Arrays.asList("algae");
} else if ("alumnas".equals(word)) {
return Arrays.asList("alumnae");
} else if ("alumnuses".equals(word)) {
return Arrays.asList("alumni");
} else if ("analysises".equals(word)) {
return Arrays.asList("analyses");
} else if ("appendixs".equals(word)) {
return Arrays.asList("appendices");
} else if ("axises".equals(word)) {
return Arrays.asList("axes");
} else if ("bacilluses".equals(word)) {
return Arrays.asList("bacilli");
} else if ("bacteriums".equals(word)) {
return Arrays.asList("bacteria");
} else if ("basises".equals(word)) {
return Arrays.asList("bases");
} else if ("beaus".equals(word)) {
return Arrays.asList("beaux");
} else if ("bisons".equals(word)) {
return Arrays.asList("bison");
} else if ("buffalos".equals(word)) {
return Arrays.asList("buffaloes");
} else if ("calfs".equals(word)) {
return Arrays.asList("calves");
} else if ("childs".equals(word)) {
return Arrays.asList("children");
} else if ("crisises".equals(word)) {
return Arrays.asList("crises");
} else if ("criterions".equals(word)) {
return Arrays.asList("criteria");
} else if ("curriculums".equals(word)) {
return Arrays.asList("curricula");
} else if ("datums".equals(word)) {
return Arrays.asList("data");
} else if ("deers".equals(word)) {
return Arrays.asList("deer");
} else if ("diagnosises".equals(word)) {
return Arrays.asList("diagnoses");
} else if ("echos".equals(word)) {
return Arrays.asList("echoes");
} else if ("elfs".equals(word)) {
return Arrays.asList("elves");
} else if ("ellipsises".equals(word)) {
return Arrays.asList("ellipses");
} else if ("embargos".equals(word)) {
return Arrays.asList("embargoes");
} else if ("erratums".equals(word)) {
return Arrays.asList("errata");
} else if ("firemans".equals(word)) {
return Arrays.asList("firemen");
} else if ("fishs".equals(word)) {
return Arrays.asList("fishes", "fish");
} else if ("genuses".equals(word)) {
return Arrays.asList("genera");
} else if ("gooses".equals(word)) {
return Arrays.asList("geese");
} else if ("halfs".equals(word)) {
return Arrays.asList("halves");
} else if ("heros".equals(word)) {
return Arrays.asList("heroes");
} else if ("indexs".equals(word)) {
return Arrays.asList("indices", "indexes");
} else if ("lifes".equals(word)) {
return Arrays.asList("lives");
} else if ("mans".equals(word)) {
return Arrays.asList("men");
} else if ("matrixs".equals(word)) {
return Arrays.asList("matrices");
} else if ("meanses".equals(word)) {
return Arrays.asList("means");
} else if ("mediums".equals(word)) {
return Arrays.asList("media");
} else if ("memorandums".equals(word)) {
return Arrays.asList("memoranda");
} else if ("mooses".equals(word)) {
return Arrays.asList("moose");
} else if ("mosquitos".equals(word)) {
return Arrays.asList("mosquitoes");
} else if ("neurosises".equals(word)) {
return Arrays.asList("neuroses");
} else if ("nucleuses".equals(word)) {
return Arrays.asList("nuclei");
} else if ("oasises".equals(word)) {
return Arrays.asList("oases");
} else if ("ovums".equals(word)) {
return Arrays.asList("ova");
} else if ("oxs".equals(word)) {
return Arrays.asList("oxen");
} else if ("oxes".equals(word)) {
return Arrays.asList("oxen");
} else if ("paralysises".equals(word)) {
return Arrays.asList("paralyses");
} else if ("potatos".equals(word)) {
return Arrays.asList("potatoes");
} else if ("radiuses".equals(word)) {
return Arrays.asList("radii");
} else if ("selfs".equals(word)) {
return Arrays.asList("selves");
} else if ("serieses".equals(word)) {
return Arrays.asList("series");
} else if ("sheeps".equals(word)) {
return Arrays.asList("sheep");
} else if ("shelfs".equals(word)) {
return Arrays.asList("shelves");
} else if ("scissorses".equals(word)) {
return Arrays.asList("scissors");
} else if ("specieses".equals(word)) {
return Arrays.asList("species");
} else if ("stimuluses".equals(word)) {
return Arrays.asList("stimuli");
} else if ("stratums".equals(word)) {
return Arrays.asList("strata");
} else if ("tableaus".equals(word)) {
return Arrays.asList("tableaux");
} else if ("thats".equals(word)) {
return Arrays.asList("those");
} else if ("thesises".equals(word)) {
return Arrays.asList("theses");
} else if ("thiefs".equals(word)) {
return Arrays.asList("thieves");
} else if ("thises".equals(word)) {
return Arrays.asList("these");
} else if ("tomatos".equals(word)) {
return Arrays.asList("tomatoes");
} else if ("tooths".equals(word)) {
return Arrays.asList("teeth");
} else if ("torpedos".equals(word)) {
return Arrays.asList("torpedoes");
} else if ("vertebras".equals(word)) {
return Arrays.asList("vertebrae");
} else if ("vetos".equals(word)) {
return Arrays.asList("vetoes");
} else if ("vitas".equals(word)) {
return Arrays.asList("vitae");
} else if ("watchs".equals(word)) {
return Arrays.asList("watches");
} else if ("wifes".equals(word)) {
return Arrays.asList("wives");
} else if ("womans".equals(word)) {
return Arrays.asList("women");
// AtD irregular plurals - END
} else if ("tippy-top".equals(word) || "tippytop".equals(word)) {
// "tippy-top" is an often used word by Donald Trump
return Arrays.asList("tip-top", "top most");
} else if (word.endsWith("ys")) {
String suggestion = word.replaceFirst("ys$", "ies");
if (!speller1.isMisspelled(suggestion)) {
return Arrays.asList(suggestion);
}
}
return super.getAdditionalTopSuggestions(suggestions, word);
}
private static class IrregularForms {
final String baseform;
final String posName;
final String formName;
final List<String> forms;
private IrregularForms(String baseform, String posName, String formName, List<String> forms) {
this.baseform = baseform;
this.posName = posName;
this.formName = formName;
this.forms = forms;
}
}
}
| [en] improve suggestion
| languagetool-language-modules/en/src/main/java/org/languagetool/rules/en/AbstractEnglishSpellerRule.java | [en] improve suggestion |
|
Java | apache-2.0 | f8f78eca61db6ad7685c2a7f3703e75fb3bad26e | 0 | skitt/maven,barthel/maven,Mounika-Chirukuri/maven,keith-turner/maven,likaiwalkman/maven,atanasenko/maven,xasx/maven,wangyuesong0/maven,vedmishr/demo1,likaiwalkman/maven,vedmishr/demo1,josephw/maven,stephenc/maven,olamy/maven,stephenc/maven,dsyer/maven,atanasenko/maven,ChristianSchulte/maven,josephw/maven,wangyuesong0/maven,changbai1980/maven,keith-turner/maven,xasx/maven,pkozelka/maven,apache/maven,mcculls/maven,runepeter/maven-deploy-plugin-2.8.1,mcculls/maven,stephenc/maven,trajano/maven,apache/maven,lbndev/maven,gorcz/maven,njuneau/maven,ChristianSchulte/maven,Tibor17/maven,Distrotech/maven,Tibor17/maven,josephw/maven,trajano/maven,trajano/maven,mcculls/maven,aheritier/maven,dsyer/maven,ChristianSchulte/maven,gorcz/maven,cstamas/maven,lbndev/maven,keith-turner/maven,olamy/maven,mizdebsk/maven,rogerchina/maven,wangyuesong0/maven,dsyer/maven,runepeter/maven-deploy-plugin-2.8.1,kidaa/maven-1,wangyuesong/maven,likaiwalkman/maven,kidaa/maven-1,karthikjaps/maven,lbndev/maven,cstamas/maven,Distrotech/maven,wangyuesong/maven,njuneau/maven,changbai1980/maven,olamy/maven,atanasenko/maven,skitt/maven,Mounika-Chirukuri/maven,barthel/maven,kidaa/maven-1,karthikjaps/maven,cstamas/maven,skitt/maven,rogerchina/maven,wangyuesong/maven,rogerchina/maven,Mounika-Chirukuri/maven,changbai1980/maven,njuneau/maven,mizdebsk/maven,xasx/maven,vedmishr/demo1,pkozelka/maven,gorcz/maven,apache/maven,aheritier/maven,mizdebsk/maven,aheritier/maven,pkozelka/maven,barthel/maven,karthikjaps/maven | package org.apache.maven.plugin;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.io.File;
import java.util.Properties;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.descriptor.MojoDescriptor;
import org.apache.maven.plugin.descriptor.PluginDescriptor;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.path.PathTranslator;
import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException;
import org.codehaus.plexus.component.configurator.expression.TypeAwareExpressionEvaluator;
import org.codehaus.plexus.logging.Logger;
import org.codehaus.plexus.util.introspection.ReflectionValueExtractor;
/**
* Evaluator for plugin parameters expressions. Content surrounded by <code>${</code> and <code>}</code> is evaluated.
* Recognized values are:<ul>
* <li><code>localRepository</code></li>
* <li><code>session</code></li>
* <li><code>session.*</code> (since Maven 3)</li>
* <li><code>reactorProjects</code></li>
* <li><code>mojoExecution</code></li>
* <li><code>project</code></li>
* <li><code>executedProject</code></li>
* <li><code>project.*</code></li>
* <li><code>pom.*</code> (since Maven 3)</li>
* <li><code>repositorySystemSession</code> (since Maven 3)</li>
* <li><code>mojo</code> (since Maven 3)</li>
* <li><code>mojo.*</code> (since Maven 3)</li>
* <li><code>plugin</code> (since Maven 3)</li>
* <li><code>plugin.*</code></li>
* <li><code>settings</code></li>
* <li><code>settings.*</code></li>
* <li><code>basedir</code></li>
* <li>system properties</li>
* <li>project properties</li>
* </ul>
* <i>Notice:</i> <code>reports</code> was supported in Maven 2.x but was removed in Maven 3
*
* @author Jason van Zyl
*/
public class PluginParameterExpressionEvaluator
implements TypeAwareExpressionEvaluator
{
private MavenSession session;
private MojoExecution mojoExecution;
private MavenProject project;
private String basedir;
private Properties properties;
@Deprecated //TODO: used by the Enforcer plugin
public PluginParameterExpressionEvaluator( MavenSession session, MojoExecution mojoExecution,
PathTranslator pathTranslator, Logger logger, MavenProject project,
Properties properties )
{
this( session, mojoExecution );
}
public PluginParameterExpressionEvaluator( MavenSession session )
{
this( session, null );
}
public PluginParameterExpressionEvaluator( MavenSession session, MojoExecution mojoExecution )
{
this.session = session;
this.mojoExecution = mojoExecution;
this.properties = session.getExecutionProperties();
this.project = session.getCurrentProject();
String basedir = null;
if ( project != null )
{
File projectFile = project.getBasedir();
// this should always be the case for non-super POM instances...
if ( projectFile != null )
{
basedir = projectFile.getAbsolutePath();
}
}
if ( ( basedir == null ) && ( session != null ) )
{
basedir = session.getExecutionRootDirectory();
}
if ( basedir == null )
{
basedir = System.getProperty( "user.dir" );
}
this.basedir = basedir;
}
public Object evaluate( String expr )
throws ExpressionEvaluationException
{
return evaluate( expr, null );
}
public Object evaluate( String expr, Class<?> type )
throws ExpressionEvaluationException
{
Object value = null;
if ( expr == null )
{
return null;
}
String expression = stripTokens( expr );
if ( expression.equals( expr ) )
{
int index = expr.indexOf( "${" );
if ( index >= 0 )
{
int lastIndex = expr.indexOf( "}", index );
if ( lastIndex >= 0 )
{
String retVal = expr.substring( 0, index );
if ( ( index > 0 ) && ( expr.charAt( index - 1 ) == '$' ) )
{
retVal += expr.substring( index + 1, lastIndex + 1 );
}
else
{
Object subResult = evaluate( expr.substring( index, lastIndex + 1 ) );
if ( subResult != null )
{
retVal += subResult;
}
else
{
retVal += "$" + expr.substring( index + 1, lastIndex + 1 );
}
}
retVal += evaluate( expr.substring( lastIndex + 1 ) );
return retVal;
}
}
// Was not an expression
if ( expression.indexOf( "$$" ) > -1 )
{
return expression.replaceAll( "\\$\\$", "\\$" );
}
else
{
return expression;
}
}
MojoDescriptor mojoDescriptor = mojoExecution.getMojoDescriptor();
if ( "localRepository".equals( expression ) )
{
value = session.getLocalRepository();
}
else if ( "session".equals( expression ) )
{
value = session;
}
else if ( expression.startsWith( "session" ) )
{
try
{
int pathSeparator = expression.indexOf( "/" );
if ( pathSeparator > 0 )
{
String pathExpression = expression.substring( 1, pathSeparator );
value = ReflectionValueExtractor.evaluate( pathExpression, session );
value = value + expression.substring( pathSeparator );
}
else
{
value = ReflectionValueExtractor.evaluate( expression.substring( 1 ), session );
}
}
catch ( Exception e )
{
// TODO: don't catch exception
throw new ExpressionEvaluationException( "Error evaluating plugin parameter expression: " + expression,
e );
}
}
else if ( "reactorProjects".equals( expression ) )
{
value = session.getProjects();
}
else if ( "mojoExecution".equals( expression ) )
{
value = mojoExecution;
}
else if ( "project".equals( expression ) )
{
value = project;
}
else if ( "executedProject".equals( expression ) )
{
value = project.getExecutionProject();
}
else if ( expression.startsWith( "project" ) || expression.startsWith( "pom" ) )
{
try
{
int pathSeparator = expression.indexOf( "/" );
if ( pathSeparator > 0 )
{
String pathExpression = expression.substring( 0, pathSeparator );
value = ReflectionValueExtractor.evaluate( pathExpression, project );
value = value + expression.substring( pathSeparator );
}
else
{
value = ReflectionValueExtractor.evaluate( expression.substring( 1 ), project );
}
}
catch ( Exception e )
{
// TODO: don't catch exception
throw new ExpressionEvaluationException( "Error evaluating plugin parameter expression: " + expression,
e );
}
}
else if ( expression.equals( "repositorySystemSession" ) )
{
value = session.getRepositorySession();
}
else if ( expression.equals( "mojo" ) )
{
value = mojoExecution;
}
else if ( expression.startsWith( "mojo" ) )
{
try
{
int pathSeparator = expression.indexOf( "/" );
if ( pathSeparator > 0 )
{
String pathExpression = expression.substring( 1, pathSeparator );
value = ReflectionValueExtractor.evaluate( pathExpression, mojoExecution );
value = value + expression.substring( pathSeparator );
}
else
{
value = ReflectionValueExtractor.evaluate( expression.substring( 1 ), mojoExecution );
}
}
catch ( Exception e )
{
// TODO: don't catch exception
throw new ExpressionEvaluationException( "Error evaluating plugin parameter expression: " + expression,
e );
}
}
else if ( expression.equals( "plugin" ) )
{
value = mojoDescriptor.getPluginDescriptor();
}
else if ( expression.startsWith( "plugin" ) )
{
try
{
int pathSeparator = expression.indexOf( "/" );
PluginDescriptor pluginDescriptor = mojoDescriptor.getPluginDescriptor();
if ( pathSeparator > 0 )
{
String pathExpression = expression.substring( 1, pathSeparator );
value = ReflectionValueExtractor.evaluate( pathExpression, pluginDescriptor );
value = value + expression.substring( pathSeparator );
}
else
{
value = ReflectionValueExtractor.evaluate( expression.substring( 1 ), pluginDescriptor );
}
}
catch ( Exception e )
{
throw new ExpressionEvaluationException( "Error evaluating plugin parameter expression: " + expression,
e );
}
}
else if ( "settings".equals( expression ) )
{
value = session.getSettings();
}
else if ( expression.startsWith( "settings" ) )
{
try
{
int pathSeparator = expression.indexOf( "/" );
if ( pathSeparator > 0 )
{
String pathExpression = expression.substring( 1, pathSeparator );
value = ReflectionValueExtractor.evaluate( pathExpression, session.getSettings() );
value = value + expression.substring( pathSeparator );
}
else
{
value = ReflectionValueExtractor.evaluate( expression.substring( 1 ), session.getSettings() );
}
}
catch ( Exception e )
{
// TODO: don't catch exception
throw new ExpressionEvaluationException( "Error evaluating plugin parameter expression: " + expression,
e );
}
}
else if ( "basedir".equals( expression ) )
{
value = basedir;
}
else if ( expression.startsWith( "basedir" ) )
{
int pathSeparator = expression.indexOf( "/" );
if ( pathSeparator > 0 )
{
value = basedir + expression.substring( pathSeparator );
}
}
/*
* MNG-4312: We neither have reserved all of the above magic expressions nor is their set fixed/well-known (it
* gets occasionally extended by newer Maven versions). This imposes the risk for existing plugins to
* unintentionally use such a magic expression for an ordinary system property. So here we check whether we
* ended up with a magic value that is not compatible with the type of the configured mojo parameter (a string
* could still be converted by the configurator so we leave those alone). If so, back off to evaluating the
* expression from properties only.
*/
if ( value != null && type != null && !( value instanceof String ) && !isTypeCompatible( type, value ) )
{
value = null;
}
if ( value == null )
{
// The CLI should win for defining properties
if ( ( value == null ) && ( properties != null ) )
{
// We will attempt to get nab a system property as a way to specify a
// parameter to a plugins. My particular case here is allowing the surefire
// plugin to run a single test so I want to specify that class on the cli
// as a parameter.
value = properties.getProperty( expression );
}
if ( ( value == null ) && ( ( project != null ) && ( project.getProperties() != null ) ) )
{
value = project.getProperties().getProperty( expression );
}
}
if ( value instanceof String )
{
// TODO: without #, this could just be an evaluate call...
String val = (String) value;
int exprStartDelimiter = val.indexOf( "${" );
if ( exprStartDelimiter >= 0 )
{
if ( exprStartDelimiter > 0 )
{
value = val.substring( 0, exprStartDelimiter ) + evaluate( val.substring( exprStartDelimiter ) );
}
else
{
value = evaluate( val.substring( exprStartDelimiter ) );
}
}
}
return value;
}
private static boolean isTypeCompatible( Class<?> type, Object value )
{
if ( type.isInstance( value ) )
{
return true;
}
// likely Boolean -> boolean, Short -> int etc. conversions, it's not the problem case we try to avoid
return ( ( type.isPrimitive() || type.getName().startsWith( "java.lang." ) )
&& value.getClass().getName().startsWith( "java.lang." ) );
}
private String stripTokens( String expr )
{
if ( expr.startsWith( "${" ) && ( expr.indexOf( "}" ) == expr.length() - 1 ) )
{
expr = expr.substring( 2, expr.length() - 1 );
}
return expr;
}
public File alignToBaseDirectory( File file )
{
// TODO: Copied from the DefaultInterpolator. We likely want to resurrect the PathTranslator or at least a
// similar component for re-usage
if ( file != null )
{
if ( file.isAbsolute() )
{
// path was already absolute, just normalize file separator and we're done
}
else if ( file.getPath().startsWith( File.separator ) )
{
// drive-relative Windows path, don't align with project directory but with drive root
file = file.getAbsoluteFile();
}
else
{
// an ordinary relative path, align with project directory
file = new File( new File( basedir, file.getPath() ).toURI().normalize() ).getAbsoluteFile();
}
}
return file;
}
}
| maven-core/src/main/java/org/apache/maven/plugin/PluginParameterExpressionEvaluator.java | package org.apache.maven.plugin;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.io.File;
import java.util.Properties;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.descriptor.MojoDescriptor;
import org.apache.maven.plugin.descriptor.PluginDescriptor;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.path.PathTranslator;
import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException;
import org.codehaus.plexus.component.configurator.expression.TypeAwareExpressionEvaluator;
import org.codehaus.plexus.logging.Logger;
import org.codehaus.plexus.util.introspection.ReflectionValueExtractor;
/**
* @author Jason van Zyl
*/
public class PluginParameterExpressionEvaluator
implements TypeAwareExpressionEvaluator
{
private MavenSession session;
private MojoExecution mojoExecution;
private MavenProject project;
private String basedir;
private Properties properties;
@Deprecated //TODO: used by the Enforcer plugin
public PluginParameterExpressionEvaluator( MavenSession session, MojoExecution mojoExecution,
PathTranslator pathTranslator, Logger logger, MavenProject project,
Properties properties )
{
this( session, mojoExecution );
}
public PluginParameterExpressionEvaluator( MavenSession session )
{
this( session, null );
}
public PluginParameterExpressionEvaluator( MavenSession session, MojoExecution mojoExecution )
{
this.session = session;
this.mojoExecution = mojoExecution;
this.properties = session.getExecutionProperties();
this.project = session.getCurrentProject();
String basedir = null;
if ( project != null )
{
File projectFile = project.getBasedir();
// this should always be the case for non-super POM instances...
if ( projectFile != null )
{
basedir = projectFile.getAbsolutePath();
}
}
if ( ( basedir == null ) && ( session != null ) )
{
basedir = session.getExecutionRootDirectory();
}
if ( basedir == null )
{
basedir = System.getProperty( "user.dir" );
}
this.basedir = basedir;
}
public Object evaluate( String expr )
throws ExpressionEvaluationException
{
return evaluate( expr, null );
}
public Object evaluate( String expr, Class<?> type )
throws ExpressionEvaluationException
{
Object value = null;
if ( expr == null )
{
return null;
}
String expression = stripTokens( expr );
if ( expression.equals( expr ) )
{
int index = expr.indexOf( "${" );
if ( index >= 0 )
{
int lastIndex = expr.indexOf( "}", index );
if ( lastIndex >= 0 )
{
String retVal = expr.substring( 0, index );
if ( ( index > 0 ) && ( expr.charAt( index - 1 ) == '$' ) )
{
retVal += expr.substring( index + 1, lastIndex + 1 );
}
else
{
Object subResult = evaluate( expr.substring( index, lastIndex + 1 ) );
if ( subResult != null )
{
retVal += subResult;
}
else
{
retVal += "$" + expr.substring( index + 1, lastIndex + 1 );
}
}
retVal += evaluate( expr.substring( lastIndex + 1 ) );
return retVal;
}
}
// Was not an expression
if ( expression.indexOf( "$$" ) > -1 )
{
return expression.replaceAll( "\\$\\$", "\\$" );
}
else
{
return expression;
}
}
MojoDescriptor mojoDescriptor = mojoExecution.getMojoDescriptor();
if ( "localRepository".equals( expression ) )
{
value = session.getLocalRepository();
}
else if ( "session".equals( expression ) )
{
value = session;
}
else if ( expression.startsWith( "session" ) )
{
try
{
int pathSeparator = expression.indexOf( "/" );
if ( pathSeparator > 0 )
{
String pathExpression = expression.substring( 1, pathSeparator );
value = ReflectionValueExtractor.evaluate( pathExpression, session );
value = value + expression.substring( pathSeparator );
}
else
{
value = ReflectionValueExtractor.evaluate( expression.substring( 1 ), session );
}
}
catch ( Exception e )
{
// TODO: don't catch exception
throw new ExpressionEvaluationException( "Error evaluating plugin parameter expression: " + expression,
e );
}
}
else if ( "reactorProjects".equals( expression ) )
{
value = session.getProjects();
}
else if ( "mojoExecution".equals( expression ) )
{
value = mojoExecution;
}
else if ( "project".equals( expression ) )
{
value = project;
}
else if ( "executedProject".equals( expression ) )
{
value = project.getExecutionProject();
}
else if ( expression.startsWith( "project" ) || expression.startsWith( "pom" ) )
{
try
{
int pathSeparator = expression.indexOf( "/" );
if ( pathSeparator > 0 )
{
String pathExpression = expression.substring( 0, pathSeparator );
value = ReflectionValueExtractor.evaluate( pathExpression, project );
value = value + expression.substring( pathSeparator );
}
else
{
value = ReflectionValueExtractor.evaluate( expression.substring( 1 ), project );
}
}
catch ( Exception e )
{
// TODO: don't catch exception
throw new ExpressionEvaluationException( "Error evaluating plugin parameter expression: " + expression,
e );
}
}
else if ( expression.equals( "repositorySystemSession" ) )
{
value = session.getRepositorySession();
}
else if ( expression.equals( "mojo" ) )
{
value = mojoExecution;
}
else if ( expression.startsWith( "mojo" ) )
{
try
{
int pathSeparator = expression.indexOf( "/" );
if ( pathSeparator > 0 )
{
String pathExpression = expression.substring( 1, pathSeparator );
value = ReflectionValueExtractor.evaluate( pathExpression, mojoExecution );
value = value + expression.substring( pathSeparator );
}
else
{
value = ReflectionValueExtractor.evaluate( expression.substring( 1 ), mojoExecution );
}
}
catch ( Exception e )
{
// TODO: don't catch exception
throw new ExpressionEvaluationException( "Error evaluating plugin parameter expression: " + expression,
e );
}
}
else if ( expression.equals( "plugin" ) )
{
value = mojoDescriptor.getPluginDescriptor();
}
else if ( expression.startsWith( "plugin" ) )
{
try
{
int pathSeparator = expression.indexOf( "/" );
PluginDescriptor pluginDescriptor = mojoDescriptor.getPluginDescriptor();
if ( pathSeparator > 0 )
{
String pathExpression = expression.substring( 1, pathSeparator );
value = ReflectionValueExtractor.evaluate( pathExpression, pluginDescriptor );
value = value + expression.substring( pathSeparator );
}
else
{
value = ReflectionValueExtractor.evaluate( expression.substring( 1 ), pluginDescriptor );
}
}
catch ( Exception e )
{
throw new ExpressionEvaluationException( "Error evaluating plugin parameter expression: " + expression,
e );
}
}
else if ( "settings".equals( expression ) )
{
value = session.getSettings();
}
else if ( expression.startsWith( "settings" ) )
{
try
{
int pathSeparator = expression.indexOf( "/" );
if ( pathSeparator > 0 )
{
String pathExpression = expression.substring( 1, pathSeparator );
value = ReflectionValueExtractor.evaluate( pathExpression, session.getSettings() );
value = value + expression.substring( pathSeparator );
}
else
{
value = ReflectionValueExtractor.evaluate( expression.substring( 1 ), session.getSettings() );
}
}
catch ( Exception e )
{
// TODO: don't catch exception
throw new ExpressionEvaluationException( "Error evaluating plugin parameter expression: " + expression,
e );
}
}
else if ( "basedir".equals( expression ) )
{
value = basedir;
}
else if ( expression.startsWith( "basedir" ) )
{
int pathSeparator = expression.indexOf( "/" );
if ( pathSeparator > 0 )
{
value = basedir + expression.substring( pathSeparator );
}
}
/*
* MNG-4312: We neither have reserved all of the above magic expressions nor is their set fixed/well-known (it
* gets occasionally extended by newer Maven versions). This imposes the risk for existing plugins to
* unintentionally use such a magic expression for an ordinary system property. So here we check whether we
* ended up with a magic value that is not compatible with the type of the configured mojo parameter (a string
* could still be converted by the configurator so we leave those alone). If so, back off to evaluating the
* expression from properties only.
*/
if ( value != null && type != null && !( value instanceof String ) && !isTypeCompatible( type, value ) )
{
value = null;
}
if ( value == null )
{
// The CLI should win for defining properties
if ( ( value == null ) && ( properties != null ) )
{
// We will attempt to get nab a system property as a way to specify a
// parameter to a plugins. My particular case here is allowing the surefire
// plugin to run a single test so I want to specify that class on the cli
// as a parameter.
value = properties.getProperty( expression );
}
if ( ( value == null ) && ( ( project != null ) && ( project.getProperties() != null ) ) )
{
value = project.getProperties().getProperty( expression );
}
}
if ( value instanceof String )
{
// TODO: without #, this could just be an evaluate call...
String val = (String) value;
int exprStartDelimiter = val.indexOf( "${" );
if ( exprStartDelimiter >= 0 )
{
if ( exprStartDelimiter > 0 )
{
value = val.substring( 0, exprStartDelimiter ) + evaluate( val.substring( exprStartDelimiter ) );
}
else
{
value = evaluate( val.substring( exprStartDelimiter ) );
}
}
}
return value;
}
private static boolean isTypeCompatible( Class<?> type, Object value )
{
if ( type.isInstance( value ) )
{
return true;
}
// likely Boolean -> boolean, Short -> int etc. conversions, it's not the problem case we try to avoid
return ( ( type.isPrimitive() || type.getName().startsWith( "java.lang." ) )
&& value.getClass().getName().startsWith( "java.lang." ) );
}
private String stripTokens( String expr )
{
if ( expr.startsWith( "${" ) && ( expr.indexOf( "}" ) == expr.length() - 1 ) )
{
expr = expr.substring( 2, expr.length() - 1 );
}
return expr;
}
public File alignToBaseDirectory( File file )
{
// TODO: Copied from the DefaultInterpolator. We likely want to resurrect the PathTranslator or at least a
// similar component for re-usage
if ( file != null )
{
if ( file.isAbsolute() )
{
// path was already absolute, just normalize file separator and we're done
}
else if ( file.getPath().startsWith( File.separator ) )
{
// drive-relative Windows path, don't align with project directory but with drive root
file = file.getAbsoluteFile();
}
else
{
// an ordinary relative path, align with project directory
file = new File( new File( basedir, file.getPath() ).toURI().normalize() ).getAbsoluteFile();
}
}
return file;
}
}
| added javadoc
git-svn-id: d3061b52f177ba403f02f0a296a85518da96c313@1340266 13f79535-47bb-0310-9956-ffa450edef68
| maven-core/src/main/java/org/apache/maven/plugin/PluginParameterExpressionEvaluator.java | added javadoc |
|
Java | apache-2.0 | dbd9b4b0710f3ab59ed9fe2ac9638d1ee615de8c | 0 | mikaelkindborg/cordova-ble,evothings/cordova-ble,divineprog/cordova-ble,divineprog/cordova-ble,mikaelkindborg/cordova-ble,evothings/cordova-ble,divineprog/cordova-ble,mikaelkindborg/cordova-ble,evothings/cordova-ble | /*
Copyright 2014 Evothings AB
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.evothings;
import org.apache.cordova.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.bluetooth.*;
import android.bluetooth.le.*;
import android.bluetooth.BluetoothAdapter.LeScanCallback;
import android.content.*;
import android.app.Activity;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Iterator;
import java.util.UUID;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.*;
import android.util.Base64;
import android.os.ParcelUuid;
import android.util.Log;
import android.content.pm.PackageManager;
import android.os.Build;
import android.Manifest;
public class BLE
extends CordovaPlugin
implements
LeScanCallback
{
// ************* BLE CENTRAL ROLE *************
// Implementation of BLE Central API.
private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
// Used by startScan().
private CallbackContext mScanCallbackContext;
private CordovaArgs mScanArgs;
// Used by reset().
private CallbackContext mResetCallbackContext;
// The Android application Context.
private Context mContext;
private boolean mRegisteredReceiver = false;
// Called when the device's Bluetooth powers on.
// Used by startScan() and connect() to wait for power-on if Bluetooth was
// off when the function was called.
private Runnable mOnPowerOn;
// Used to send error messages to the JavaScript side if Bluetooth power-on fails.
private CallbackContext mPowerOnCallbackContext;
// Map of connected devices.
HashMap<Integer, GattHandler> mConnectedDevices = null;
// Monotonically incrementing key to the Gatt map.
int mNextGattHandle = 1;
// Called each time cordova.js is loaded.
@Override
public void initialize(final CordovaInterface cordova, CordovaWebView webView)
{
super.initialize(cordova, webView);
mContext = webView.getContext();
if(!mRegisteredReceiver) {
mContext.registerReceiver(
new BluetoothStateReceiver(),
new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
mRegisteredReceiver = true;
}
}
// Handles JavaScript-to-native function calls.
// Returns true if a supported function was called, false otherwise.
@Override
public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext)
{
try {
if("startScan".equals(action)) { startScan(args, callbackContext); return true; }
else if("stopScan".equals(action)) { stopScan(args, callbackContext); return true; }
else if("connect".equals(action)) { connect(args, callbackContext); return true; }
else if("close".equals(action)) { close(args, callbackContext); return true; }
else if("rssi".equals(action)) { rssi(args, callbackContext); return true; }
else if("services".equals(action)) { services(args, callbackContext); return true; }
else if("characteristics".equals(action)) { characteristics(args, callbackContext); return true; }
else if("descriptors".equals(action)) { descriptors(args, callbackContext); return true; }
else if("readCharacteristic".equals(action)) { readCharacteristic(args, callbackContext); return true; }
else if("readDescriptor".equals(action)) { readDescriptor(args, callbackContext); return true; }
else if("writeCharacteristic".equals(action))
{ writeCharacteristic(args, callbackContext, BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT); return true; }
else if("writeCharacteristicWithoutResponse".equals(action))
{ writeCharacteristic(args, callbackContext, BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE); return true; }
else if("writeDescriptor".equals(action)) { writeDescriptor(args, callbackContext); return true; }
else if("enableNotification".equals(action)) { enableNotification(args, callbackContext); return true; }
else if("disableNotification".equals(action)) { disableNotification(args, callbackContext); return true; }
else if("testCharConversion".equals(action)) { testCharConversion(args, callbackContext); return true; }
else if("reset".equals(action)) { reset(args, callbackContext); return true; }
else if("startAdvertise".equals(action)) { startAdvertise(args, callbackContext); return true; }
else if("stopAdvertise".equals(action)) { stopAdvertise(args, callbackContext); return true; }
else if("startGattServer".equals(action)) { startGattServer(args, callbackContext); return true; }
else if("stopGattServer".equals(action)) { stopGattServer(args, callbackContext); return true; }
else if("sendResponse".equals(action)) { sendResponse(args, callbackContext); return true; }
else if("notify".equals(action)) { notify(args, callbackContext); return true; }
} catch(JSONException e) {
e.printStackTrace();
callbackContext.error(e.getMessage());
}
return false;
}
/**
* Called when the WebView does a top-level navigation or refreshes.
*
* Plugins should stop any long-running processes and clean up internal state.
*
* Does nothing by default.
*
* Our version should stop any ongoing scan, and close any existing connections.
*/
@Override
public void onReset()
{
if(mScanCallbackContext != null) {
BluetoothAdapter a = BluetoothAdapter.getDefaultAdapter();
a.stopLeScan(this);
mScanCallbackContext = null;
}
if(mConnectedDevices != null) {
Iterator<GattHandler> itr = mConnectedDevices.values().iterator();
while(itr.hasNext()) {
GattHandler gh = itr.next();
if(gh.mGatt != null)
gh.mGatt.close();
}
mConnectedDevices.clear();
}
if(mGattServer != null) {
mGattServer.close();
mGattServer = null;
}
}
// Possibly asynchronous.
// Ensures Bluetooth is powered on, then calls the Runnable \a onPowerOn.
// Calls cc.error if power-on fails.
private void checkPowerState(BluetoothAdapter adapter, CallbackContext cc, Runnable onPowerOn)
{
if(adapter == null) {
cc.error("Bluetooth not supported");
return;
}
if(adapter.getState() == BluetoothAdapter.STATE_ON) {
// Bluetooth is ON
onPowerOn.run();
} else {
mOnPowerOn = onPowerOn;
mPowerOnCallbackContext = cc;
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
cordova.startActivityForResult(this, enableBtIntent, 0);
}
}
// Called whe the Bluetooth power-on request is completed.
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
Runnable onPowerOn = mOnPowerOn;
CallbackContext cc = mPowerOnCallbackContext;
mOnPowerOn = null;
mPowerOnCallbackContext = null;
if(resultCode == Activity.RESULT_OK) {
if (null != onPowerOn) {
onPowerOn.run();
} else {
// Runnable was null.
if (null != cc) cc.error("Runnable is null in onActivityResult (internal error)");
}
} else {
if(resultCode == Activity.RESULT_CANCELED) {
if (null != cc) cc.error("Bluetooth power-on canceled");
} else {
if (null != cc) cc.error("Bluetooth power-on failed with code: "+resultCode);
}
}
}
// These three functions each send a JavaScript callback *without* removing
// the callback context, as is default.
private void keepCallback(final CallbackContext callbackContext, JSONObject message)
{
PluginResult r = new PluginResult(PluginResult.Status.OK, message);
r.setKeepCallback(true);
if (callbackContext != null) {
callbackContext.sendPluginResult(r);
}
}
private void keepCallback(final CallbackContext callbackContext, String message)
{
PluginResult r = new PluginResult(PluginResult.Status.OK, message);
r.setKeepCallback(true);
if (callbackContext != null) {
callbackContext.sendPluginResult(r);
}
}
private void keepCallback(final CallbackContext callbackContext, byte[] message)
{
PluginResult r = new PluginResult(PluginResult.Status.OK, message);
r.setKeepCallback(true);
if (callbackContext != null) {
callbackContext.sendPluginResult(r);
}
}
// Callback from cordova.requestPermissions().
@Override
public void onRequestPermissionResult(int requestCode, String[] permissions,
int[] grantResults) throws JSONException
{
//Log.i("@@@@@@@@", "onRequestPermissionsResult: " + permissions + " " + grantResults);
if (PERMISSION_REQUEST_COARSE_LOCATION == requestCode)
{
if (PackageManager.PERMISSION_GRANTED == grantResults[0])
{
//Log.i("@@@@@@@@", "Coarse location permission granted");
// Permission ok, start scanning.
startScanImpl(mScanArgs, mScanCallbackContext);
}
else
{
//Log.i("@@@@@@@@", "Coarse location permission NOT granted");
// Permission NOT ok, send callback error.
mScanCallbackContext.error("Location permission not granted");
mScanCallbackContext = null;
}
}
}
// API implementation. See ble.js for documentation.
private void startScan(final CordovaArgs args, final CallbackContext callbackContext)
{
// Save callback context.
mScanCallbackContext = callbackContext;
mScanArgs = args;
// Cordova Permission check
if (!cordova.hasPermission(Manifest.permission.ACCESS_COARSE_LOCATION))
{
//Log.i("@@@@@@@@", "PERMISSION NEEDED");
// Permission needed. Ask user.
cordova.requestPermission(this, PERMISSION_REQUEST_COARSE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION);
return;
}
// Permission ok, go ahead and start scanning.
startScanImpl(mScanArgs, mScanCallbackContext);
}
private void startScanImpl(final CordovaArgs args, final CallbackContext callbackContext)
{
//Log.i("@@@@@@", "Start scan");
final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
final LeScanCallback self = this;
// Get service UUIDs.
UUID[] uuidArray = null;
try
{
JSONArray uuids = args.getJSONArray(0);
if (null != uuids)
{
uuidArray = new UUID[uuids.length()];
for (int i = 0; i < uuids.length(); ++i)
{
uuidArray[i] = UUID.fromString(uuids.getString(i));
}
}
}
catch(JSONException ex)
{
uuidArray = null;
}
final UUID[] serviceUUIDs = uuidArray;
checkPowerState(adapter, callbackContext, new Runnable()
{
@Override
public void run()
{
if(!adapter.startLeScan(serviceUUIDs, self))
{
//Log.i("@@@@@@", "Start scan failed");
callbackContext.error("Android function startLeScan failed");
mScanCallbackContext = null;
return;
}
}
});
}
// Called during scan, when a device advertisement is received.
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord)
{
//Log.i("@@@@@@", "onLeScan");
if (mScanCallbackContext == null)
{
return;
}
try
{
//Log.i("@@@@@@", "onLeScan "+device.getAddress()+" "+rssi+" "+device.getName());
//System.out.println("onLeScan "+device.getAddress()+" "+rssi+" "+device.getName());
JSONObject jsonObject = new JSONObject();
jsonObject.put("address", device.getAddress());
jsonObject.put("rssi", rssi);
jsonObject.put("name", device.getName());
jsonObject.put("scanRecord", Base64.encodeToString(scanRecord, Base64.NO_WRAP));
keepCallback(mScanCallbackContext, jsonObject);
}
catch(JSONException e)
{
mScanCallbackContext.error(e.toString());
}
}
// API implementation.
private void stopScan(final CordovaArgs args, final CallbackContext callbackContext)
{
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
adapter.stopLeScan(this);
mScanCallbackContext = null;
}
// API implementation.
private void connect(final CordovaArgs args, final CallbackContext callbackContext)
{
final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
checkPowerState(adapter, callbackContext, new Runnable()
{
@Override
public void run()
{
try {
// Each device connection has a GattHandler, which handles the events the can happen to the connection.
// The implementation of the GattHandler class is found at the end of this file.
GattHandler gh = new GattHandler(mNextGattHandle, callbackContext);
gh.mGatt = adapter.getRemoteDevice(args.getString(0)).connectGatt(mContext, true, gh);
// Note that gh.mGatt and this.mGatt are different object and have different types.
// --> Renamed this.mGatt to mConnectedDevices to avoid confusion.
if(mConnectedDevices == null)
mConnectedDevices = new HashMap<Integer, GattHandler>();
Object res = mConnectedDevices.put(mNextGattHandle, gh);
assert(res == null);
mNextGattHandle++;
} catch(Exception e) {
e.printStackTrace();
callbackContext.error(e.toString());
}
}
});
}
// API implementation.
private void close(final CordovaArgs args, final CallbackContext callbackContext)
{
try {
GattHandler gh = mConnectedDevices.get(args.getInt(0));
gh.mGatt.close();
mConnectedDevices.remove(args.getInt(0));
} catch(JSONException e) {
e.printStackTrace();
callbackContext.error(e.toString());
}
}
// API implementation.
private void rssi(final CordovaArgs args, final CallbackContext callbackContext)
{
GattHandler gh = null;
try {
gh = mConnectedDevices.get(args.getInt(0));
if(gh.mRssiContext != null) {
callbackContext.error("Previous call to rssi() not yet completed!");
return;
}
gh.mRssiContext = callbackContext;
if(!gh.mGatt.readRemoteRssi()) {
gh.mRssiContext = null;
callbackContext.error("readRemoteRssi");
}
} catch(Exception e) {
e.printStackTrace();
if(gh != null) {
gh.mRssiContext = null;
}
callbackContext.error(e.toString());
}
}
// API implementation.
private void services(final CordovaArgs args, final CallbackContext callbackContext)
{
try {
final GattHandler gh = mConnectedDevices.get(args.getInt(0));
gh.mOperations.add(new Runnable() {
@Override
public void run() {
gh.mCurrentOpContext = callbackContext;
if(!gh.mGatt.discoverServices()) {
gh.mCurrentOpContext = null;
callbackContext.error("discoverServices");
gh.process();
}
}
});
gh.process();
} catch(Exception e) {
e.printStackTrace();
callbackContext.error(e.toString());
}
}
// API implementation.
private void characteristics(
final CordovaArgs args,
final CallbackContext callbackContext)
throws JSONException
{
final GattHandler gh = mConnectedDevices.get(args.getInt(0));
JSONArray a = new JSONArray();
for(BluetoothGattCharacteristic c : gh.mServices.get(args.getInt(1)).getCharacteristics()) {
if(gh.mCharacteristics == null)
gh.mCharacteristics = new HashMap<Integer, BluetoothGattCharacteristic>();
Object res = gh.mCharacteristics.put(gh.mNextHandle, c);
assert(res == null);
JSONObject o = new JSONObject();
o.put("handle", gh.mNextHandle);
o.put("uuid", c.getUuid().toString());
o.put("permissions", c.getPermissions());
o.put("properties", c.getProperties());
o.put("writeType", c.getWriteType());
gh.mNextHandle++;
a.put(o);
}
callbackContext.success(a);
}
// API implementation.
private void descriptors(
final CordovaArgs args,
final CallbackContext callbackContext)
throws JSONException
{
final GattHandler gh = mConnectedDevices.get(args.getInt(0));
JSONArray a = new JSONArray();
for(BluetoothGattDescriptor d : gh.mCharacteristics.get(args.getInt(1)).getDescriptors()) {
if(gh.mDescriptors == null)
gh.mDescriptors = new HashMap<Integer, BluetoothGattDescriptor>();
Object res = gh.mDescriptors.put(gh.mNextHandle, d);
assert(res == null);
JSONObject o = new JSONObject();
o.put("handle", gh.mNextHandle);
o.put("uuid", d.getUuid().toString());
o.put("permissions", d.getPermissions());
gh.mNextHandle++;
a.put(o);
}
callbackContext.success(a);
}
// API implementation.
private void readCharacteristic(
final CordovaArgs args,
final CallbackContext callbackContext)
throws JSONException
{
final GattHandler gh = mConnectedDevices.get(args.getInt(0));
gh.mOperations.add(new Runnable() {
@Override
public void run() {
try {
gh.mCurrentOpContext = callbackContext;
if(!gh.mGatt.readCharacteristic(gh.mCharacteristics.get(args.getInt(1)))) {
gh.mCurrentOpContext = null;
callbackContext.error("readCharacteristic");
gh.process();
}
} catch(JSONException e) {
e.printStackTrace();
callbackContext.error(e.toString());
gh.process();
}
}
});
gh.process();
}
// API implementation.
private void readDescriptor(
final CordovaArgs args,
final CallbackContext callbackContext)
throws JSONException
{
final GattHandler gh = mConnectedDevices.get(args.getInt(0));
gh.mOperations.add(new Runnable()
{
@Override
public void run()
{
try {
gh.mCurrentOpContext = callbackContext;
if(!gh.mGatt.readDescriptor(gh.mDescriptors.get(args.getInt(1)))) {
gh.mCurrentOpContext = null;
callbackContext.error("readDescriptor");
gh.process();
}
} catch(JSONException e) {
e.printStackTrace();
callbackContext.error(e.toString());
gh.process();
}
}
});
gh.process();
}
// API implementation.
private void writeCharacteristic(
final CordovaArgs args,
final CallbackContext callbackContext,
final int writeType)
throws JSONException
{
final GattHandler gh = mConnectedDevices.get(args.getInt(0));
gh.mOperations.add(new Runnable()
{
@Override
public void run()
{
try {
gh.mCurrentOpContext = callbackContext;
BluetoothGattCharacteristic c = gh.mCharacteristics.get(args.getInt(1));
System.out.println("writeCharacteristic("+args.getInt(0)+", "+args.getInt(1)+", "+args.getString(2)+")");
c.setWriteType(writeType);
c.setValue(args.getArrayBuffer(2));
if(!gh.mGatt.writeCharacteristic(c)) {
gh.mCurrentOpContext = null;
callbackContext.error("writeCharacteristic");
gh.process();
}
} catch(JSONException e) {
e.printStackTrace();
callbackContext.error(e.toString());
gh.process();
}
}
});
gh.process();
}
// API implementation.
private void writeDescriptor(
final CordovaArgs args,
final CallbackContext callbackContext)
throws JSONException
{
final GattHandler gh = mConnectedDevices.get(args.getInt(0));
gh.mOperations.add(new Runnable()
{
@Override
public void run()
{
try {
gh.mCurrentOpContext = callbackContext;
BluetoothGattDescriptor d = gh.mDescriptors.get(args.getInt(1));
d.setValue(args.getArrayBuffer(2));
if(!gh.mGatt.writeDescriptor(d)) {
gh.mCurrentOpContext = null;
callbackContext.error("writeDescriptor");
gh.process();
}
} catch(JSONException e) {
e.printStackTrace();
callbackContext.error(e.toString());
gh.process();
}
}
});
gh.process();
}
// Notification options flag.
private final int NOTIFICATION_OPTIONS_DISABLE_AUTOMATIC_CONFIG = 1;
// API implementation.
private void enableNotification(
final CordovaArgs args,
final CallbackContext callbackContext)
throws JSONException
{
final GattHandler gh = mConnectedDevices.get(args.getInt(0));
// Get characteristic.
BluetoothGattCharacteristic characteristic = gh.mCharacteristics.get(args.getInt(1));
// Get options flag.
int options = args.getInt(2);
// Turn notification on.
boolean setConfigDescriptor = (options == 0);
turnNotificationOn(callbackContext, gh, gh.mGatt, characteristic, setConfigDescriptor);
}
// API implementation.
private void disableNotification(
final CordovaArgs args,
final CallbackContext callbackContext)
throws JSONException
{
final GattHandler gh = mConnectedDevices.get(args.getInt(0));
// Get characteristic.
BluetoothGattCharacteristic characteristic = gh.mCharacteristics.get(args.getInt(1));
// Get options flag.
int options = args.getInt(2);
// Turn notification off.
boolean setConfigDescriptor = (options == 0);
turnNotificationOff(callbackContext, gh, gh.mGatt, characteristic, setConfigDescriptor);
}
// Helper method.
private void turnNotificationOn(
final CallbackContext callbackContext,
final GattHandler gattHandler,
final BluetoothGatt gatt,
final BluetoothGattCharacteristic characteristic,
final boolean setConfigDescriptor)
{
gattHandler.mOperations.add(new Runnable()
{
@Override
public void run()
{
try {
// Mark operation in progress.
gattHandler.mCurrentOp = true;
if (setConfigDescriptor) {
// Write the config descriptor and enable notification.
if (enableConfigDescriptor(callbackContext, gattHandler, gatt, characteristic)) {
enableNotification(callbackContext, gattHandler, gatt, characteristic);
}
}
else {
// Enable notification without writing config descriptor.
// This is useful for applications that want to manually
// set the config descriptor.
enableNotification(callbackContext, gattHandler, gatt, characteristic);
}
}
catch (Exception e) {
e.printStackTrace();
callbackContext.error("Exception when enabling notification");
gattHandler.process();
}
}
});
gattHandler.process();
}
// Helper method.
private boolean enableConfigDescriptor(
final CallbackContext callbackContext,
final GattHandler gattHandler,
final BluetoothGatt gatt,
final BluetoothGattCharacteristic characteristic)
{
// Get config descriptor.
BluetoothGattDescriptor configDescriptor = characteristic.getDescriptor(
UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
if (configDescriptor == null) {
callbackContext.error("Could not get config descriptor");
gattHandler.process();
return false;
}
// Config descriptor value.
byte[] descriptorValue;
// Check if notification or indication should be used.
if (0 != (characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY)) {
descriptorValue = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE;
}
else if (0 != (characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_INDICATE)) {
descriptorValue = BluetoothGattDescriptor.ENABLE_INDICATION_VALUE;
}
else {
callbackContext.error("Characteristic does not support notification or indication.");
gattHandler.process();
return false;
}
// Set value of config descriptor.
configDescriptor.setValue(descriptorValue);
// Write descriptor.
boolean success = gatt.writeDescriptor(configDescriptor);
if (!success) {
callbackContext.error("Could not write config descriptor");
gattHandler.process();
return false;
}
return true;
}
// Helper method.
private void enableNotification(
final CallbackContext callbackContext,
final GattHandler gattHandler,
final BluetoothGatt gatt,
final BluetoothGattCharacteristic characteristic)
{
// Turn notification on.
boolean success = gatt.setCharacteristicNotification(characteristic, true);
if (!success) {
callbackContext.error("Could not enable notification");
gattHandler.process();
return;
}
// Save callback context for the characteristic.
// When turning notification on, the success callback will be
// called on every notification event.
gattHandler.mNotifications.put(characteristic, callbackContext);
}
// Helper method.
private void turnNotificationOff(
final CallbackContext callbackContext,
final GattHandler gattHandler,
final BluetoothGatt gatt,
final BluetoothGattCharacteristic characteristic,
final boolean setConfigDescriptor)
{
gattHandler.mOperations.add(new Runnable()
{
@Override
public void run()
{
try {
// Mark operation in progress.
gattHandler.mCurrentOp = true;
// Remove callback context for the characteristic
// when turning off notification.
gattHandler.mNotifications.remove(characteristic);
if (setConfigDescriptor) {
// Write the config descriptor and disable notification.
if (disableConfigDescriptor(callbackContext, gattHandler, gatt, characteristic)) {
disableNotification(callbackContext, gattHandler, gatt, characteristic);
}
}
else {
// Disable notification without writing config descriptor.
// This is useful for applications that want to manually
// set the config descriptor.
disableNotification(callbackContext, gattHandler, gatt, characteristic);
}
}
catch (Exception e) {
e.printStackTrace();
callbackContext.error("Exception when disabling notification");
gattHandler.process();
}
}
});
gattHandler.process();
}
// Helper method.
private boolean disableConfigDescriptor(
final CallbackContext callbackContext,
final GattHandler gattHandler,
final BluetoothGatt gatt,
final BluetoothGattCharacteristic characteristic)
{
// Get config descriptor.
BluetoothGattDescriptor configDescriptor = characteristic.getDescriptor(
UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
if (configDescriptor == null) {
callbackContext.error("Could not get config descriptor");
gattHandler.process();
return false;
}
// Set value of config descriptor.
byte[] descriptorValue = BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE;
configDescriptor.setValue(descriptorValue);
// Write descriptor.
boolean success = gatt.writeDescriptor(configDescriptor);
if (!success) {
callbackContext.error("Could not write config descriptor");
gattHandler.process();
return false;
}
return true;
}
// Helper method.
private void disableNotification(
final CallbackContext callbackContext,
final GattHandler gattHandler,
final BluetoothGatt gatt,
final BluetoothGattCharacteristic characteristic)
{
// Turn notification off.
boolean success = gatt.setCharacteristicNotification(characteristic, false);
if (!success) {
callbackContext.error("Could not disable notification");
gattHandler.process();
return;
}
// Call success callback when notification is turned off.
callbackContext.success();
}
// API implementation.
private void testCharConversion(
final CordovaArgs args,
final CallbackContext callbackContext)
throws JSONException
{
byte[] b = {(byte)args.getInt(0)};
callbackContext.success(b);
}
// API implementation.
private void reset(final CordovaArgs args, final CallbackContext cc) throws JSONException
{
mResetCallbackContext = null;
BluetoothAdapter a = BluetoothAdapter.getDefaultAdapter();
if(mScanCallbackContext != null) {
a.stopLeScan(this);
mScanCallbackContext = null;
}
int state = a.getState();
//STATE_OFF, STATE_TURNING_ON, STATE_ON, STATE_TURNING_OFF.
if(state == BluetoothAdapter.STATE_TURNING_ON) {
// reset in progress; wait for STATE_ON.
mResetCallbackContext = cc;
return;
}
if(state == BluetoothAdapter.STATE_TURNING_OFF) {
// reset in progress; wait for STATE_OFF.
mResetCallbackContext = cc;
return;
}
if(state == BluetoothAdapter.STATE_OFF) {
boolean res = a.enable();
if(res) {
mResetCallbackContext = cc;
} else {
cc.error("enable");
}
return;
}
if(state == BluetoothAdapter.STATE_ON) {
boolean res = a.disable();
if(res) {
mResetCallbackContext = cc;
} else {
cc.error("disable");
}
return;
}
cc.error("Unknown state: "+state);
}
// Receives notification about Bluetooth power on and off. Used by reset().
class BluetoothStateReceiver extends BroadcastReceiver
{
public void onReceive(Context context, Intent intent)
{
BluetoothAdapter a = BluetoothAdapter.getDefaultAdapter();
int state = a.getState();
System.out.println("BluetoothState: "+a);
if(mResetCallbackContext != null) {
if(state == BluetoothAdapter.STATE_OFF) {
boolean res = a.enable();
if(!res) {
mResetCallbackContext.error("enable");
mResetCallbackContext = null;
}
}
if(state == BluetoothAdapter.STATE_ON) {
mResetCallbackContext.success();
mResetCallbackContext = null;
}
}
}
};
/* Running more than one operation of certain types on remote Gatt devices
* seem to cause it to stop responding.
* The known types are 'read' and 'write'.
* I've added 'services' to be on the safe side.
* 'rssi' and 'notification' should be safe.
*/
// This class handles callbacks pertaining to device connections.
// Also maintains the per-device operation queue.
private class GattHandler extends BluetoothGattCallback
{
// Local copy of the key to BLE.mGatt. Fed by BLE.mNextGattHandle.
final int mHandle;
// The queue of operations.
LinkedList<Runnable> mOperations = new LinkedList<Runnable>();
// connect() and rssi() are handled separately from other operations.
CallbackContext mConnectContext;
CallbackContext mRssiContext;
CallbackContext mCurrentOpContext;
// Special flag for doing async operations without a Cordova callback context.
// Used when writing notification config descriptor.
boolean mCurrentOp = false;
// The Android API connection.
BluetoothGatt mGatt;
// Maps of integer to Gatt subobject.
HashMap<Integer, BluetoothGattService> mServices;
HashMap<Integer, BluetoothGattCharacteristic> mCharacteristics;
HashMap<Integer, BluetoothGattDescriptor> mDescriptors;
// Monotonically incrementing key to the subobject maps.
int mNextHandle = 1;
// Notification callbacks. The BluetoothGattCharacteristic object, as found
// in the mCharacteristics map, is the key.
HashMap<BluetoothGattCharacteristic, CallbackContext> mNotifications =
new HashMap<BluetoothGattCharacteristic, CallbackContext>();
GattHandler(int h, CallbackContext cc)
{
mHandle = h;
mConnectContext = cc;
}
// Run the next operation, if any.
void process()
{
if(mCurrentOpContext != null || mCurrentOp)
return;
Runnable r = mOperations.poll();
if(r == null)
return;
r.run();
}
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState)
{
if(status == BluetoothGatt.GATT_SUCCESS) {
try {
JSONObject o = new JSONObject();
o.put("deviceHandle", mHandle);
o.put("state", newState);
keepCallback(mConnectContext, o);
} catch(JSONException e) {
e.printStackTrace();
assert(false);
}
} else {
mConnectContext.error(status);
}
}
@Override
public void onReadRemoteRssi(BluetoothGatt g, int rssi, int status)
{
CallbackContext c = mRssiContext;
mRssiContext = null;
if(status == BluetoothGatt.GATT_SUCCESS) {
c.success(rssi);
} else {
c.error(status);
}
}
@Override
public void onServicesDiscovered(BluetoothGatt g, int status)
{
if(status == BluetoothGatt.GATT_SUCCESS) {
List<BluetoothGattService> services = g.getServices();
JSONArray a = new JSONArray();
for(BluetoothGattService s : services) {
// give the service a handle.
if(mServices == null)
mServices = new HashMap<Integer, BluetoothGattService>();
Object res = mServices.put(mNextHandle, s);
assert(res == null);
try {
JSONObject o = new JSONObject();
o.put("handle", mNextHandle);
o.put("uuid", s.getUuid().toString());
o.put("type", s.getType());
mNextHandle++;
a.put(o);
} catch(JSONException e) {
e.printStackTrace();
assert(false);
}
}
mCurrentOpContext.success(a);
} else {
mCurrentOpContext.error(status);
}
mCurrentOpContext = null;
process();
}
@Override
public void onCharacteristicRead(BluetoothGatt g, BluetoothGattCharacteristic c, int status)
{
if(status == BluetoothGatt.GATT_SUCCESS) {
mCurrentOpContext.success(c.getValue());
} else {
mCurrentOpContext.error(status);
}
mCurrentOpContext = null;
process();
}
@Override
public void onDescriptorRead(BluetoothGatt g, BluetoothGattDescriptor d, int status)
{
if(status == BluetoothGatt.GATT_SUCCESS) {
mCurrentOpContext.success(d.getValue());
} else {
mCurrentOpContext.error(status);
}
mCurrentOpContext = null;
process();
}
@Override
public void onCharacteristicWrite(BluetoothGatt g, BluetoothGattCharacteristic c, int status)
{
if(status == BluetoothGatt.GATT_SUCCESS) {
mCurrentOpContext.success();
} else {
mCurrentOpContext.error(status);
}
mCurrentOpContext = null;
process();
}
@Override
public void onDescriptorWrite(BluetoothGatt g, BluetoothGattDescriptor d, int status)
{
// We write the notification config descriptor in native code,
// and in this case there is no callback context. Thus we check
// if the context is null here.
// TODO: Encapsulate exposed instance variables in this file,
// use method calls instead.
if (mCurrentOpContext != null) {
if (status == BluetoothGatt.GATT_SUCCESS) {
mCurrentOpContext.success();
} else {
mCurrentOpContext.error(status);
}
mCurrentOpContext = null;
}
mCurrentOp = false;
process();
}
@Override
public void onCharacteristicChanged(BluetoothGatt g, BluetoothGattCharacteristic c)
{
CallbackContext cc = mNotifications.get(c);
keepCallback(cc, c.getValue());
}
}
// ************* BLE PERIPHERAL ROLE *************
// Implementation of advertisement API.
private BluetoothLeAdvertiser mAdvertiser;
private AdvertiseCallback mAdCallback;
private AdvertiseSettings buildAdvertiseSettings(JSONObject setJson) throws JSONException
{
AdvertiseSettings.Builder setBuild = new AdvertiseSettings.Builder();
{
String advModeString = setJson.optString("advertiseMode", "ADVERTISE_MODE_LOW_POWER");
int advMode;
if(advModeString.equals("ADVERTISE_MODE_LOW_POWER"))
advMode = AdvertiseSettings.ADVERTISE_MODE_LOW_POWER;
else if(advModeString.equals("ADVERTISE_MODE_BALANCED"))
advMode = AdvertiseSettings.ADVERTISE_MODE_BALANCED;
else if(advModeString.equals("ADVERTISE_MODE_LOW_LATENCY"))
advMode = AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY;
else
throw new JSONException("Invalid advertiseMode: "+advModeString);
setBuild.setAdvertiseMode(advMode);
}
boolean connectable = setJson.optBoolean("connectable", mGattServer != null);
System.out.println("connectable: "+connectable);
setBuild.setConnectable(connectable);
setBuild.setTimeout(setJson.optInt("timeoutMillis", 0));
{
String advModeString = setJson.optString("txPowerLevel", "ADVERTISE_TX_POWER_MEDIUM");
int advMode;
if(advModeString.equals("ADVERTISE_TX_POWER_ULTRA_LOW"))
advMode = AdvertiseSettings.ADVERTISE_TX_POWER_ULTRA_LOW;
else if(advModeString.equals("ADVERTISE_TX_POWER_LOW"))
advMode = AdvertiseSettings.ADVERTISE_TX_POWER_LOW;
else if(advModeString.equals("ADVERTISE_TX_POWER_MEDIUM"))
advMode = AdvertiseSettings.ADVERTISE_TX_POWER_MEDIUM;
else if(advModeString.equals("ADVERTISE_TX_POWER_HIGH"))
advMode = AdvertiseSettings.ADVERTISE_TX_POWER_HIGH;
else
throw new JSONException("Invalid txPowerLevel");
setBuild.setTxPowerLevel(advMode);
}
return setBuild.build();
}
private AdvertiseData buildAdvertiseData(JSONObject dataJson) throws JSONException
{
if(dataJson == null)
return null;
AdvertiseData.Builder dataBuild = new AdvertiseData.Builder();
dataBuild.setIncludeDeviceName(dataJson.optBoolean("includeDeviceName", false));
dataBuild.setIncludeTxPowerLevel(dataJson.optBoolean("includeTxPowerLevel", false));
JSONArray serviceUUIDs = dataJson.optJSONArray("serviceUUIDs");
if(serviceUUIDs != null) {
for(int i=0; i<serviceUUIDs.length(); i++) {
dataBuild.addServiceUuid(new ParcelUuid(UUID.fromString(serviceUUIDs.getString(i))));
}
}
JSONObject serviceData = dataJson.optJSONObject("serviceData");
if(serviceData != null) {
Iterator<String> keys = serviceData.keys();
while(keys.hasNext()) {
String key = keys.next();
ParcelUuid uuid = new ParcelUuid(UUID.fromString(key));
byte[] data = Base64.decode(serviceData.getString(key), Base64.DEFAULT);
dataBuild.addServiceData(uuid, data);
}
}
JSONObject manufacturerData = dataJson.optJSONObject("manufacturerData");
if(manufacturerData != null) {
Iterator<String> keys = manufacturerData.keys();
while(keys.hasNext()) {
String key = keys.next();
int id = Integer.parseInt(key);
byte[] data = Base64.decode(manufacturerData.getString(key), Base64.DEFAULT);
dataBuild.addManufacturerData(id, data);
}
}
return dataBuild.build();
}
private void startAdvertise(final CordovaArgs args, final CallbackContext cc) throws JSONException
{
if(mAdCallback != null) {
cc.error("Advertise must be stopped first!");
return;
}
final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if(!adapter.isMultipleAdvertisementSupported()) {
cc.error("BLE advertisement not supported by this device!");
return;
}
JSONObject setJson = args.getJSONObject(0);
// build settings. this checks arguments for validity.
final AdvertiseSettings settings = buildAdvertiseSettings(setJson);
// build data. this checks arguments for validity.
final AdvertiseData broadcastData = buildAdvertiseData(setJson.getJSONObject("broadcastData"));
final AdvertiseData scanResponseData = buildAdvertiseData(setJson.optJSONObject("scanResponseData"));
mAdCallback = new AdvertiseCallback()
{
@Override
public void onStartFailure(int errorCode)
{
mAdCallback = null;
// translate available error codes using reflection.
// we're looking for all fields typed "public static final int".
Field[] fields = AdvertiseCallback.class.getDeclaredFields();
String errorMessage = null;
for(int i=0; i<fields.length; i++) {
Field f = fields[i];
System.out.println("Field: Class "+f.getType().getName()+". Modifiers: "+Modifier.toString(f.getModifiers()));
if(f.getType() == int.class &&
f.getModifiers() == (Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL))
{
try {
if(f.getInt(null) == errorCode) {
errorMessage = f.getName();
break;
}
} catch(IllegalAccessException e) {
// if this happens, it is an internal error.
e.printStackTrace();
}
}
}
if(errorMessage == null) {
errorMessage = Integer.toString(errorCode);
}
cc.error("AdvertiseCallback.onStartFailure: "+errorMessage);
}
public void onStartSuccess(AdvertiseSettings settingsInEffect)
{
cc.success();
}
};
// ensure Bluetooth is powered on, then start advertising.
checkPowerState(adapter, cc, new Runnable()
{
@Override
public void run()
{
try {
mAdvertiser = adapter.getBluetoothLeAdvertiser();
if(scanResponseData != null) {
mAdvertiser.startAdvertising(settings, broadcastData, scanResponseData, mAdCallback);
} else {
mAdvertiser.startAdvertising(settings, broadcastData, mAdCallback);
}
} catch(Exception e) {
mAdCallback = null;
e.printStackTrace();
cc.error(e.toString());
}
}
});
}
private void stopAdvertise(final CordovaArgs args, final CallbackContext cc)
{
if(mAdvertiser != null && mAdCallback != null) {
mAdvertiser.stopAdvertising(mAdCallback);
mAdCallback = null;
}
cc.success();
}
private BluetoothGattServer mGattServer;
private MyBluetoothGattServerCallback mGattServerCallback;
private void startGattServer(final CordovaArgs args, final CallbackContext cc) throws JSONException
{
if(mGattServer != null) {
cc.error("GATT server already started!");
return;
}
JSONObject settings = args.getJSONObject(0);
mGattServerCallback = new MyBluetoothGattServerCallback(settings.getInt("nextHandle"), cc);
mGattServer = ((BluetoothManager)mContext.getSystemService(Context.BLUETOOTH_SERVICE))
.openGattServer(mContext, mGattServerCallback);
JSONArray services = settings.getJSONArray("services");
for(int i=0; i<services.length(); i++) {
JSONObject service = services.getJSONObject(i);
BluetoothGattService s = new BluetoothGattService(
UUID.fromString(service.getString("uuid")), service.getInt("type"));
JSONArray characteristics = service.optJSONArray("characteristics");
if(characteristics != null) {
for(int j=0; j<characteristics.length(); j++) {
JSONObject characteristic = characteristics.getJSONObject(j);
System.out.println("characteristic:"+characteristic.toString(1));
BluetoothGattCharacteristic c = new BluetoothGattCharacteristic(
UUID.fromString(characteristic.getString("uuid")),
characteristic.getInt("properties"), characteristic.getInt("permissions"));
mGattServerCallback.mReadHandles.put(c, characteristic.getInt("onReadRequestHandle"));
mGattServerCallback.mWriteHandles.put(c, characteristic.getInt("onWriteRequestHandle"));
JSONArray descriptors = characteristic.optJSONArray("descriptors");
if(descriptors != null) for(int k=0; k<descriptors.length(); k++) {
JSONObject descriptor = descriptors.getJSONObject(k);
System.out.println("descriptor:"+descriptor.toString(1));
BluetoothGattDescriptor d = new BluetoothGattDescriptor(
UUID.fromString(descriptor.getString("uuid")),
descriptor.getInt("permissions"));
c.addDescriptor(d);
mGattServerCallback.mReadHandles.put(d, descriptor.getInt("onReadRequestHandle"));
mGattServerCallback.mWriteHandles.put(d, descriptor.getInt("onWriteRequestHandle"));
}
s.addCharacteristic(c);
}
}
mGattServer.addService(s);
}
keepCallback(cc, new JSONObject().put("name", "win"));
}
private void stopGattServer(final CordovaArgs args, final CallbackContext cc)
{
if(mGattServer == null) {
cc.error("GATT server not started!");
return;
}
mGattServer.close();
mGattServer = null;
cc.success();
}
class MyBluetoothGattServerCallback extends BluetoothGattServerCallback
{
// Bidirectional maps; look up object from handle, or handle from object.
// The JavaScript side needs handles, the native side needs objects.
public HashMap<Integer, BluetoothDevice> mDevices;
public HashMap<Object, Integer> mDeviceHandles;
public HashMap<Object, Integer> mReadHandles;
public HashMap<Object, Integer> mWriteHandles;
int mNextHandle;
CallbackContext mCC;
CallbackContext mNotifyCC;
MyBluetoothGattServerCallback(int nextHandle, final CallbackContext cc)
{
mNextHandle = nextHandle;
mDevices = new HashMap<Integer, BluetoothDevice>();
mDeviceHandles = new HashMap<Object, Integer>();
mReadHandles = new HashMap<Object, Integer>();
mWriteHandles = new HashMap<Object, Integer>();
mCC = cc;
}
@Override
public void onConnectionStateChange(BluetoothDevice device, int status, int newState)
{
System.out.println("onConnectionStateChange("+device.getAddress()+", "+status+", "+newState+")");
Integer handle = mDeviceHandles.get(device);
if(handle == null) {
handle = new Integer(mNextHandle++);
mDeviceHandles.put(device, handle);
mDevices.put(handle, device);
}
try {
keepCallback(mCC, new JSONObject()
.put("name", "connection")
.put("deviceHandle", handle)
.put("connected", newState == BluetoothProfile.STATE_CONNECTED)
);
} catch(JSONException e) {
throw new Error(e);
}
}
@Override
public void onCharacteristicReadRequest(
BluetoothDevice device,
int requestId,
int offset,
BluetoothGattCharacteristic characteristic)
{
System.out.println("onCharacteristicReadRequest("+device.getAddress()+", "+requestId+", "+offset+")");
Integer handle = mDeviceHandles.get(device);
try {
keepCallback(mCC, new JSONObject()
.put("name", "read")
.put("deviceHandle", handle)
.put("requestId", requestId)
.put("callbackHandle", mReadHandles.get(characteristic))
);
} catch(JSONException e) {
throw new Error(e);
}
}
@Override
public void onDescriptorReadRequest(
BluetoothDevice device,
int requestId,
int offset,
BluetoothGattDescriptor descriptor)
{
System.out.println("onDescriptorReadRequest("+device.getAddress()+", "+requestId+", "+offset+")");
Integer handle = mDeviceHandles.get(device);
try {
keepCallback(mCC, new JSONObject()
.put("name", "read")
.put("deviceHandle", handle)
.put("requestId", requestId)
.put("callbackHandle", mReadHandles.get(descriptor))
);
} catch(JSONException e) {
throw new Error(e);
}
}
@Override
public void onCharacteristicWriteRequest(
BluetoothDevice device,
int requestId,
BluetoothGattCharacteristic characteristic,
boolean preparedWrite,
boolean responseNeeded,
int offset,
byte[] value)
{
System.out.println("onCharacteristicWriteRequest("+device.getAddress()+", "+requestId+", "+offset+")");
Integer handle = mDeviceHandles.get(device);
try {
keepCallback(mCC, new JSONObject()
.put("name", "write")
.put("deviceHandle", handle)
.put("requestId", requestId)
.put("data", value)
.put("callbackHandle", mWriteHandles.get(characteristic))
);
} catch(JSONException e) {
throw new Error(e);
}
}
@Override
public void onDescriptorWriteRequest(
BluetoothDevice device,
int requestId,
BluetoothGattDescriptor descriptor,
boolean preparedWrite,
boolean responseNeeded,
int offset,
byte[] value)
{
System.out.println("onDescriptorWriteRequest("+device.getAddress()+", "+requestId+", "+offset+")");
Integer handle = mDeviceHandles.get(device);
try {
keepCallback(mCC, new JSONObject()
.put("name", "write")
.put("deviceHandle", handle)
.put("requestId", requestId)
.put("data", value)
.put("callbackHandle", mWriteHandles.get(descriptor))
);
} catch(JSONException e) {
throw new Error(e);
}
}
@Override
public void onExecuteWrite(BluetoothDevice device, int requestId, boolean execute)
{
System.out.println("onExecuteWrite("+device.getAddress()+", "+requestId+", "+execute+")");
mGattServer.sendResponse(device, requestId, 0, 0, null);
}
@Override
public void onMtuChanged(BluetoothDevice device, int mtu)
{
System.out.println("onMtuChanged("+mtu+")");
}
@Override
public void onNotificationSent(BluetoothDevice device, int status)
{
System.out.println("onNotificationSent("+device.getAddress()+", "+status+")");
if(status == BluetoothGatt.GATT_SUCCESS)
mNotifyCC.success();
else
mNotifyCC.error(status);
mNotifyCC = null;
}
@Override
public void onServiceAdded(int status, BluetoothGattService service)
{
System.out.println("onServiceAdded("+status+")");
}
}
private void sendResponse(final CordovaArgs args, final CallbackContext cc) throws JSONException
{
if(mGattServer == null) {
cc.error("GATT server not started!");
return;
}
int deviceHandle = args.getInt(0);
int requestId = args.getInt(1);
byte[] data = args.getArrayBuffer(2);
boolean res = mGattServer.sendResponse(
mGattServerCallback.mDevices.get(deviceHandle),
requestId,
0,
0,
data);
System.out.println("sendResponse result: "+res);
cc.success();
}
private void notify(final CordovaArgs args, final CallbackContext cc) throws JSONException
{
if(mGattServer == null) {
cc.error("GATT server not started!");
return;
}
}
}
| src/android/BLE.java | /*
Copyright 2014 Evothings AB
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.evothings;
import org.apache.cordova.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.bluetooth.*;
import android.bluetooth.le.*;
import android.bluetooth.BluetoothAdapter.LeScanCallback;
import android.content.*;
import android.app.Activity;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Iterator;
import java.util.UUID;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.*;
import android.util.Base64;
import android.os.ParcelUuid;
import android.util.Log;
import android.content.pm.PackageManager;
import android.os.Build;
import android.Manifest;
public class BLE
extends CordovaPlugin
implements
LeScanCallback
{
// ************* BLE CENTRAL ROLE *************
// Implementation of BLE Central API.
private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
// Used by startScan().
private CallbackContext mScanCallbackContext;
private CordovaArgs mScanArgs;
// Used by reset().
private CallbackContext mResetCallbackContext;
// The Android application Context.
private Context mContext;
private boolean mRegisteredReceiver = false;
// Called when the device's Bluetooth powers on.
// Used by startScan() and connect() to wait for power-on if Bluetooth was
// off when the function was called.
private Runnable mOnPowerOn;
// Used to send error messages to the JavaScript side if Bluetooth power-on fails.
private CallbackContext mPowerOnCallbackContext;
// Map of connected devices.
HashMap<Integer, GattHandler> mConnectedDevices = null;
// Monotonically incrementing key to the Gatt map.
int mNextGattHandle = 1;
// Called each time cordova.js is loaded.
@Override
public void initialize(final CordovaInterface cordova, CordovaWebView webView)
{
super.initialize(cordova, webView);
mContext = webView.getContext();
if(!mRegisteredReceiver) {
mContext.registerReceiver(
new BluetoothStateReceiver(),
new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
mRegisteredReceiver = true;
}
}
// Handles JavaScript-to-native function calls.
// Returns true if a supported function was called, false otherwise.
@Override
public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext)
{
try {
if("startScan".equals(action)) { startScan(args, callbackContext); return true; }
else if("stopScan".equals(action)) { stopScan(args, callbackContext); return true; }
else if("connect".equals(action)) { connect(args, callbackContext); return true; }
else if("close".equals(action)) { close(args, callbackContext); return true; }
else if("rssi".equals(action)) { rssi(args, callbackContext); return true; }
else if("services".equals(action)) { services(args, callbackContext); return true; }
else if("characteristics".equals(action)) { characteristics(args, callbackContext); return true; }
else if("descriptors".equals(action)) { descriptors(args, callbackContext); return true; }
else if("readCharacteristic".equals(action)) { readCharacteristic(args, callbackContext); return true; }
else if("readDescriptor".equals(action)) { readDescriptor(args, callbackContext); return true; }
else if("writeCharacteristic".equals(action))
{ writeCharacteristic(args, callbackContext, BluetoothGattCharacteristic.WRITE_TYPE_DEFAULT); return true; }
else if("writeCharacteristicWithoutResponse".equals(action))
{ writeCharacteristic(args, callbackContext, BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE); return true; }
else if("writeDescriptor".equals(action)) { writeDescriptor(args, callbackContext); return true; }
else if("enableNotification".equals(action)) { enableNotification(args, callbackContext); return true; }
else if("disableNotification".equals(action)) { disableNotification(args, callbackContext); return true; }
else if("testCharConversion".equals(action)) { testCharConversion(args, callbackContext); return true; }
else if("reset".equals(action)) { reset(args, callbackContext); return true; }
else if("startAdvertise".equals(action)) { startAdvertise(args, callbackContext); return true; }
else if("stopAdvertise".equals(action)) { stopAdvertise(args, callbackContext); return true; }
else if("startGattServer".equals(action)) { startGattServer(args, callbackContext); return true; }
else if("stopGattServer".equals(action)) { stopGattServer(args, callbackContext); return true; }
else if("sendResponse".equals(action)) { sendResponse(args, callbackContext); return true; }
else if("notify".equals(action)) { notify(args, callbackContext); return true; }
} catch(JSONException e) {
e.printStackTrace();
callbackContext.error(e.getMessage());
}
return false;
}
/**
* Called when the WebView does a top-level navigation or refreshes.
*
* Plugins should stop any long-running processes and clean up internal state.
*
* Does nothing by default.
*
* Our version should stop any ongoing scan, and close any existing connections.
*/
@Override
public void onReset()
{
if(mScanCallbackContext != null) {
BluetoothAdapter a = BluetoothAdapter.getDefaultAdapter();
a.stopLeScan(this);
mScanCallbackContext = null;
}
if(mConnectedDevices != null) {
Iterator<GattHandler> itr = mConnectedDevices.values().iterator();
while(itr.hasNext()) {
GattHandler gh = itr.next();
if(gh.mGatt != null)
gh.mGatt.close();
}
mConnectedDevices.clear();
}
if(mGattServer != null) {
mGattServer.close();
mGattServer = null;
}
}
// Possibly asynchronous.
// Ensures Bluetooth is powered on, then calls the Runnable \a onPowerOn.
// Calls cc.error if power-on fails.
private void checkPowerState(BluetoothAdapter adapter, CallbackContext cc, Runnable onPowerOn)
{
if(adapter == null) {
cc.error("Bluetooth not supported");
return;
}
if(adapter.getState() == BluetoothAdapter.STATE_ON) {
// Bluetooth is ON
onPowerOn.run();
} else {
mOnPowerOn = onPowerOn;
mPowerOnCallbackContext = cc;
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
cordova.startActivityForResult(this, enableBtIntent, 0);
}
}
// Called whe the Bluetooth power-on request is completed.
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
Runnable onPowerOn = mOnPowerOn;
CallbackContext cc = mPowerOnCallbackContext;
mOnPowerOn = null;
mPowerOnCallbackContext = null;
if(resultCode == Activity.RESULT_OK) {
if (null != onPowerOn) {
onPowerOn.run();
} else {
// Runnable was null.
if (null != cc) cc.error("Runnable is null in onActivityResult (internal error)");
}
} else {
if(resultCode == Activity.RESULT_CANCELED) {
if (null != cc) cc.error("Bluetooth power-on canceled");
} else {
if (null != cc) cc.error("Bluetooth power-on failed with code: "+resultCode);
}
}
}
// These three functions each send a JavaScript callback *without* removing
// the callback context, as is default.
private void keepCallback(final CallbackContext callbackContext, JSONObject message)
{
PluginResult r = new PluginResult(PluginResult.Status.OK, message);
r.setKeepCallback(true);
if (callbackContext != null) {
callbackContext.sendPluginResult(r);
}
}
private void keepCallback(final CallbackContext callbackContext, String message)
{
PluginResult r = new PluginResult(PluginResult.Status.OK, message);
r.setKeepCallback(true);
if (callbackContext != null) {
callbackContext.sendPluginResult(r);
}
}
private void keepCallback(final CallbackContext callbackContext, byte[] message)
{
PluginResult r = new PluginResult(PluginResult.Status.OK, message);
r.setKeepCallback(true);
if (callbackContext != null) {
callbackContext.sendPluginResult(r);
}
}
// Callback from cordova.requestPermissions().
@Override
public void onRequestPermissionResult(int requestCode, String[] permissions,
int[] grantResults) throws JSONException
{
//Log.i("@@@@@@@@", "onRequestPermissionsResult: " + permissions + " " + grantResults);
if (PERMISSION_REQUEST_COARSE_LOCATION == requestCode)
{
if (PackageManager.PERMISSION_GRANTED == grantResults[0])
{
//Log.i("@@@@@@@@", "Coarse location permission granted");
// Permission ok, start scanning.
startScanImpl(mScanArgs, mScanCallbackContext);
}
else
{
//Log.i("@@@@@@@@", "Coarse location permission NOT granted");
// Permission NOT ok, send callback error.
mScanCallbackContext.error("Location permission not granted");
mScanCallbackContext = null;
}
}
}
// API implementation. See ble.js for documentation.
private void startScan(final CordovaArgs args, final CallbackContext callbackContext)
{
// Save callback context.
mScanCallbackContext = callbackContext;
mScanArgs = args;
// Cordova Permission check
if (!cordova.hasPermission(Manifest.permission.ACCESS_COARSE_LOCATION))
{
//Log.i("@@@@@@@@", "PERMISSION NEEDED");
// Permission needed. Ask user.
cordova.requestPermission(this, PERMISSION_REQUEST_COARSE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION);
return;
}
// Permission ok, go ahead and start scanning.
startScanImpl(mScanArgs, mScanCallbackContext);
}
private void startScanImpl(final CordovaArgs args, final CallbackContext callbackContext)
{
//Log.i("@@@@@@", "Start scan");
final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
final LeScanCallback self = this;
// Get service UUIDs.
UUID[] uuidArray = null;
try
{
JSONArray uuids = args.getJSONArray(0);
if (null != uuids)
{
uuidArray = new UUID[uuids.length()];
for (int i = 0; i < uuids.length(); ++i)
{
uuidArray[i] = UUID.fromString(uuids.getString(i));
}
}
}
catch(JSONException ex)
{
uuidArray = null;
}
final UUID[] serviceUUIDs = uuidArray;
checkPowerState(adapter, callbackContext, new Runnable()
{
@Override
public void run()
{
if(!adapter.startLeScan(serviceUUIDs, self))
{
//Log.i("@@@@@@", "Start scan failed");
callbackContext.error("Android function startLeScan failed");
mScanCallbackContext = null;
return;
}
}
});
}
// Called during scan, when a device advertisement is received.
public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord)
{
//Log.i("@@@@@@", "onLeScan");
if (mScanCallbackContext == null)
{
return;
}
try
{
//Log.i("@@@@@@", "onLeScan "+device.getAddress()+" "+rssi+" "+device.getName());
//System.out.println("onLeScan "+device.getAddress()+" "+rssi+" "+device.getName());
JSONObject jsonObject = new JSONObject();
jsonObject.put("address", device.getAddress());
jsonObject.put("rssi", rssi);
jsonObject.put("name", device.getName());
jsonObject.put("scanRecord", Base64.encodeToString(scanRecord, Base64.NO_WRAP));
keepCallback(mScanCallbackContext, jsonObject);
}
catch(JSONException e)
{
mScanCallbackContext.error(e.toString());
}
}
// API implementation.
private void stopScan(final CordovaArgs args, final CallbackContext callbackContext)
{
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
adapter.stopLeScan(this);
mScanCallbackContext = null;
}
// API implementation.
private void connect(final CordovaArgs args, final CallbackContext callbackContext)
{
final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
checkPowerState(adapter, callbackContext, new Runnable()
{
@Override
public void run()
{
try {
// Each device connection has a GattHandler, which handles the events the can happen to the connection.
// The implementation of the GattHandler class is found at the end of this file.
GattHandler gh = new GattHandler(mNextGattHandle, callbackContext);
gh.mGatt = adapter.getRemoteDevice(args.getString(0)).connectGatt(mContext, true, gh);
// Note that gh.mGatt and this.mGatt are different object and have different types.
// --> Renamed this.mGatt to mConnectedDevices to avoid confusion.
if(mConnectedDevices == null)
mConnectedDevices = new HashMap<Integer, GattHandler>();
Object res = mConnectedDevices.put(mNextGattHandle, gh);
assert(res == null);
mNextGattHandle++;
} catch(Exception e) {
e.printStackTrace();
callbackContext.error(e.toString());
}
}
});
}
// API implementation.
private void close(final CordovaArgs args, final CallbackContext callbackContext)
{
try {
GattHandler gh = mConnectedDevices.get(args.getInt(0));
gh.mGatt.close();
mConnectedDevices.remove(args.getInt(0));
} catch(JSONException e) {
e.printStackTrace();
callbackContext.error(e.toString());
}
}
// API implementation.
private void rssi(final CordovaArgs args, final CallbackContext callbackContext)
{
GattHandler gh = null;
try {
gh = mConnectedDevices.get(args.getInt(0));
if(gh.mRssiContext != null) {
callbackContext.error("Previous call to rssi() not yet completed!");
return;
}
gh.mRssiContext = callbackContext;
if(!gh.mGatt.readRemoteRssi()) {
gh.mRssiContext = null;
callbackContext.error("readRemoteRssi");
}
} catch(Exception e) {
e.printStackTrace();
if(gh != null) {
gh.mRssiContext = null;
}
callbackContext.error(e.toString());
}
}
// API implementation.
private void services(final CordovaArgs args, final CallbackContext callbackContext)
{
try {
final GattHandler gh = mConnectedDevices.get(args.getInt(0));
gh.mOperations.add(new Runnable() {
@Override
public void run() {
gh.mCurrentOpContext = callbackContext;
if(!gh.mGatt.discoverServices()) {
gh.mCurrentOpContext = null;
callbackContext.error("discoverServices");
gh.process();
}
}
});
gh.process();
} catch(Exception e) {
e.printStackTrace();
callbackContext.error(e.toString());
}
}
// API implementation.
private void characteristics(
final CordovaArgs args,
final CallbackContext callbackContext)
throws JSONException
{
final GattHandler gh = mConnectedDevices.get(args.getInt(0));
JSONArray a = new JSONArray();
for(BluetoothGattCharacteristic c : gh.mServices.get(args.getInt(1)).getCharacteristics()) {
if(gh.mCharacteristics == null)
gh.mCharacteristics = new HashMap<Integer, BluetoothGattCharacteristic>();
Object res = gh.mCharacteristics.put(gh.mNextHandle, c);
assert(res == null);
JSONObject o = new JSONObject();
o.put("handle", gh.mNextHandle);
o.put("uuid", c.getUuid().toString());
o.put("permissions", c.getPermissions());
o.put("properties", c.getProperties());
o.put("writeType", c.getWriteType());
gh.mNextHandle++;
a.put(o);
}
callbackContext.success(a);
}
// API implementation.
private void descriptors(
final CordovaArgs args,
final CallbackContext callbackContext)
throws JSONException
{
final GattHandler gh = mConnectedDevices.get(args.getInt(0));
JSONArray a = new JSONArray();
for(BluetoothGattDescriptor d : gh.mCharacteristics.get(args.getInt(1)).getDescriptors()) {
if(gh.mDescriptors == null)
gh.mDescriptors = new HashMap<Integer, BluetoothGattDescriptor>();
Object res = gh.mDescriptors.put(gh.mNextHandle, d);
assert(res == null);
JSONObject o = new JSONObject();
o.put("handle", gh.mNextHandle);
o.put("uuid", d.getUuid().toString());
o.put("permissions", d.getPermissions());
gh.mNextHandle++;
a.put(o);
}
callbackContext.success(a);
}
// API implementation.
private void readCharacteristic(
final CordovaArgs args,
final CallbackContext callbackContext)
throws JSONException
{
final GattHandler gh = mConnectedDevices.get(args.getInt(0));
gh.mOperations.add(new Runnable() {
@Override
public void run() {
try {
gh.mCurrentOpContext = callbackContext;
if(!gh.mGatt.readCharacteristic(gh.mCharacteristics.get(args.getInt(1)))) {
gh.mCurrentOpContext = null;
callbackContext.error("readCharacteristic");
gh.process();
}
} catch(JSONException e) {
e.printStackTrace();
callbackContext.error(e.toString());
gh.process();
}
}
});
gh.process();
}
// API implementation.
private void readDescriptor(
final CordovaArgs args,
final CallbackContext callbackContext)
throws JSONException
{
final GattHandler gh = mConnectedDevices.get(args.getInt(0));
gh.mOperations.add(new Runnable()
{
@Override
public void run()
{
try {
gh.mCurrentOpContext = callbackContext;
if(!gh.mGatt.readDescriptor(gh.mDescriptors.get(args.getInt(1)))) {
gh.mCurrentOpContext = null;
callbackContext.error("readDescriptor");
gh.process();
}
} catch(JSONException e) {
e.printStackTrace();
callbackContext.error(e.toString());
gh.process();
}
}
});
gh.process();
}
// API implementation.
private void writeCharacteristic(
final CordovaArgs args,
final CallbackContext callbackContext,
final int writeType)
throws JSONException
{
final GattHandler gh = mConnectedDevices.get(args.getInt(0));
gh.mOperations.add(new Runnable()
{
@Override
public void run()
{
try {
gh.mCurrentOpContext = callbackContext;
BluetoothGattCharacteristic c = gh.mCharacteristics.get(args.getInt(1));
System.out.println("writeCharacteristic("+args.getInt(0)+", "+args.getInt(1)+", "+args.getString(2)+")");
c.setWriteType(writeType);
c.setValue(args.getArrayBuffer(2));
if(!gh.mGatt.writeCharacteristic(c)) {
gh.mCurrentOpContext = null;
callbackContext.error("writeCharacteristic");
gh.process();
}
} catch(JSONException e) {
e.printStackTrace();
callbackContext.error(e.toString());
gh.process();
}
}
});
gh.process();
}
// API implementation.
private void writeDescriptor(
final CordovaArgs args,
final CallbackContext callbackContext)
throws JSONException
{
final GattHandler gh = mConnectedDevices.get(args.getInt(0));
gh.mOperations.add(new Runnable()
{
@Override
public void run()
{
try {
gh.mCurrentOpContext = callbackContext;
BluetoothGattDescriptor d = gh.mDescriptors.get(args.getInt(1));
d.setValue(args.getArrayBuffer(2));
if(!gh.mGatt.writeDescriptor(d)) {
gh.mCurrentOpContext = null;
callbackContext.error("writeDescriptor");
gh.process();
}
} catch(JSONException e) {
e.printStackTrace();
callbackContext.error(e.toString());
gh.process();
}
}
});
gh.process();
}
// Notification options flag.
private final int NOTIFICATION_OPTIONS_DISABLE_AUTOMATIC_CONFIG = 1;
// API implementation.
private void enableNotification(
final CordovaArgs args,
final CallbackContext callbackContext)
throws JSONException
{
final GattHandler gh = mConnectedDevices.get(args.getInt(0));
// Get characteristic.
BluetoothGattCharacteristic characteristic = gh.mCharacteristics.get(args.getInt(1));
// Get options flag.
int options = args.getInt(2);
// Turn notification on.
boolean setConfigDescriptor =
NOTIFICATION_OPTIONS_DISABLE_AUTOMATIC_CONFIG ==
(NOTIFICATION_OPTIONS_DISABLE_AUTOMATIC_CONFIG & options);
turnNotificationOn(callbackContext, gh, gh.mGatt, characteristic, setConfigDescriptor);
}
// API implementation.
private void disableNotification(
final CordovaArgs args,
final CallbackContext callbackContext)
throws JSONException
{
final GattHandler gh = mConnectedDevices.get(args.getInt(0));
// Get characteristic.
BluetoothGattCharacteristic characteristic = gh.mCharacteristics.get(args.getInt(1));
// Get options flag.
int options = args.getInt(2);
// Turn notification off.
boolean setConfigDescriptor =
NOTIFICATION_OPTIONS_DISABLE_AUTOMATIC_CONFIG ==
(NOTIFICATION_OPTIONS_DISABLE_AUTOMATIC_CONFIG & options);
turnNotificationOff(callbackContext, gh, gh.mGatt, characteristic, setConfigDescriptor);
}
// Helper method.
private void turnNotificationOn(
final CallbackContext callbackContext,
final GattHandler gattHandler,
final BluetoothGatt gatt,
final BluetoothGattCharacteristic characteristic,
final boolean setConfigDescriptor)
{
gattHandler.mOperations.add(new Runnable()
{
@Override
public void run()
{
try {
// Mark operation in progress.
gattHandler.mCurrentOp = true;
if (setConfigDescriptor) {
// Write the config descriptor and enable notification.
if (enableConfigDescriptor(callbackContext, gattHandler, gatt, characteristic)) {
enableNotification(callbackContext, gattHandler, gatt, characteristic);
}
}
else {
// Enable notification without writing config descriptor.
// This is useful for applications that want to manually
// set the config descriptor.
enableNotification(callbackContext, gattHandler, gatt, characteristic);
}
}
catch (Exception e) {
e.printStackTrace();
callbackContext.error("Exception when enabling notification");
gattHandler.process();
}
}
});
gattHandler.process();
}
// Helper method.
private boolean enableConfigDescriptor(
final CallbackContext callbackContext,
final GattHandler gattHandler,
final BluetoothGatt gatt,
final BluetoothGattCharacteristic characteristic)
{
// Get config descriptor.
BluetoothGattDescriptor configDescriptor = characteristic.getDescriptor(
UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
if (configDescriptor == null) {
callbackContext.error("Could not get config descriptor");
gattHandler.process();
return false;
}
// Config descriptor value.
byte[] descriptorValue;
// Check if notification or indication should be used.
if (0 != (characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_NOTIFY)) {
descriptorValue = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE;
}
else if (0 != (characteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_INDICATE)) {
descriptorValue = BluetoothGattDescriptor.ENABLE_INDICATION_VALUE;
}
else {
callbackContext.error("Characteristic does not support notification or indication.");
gattHandler.process();
return false;
}
// Set value of config descriptor.
configDescriptor.setValue(descriptorValue);
// Write descriptor.
boolean success = gatt.writeDescriptor(configDescriptor);
if (!success) {
callbackContext.error("Could not write config descriptor");
gattHandler.process();
return false;
}
return true;
}
// Helper method.
private void enableNotification(
final CallbackContext callbackContext,
final GattHandler gattHandler,
final BluetoothGatt gatt,
final BluetoothGattCharacteristic characteristic)
{
// Turn notification on.
boolean success = gatt.setCharacteristicNotification(characteristic, true);
if (!success) {
callbackContext.error("Could not enable notification");
gattHandler.process();
return;
}
// Save callback context for the characteristic.
// When turning notification on, the success callback will be
// called on every notification event.
gattHandler.mNotifications.put(characteristic, callbackContext);
}
// Helper method.
private void turnNotificationOff(
final CallbackContext callbackContext,
final GattHandler gattHandler,
final BluetoothGatt gatt,
final BluetoothGattCharacteristic characteristic,
final boolean setConfigDescriptor)
{
gattHandler.mOperations.add(new Runnable()
{
@Override
public void run()
{
try {
// Mark operation in progress.
gattHandler.mCurrentOp = true;
// Remove callback context for the characteristic
// when turning off notification.
gattHandler.mNotifications.remove(characteristic);
if (setConfigDescriptor) {
// Write the config descriptor and disable notification.
if (disableConfigDescriptor(callbackContext, gattHandler, gatt, characteristic)) {
disableNotification(callbackContext, gattHandler, gatt, characteristic);
}
}
else {
// Disable notification without writing config descriptor.
// This is useful for applications that want to manually
// set the config descriptor.
disableNotification(callbackContext, gattHandler, gatt, characteristic);
}
}
catch (Exception e) {
e.printStackTrace();
callbackContext.error("Exception when disabling notification");
gattHandler.process();
}
}
});
gattHandler.process();
}
// Helper method.
private boolean disableConfigDescriptor(
final CallbackContext callbackContext,
final GattHandler gattHandler,
final BluetoothGatt gatt,
final BluetoothGattCharacteristic characteristic)
{
// Get config descriptor.
BluetoothGattDescriptor configDescriptor = characteristic.getDescriptor(
UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
if (configDescriptor == null) {
callbackContext.error("Could not get config descriptor");
gattHandler.process();
return false;
}
// Set value of config descriptor.
byte[] descriptorValue = BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE;
configDescriptor.setValue(descriptorValue);
// Write descriptor.
boolean success = gatt.writeDescriptor(configDescriptor);
if (!success) {
callbackContext.error("Could not write config descriptor");
gattHandler.process();
return false;
}
return true;
}
// Helper method.
private void disableNotification(
final CallbackContext callbackContext,
final GattHandler gattHandler,
final BluetoothGatt gatt,
final BluetoothGattCharacteristic characteristic)
{
// Turn notification off.
boolean success = gatt.setCharacteristicNotification(characteristic, false);
if (!success) {
callbackContext.error("Could not disable notification");
gattHandler.process();
return;
}
// Call success callback when notification is turned off.
callbackContext.success();
}
// API implementation.
private void testCharConversion(
final CordovaArgs args,
final CallbackContext callbackContext)
throws JSONException
{
byte[] b = {(byte)args.getInt(0)};
callbackContext.success(b);
}
// API implementation.
private void reset(final CordovaArgs args, final CallbackContext cc) throws JSONException
{
mResetCallbackContext = null;
BluetoothAdapter a = BluetoothAdapter.getDefaultAdapter();
if(mScanCallbackContext != null) {
a.stopLeScan(this);
mScanCallbackContext = null;
}
int state = a.getState();
//STATE_OFF, STATE_TURNING_ON, STATE_ON, STATE_TURNING_OFF.
if(state == BluetoothAdapter.STATE_TURNING_ON) {
// reset in progress; wait for STATE_ON.
mResetCallbackContext = cc;
return;
}
if(state == BluetoothAdapter.STATE_TURNING_OFF) {
// reset in progress; wait for STATE_OFF.
mResetCallbackContext = cc;
return;
}
if(state == BluetoothAdapter.STATE_OFF) {
boolean res = a.enable();
if(res) {
mResetCallbackContext = cc;
} else {
cc.error("enable");
}
return;
}
if(state == BluetoothAdapter.STATE_ON) {
boolean res = a.disable();
if(res) {
mResetCallbackContext = cc;
} else {
cc.error("disable");
}
return;
}
cc.error("Unknown state: "+state);
}
// Receives notification about Bluetooth power on and off. Used by reset().
class BluetoothStateReceiver extends BroadcastReceiver
{
public void onReceive(Context context, Intent intent)
{
BluetoothAdapter a = BluetoothAdapter.getDefaultAdapter();
int state = a.getState();
System.out.println("BluetoothState: "+a);
if(mResetCallbackContext != null) {
if(state == BluetoothAdapter.STATE_OFF) {
boolean res = a.enable();
if(!res) {
mResetCallbackContext.error("enable");
mResetCallbackContext = null;
}
}
if(state == BluetoothAdapter.STATE_ON) {
mResetCallbackContext.success();
mResetCallbackContext = null;
}
}
}
};
/* Running more than one operation of certain types on remote Gatt devices
* seem to cause it to stop responding.
* The known types are 'read' and 'write'.
* I've added 'services' to be on the safe side.
* 'rssi' and 'notification' should be safe.
*/
// This class handles callbacks pertaining to device connections.
// Also maintains the per-device operation queue.
private class GattHandler extends BluetoothGattCallback
{
// Local copy of the key to BLE.mGatt. Fed by BLE.mNextGattHandle.
final int mHandle;
// The queue of operations.
LinkedList<Runnable> mOperations = new LinkedList<Runnable>();
// connect() and rssi() are handled separately from other operations.
CallbackContext mConnectContext;
CallbackContext mRssiContext;
CallbackContext mCurrentOpContext;
// Special flag for doing async operations without a Cordova callback context.
// Used when writing notification config descriptor.
boolean mCurrentOp = false;
// The Android API connection.
BluetoothGatt mGatt;
// Maps of integer to Gatt subobject.
HashMap<Integer, BluetoothGattService> mServices;
HashMap<Integer, BluetoothGattCharacteristic> mCharacteristics;
HashMap<Integer, BluetoothGattDescriptor> mDescriptors;
// Monotonically incrementing key to the subobject maps.
int mNextHandle = 1;
// Notification callbacks. The BluetoothGattCharacteristic object, as found
// in the mCharacteristics map, is the key.
HashMap<BluetoothGattCharacteristic, CallbackContext> mNotifications =
new HashMap<BluetoothGattCharacteristic, CallbackContext>();
GattHandler(int h, CallbackContext cc)
{
mHandle = h;
mConnectContext = cc;
}
// Run the next operation, if any.
void process()
{
if(mCurrentOpContext != null || mCurrentOp)
return;
Runnable r = mOperations.poll();
if(r == null)
return;
r.run();
}
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState)
{
if(status == BluetoothGatt.GATT_SUCCESS) {
try {
JSONObject o = new JSONObject();
o.put("deviceHandle", mHandle);
o.put("state", newState);
keepCallback(mConnectContext, o);
} catch(JSONException e) {
e.printStackTrace();
assert(false);
}
} else {
mConnectContext.error(status);
}
}
@Override
public void onReadRemoteRssi(BluetoothGatt g, int rssi, int status)
{
CallbackContext c = mRssiContext;
mRssiContext = null;
if(status == BluetoothGatt.GATT_SUCCESS) {
c.success(rssi);
} else {
c.error(status);
}
}
@Override
public void onServicesDiscovered(BluetoothGatt g, int status)
{
if(status == BluetoothGatt.GATT_SUCCESS) {
List<BluetoothGattService> services = g.getServices();
JSONArray a = new JSONArray();
for(BluetoothGattService s : services) {
// give the service a handle.
if(mServices == null)
mServices = new HashMap<Integer, BluetoothGattService>();
Object res = mServices.put(mNextHandle, s);
assert(res == null);
try {
JSONObject o = new JSONObject();
o.put("handle", mNextHandle);
o.put("uuid", s.getUuid().toString());
o.put("type", s.getType());
mNextHandle++;
a.put(o);
} catch(JSONException e) {
e.printStackTrace();
assert(false);
}
}
mCurrentOpContext.success(a);
} else {
mCurrentOpContext.error(status);
}
mCurrentOpContext = null;
process();
}
@Override
public void onCharacteristicRead(BluetoothGatt g, BluetoothGattCharacteristic c, int status)
{
if(status == BluetoothGatt.GATT_SUCCESS) {
mCurrentOpContext.success(c.getValue());
} else {
mCurrentOpContext.error(status);
}
mCurrentOpContext = null;
process();
}
@Override
public void onDescriptorRead(BluetoothGatt g, BluetoothGattDescriptor d, int status)
{
if(status == BluetoothGatt.GATT_SUCCESS) {
mCurrentOpContext.success(d.getValue());
} else {
mCurrentOpContext.error(status);
}
mCurrentOpContext = null;
process();
}
@Override
public void onCharacteristicWrite(BluetoothGatt g, BluetoothGattCharacteristic c, int status)
{
if(status == BluetoothGatt.GATT_SUCCESS) {
mCurrentOpContext.success();
} else {
mCurrentOpContext.error(status);
}
mCurrentOpContext = null;
process();
}
@Override
public void onDescriptorWrite(BluetoothGatt g, BluetoothGattDescriptor d, int status)
{
// We write the notification config descriptor in native code,
// and in this case there is no callback context. Thus we check
// if the context is null here.
// TODO: Encapsulate exposed instance variables in this file,
// use method calls instead.
if (mCurrentOpContext != null) {
if (status == BluetoothGatt.GATT_SUCCESS) {
mCurrentOpContext.success();
} else {
mCurrentOpContext.error(status);
}
mCurrentOpContext = null;
}
mCurrentOp = false;
process();
}
@Override
public void onCharacteristicChanged(BluetoothGatt g, BluetoothGattCharacteristic c)
{
CallbackContext cc = mNotifications.get(c);
keepCallback(cc, c.getValue());
}
}
// ************* BLE PERIPHERAL ROLE *************
// Implementation of advertisement API.
private BluetoothLeAdvertiser mAdvertiser;
private AdvertiseCallback mAdCallback;
private AdvertiseSettings buildAdvertiseSettings(JSONObject setJson) throws JSONException
{
AdvertiseSettings.Builder setBuild = new AdvertiseSettings.Builder();
{
String advModeString = setJson.optString("advertiseMode", "ADVERTISE_MODE_LOW_POWER");
int advMode;
if(advModeString.equals("ADVERTISE_MODE_LOW_POWER"))
advMode = AdvertiseSettings.ADVERTISE_MODE_LOW_POWER;
else if(advModeString.equals("ADVERTISE_MODE_BALANCED"))
advMode = AdvertiseSettings.ADVERTISE_MODE_BALANCED;
else if(advModeString.equals("ADVERTISE_MODE_LOW_LATENCY"))
advMode = AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY;
else
throw new JSONException("Invalid advertiseMode: "+advModeString);
setBuild.setAdvertiseMode(advMode);
}
boolean connectable = setJson.optBoolean("connectable", mGattServer != null);
System.out.println("connectable: "+connectable);
setBuild.setConnectable(connectable);
setBuild.setTimeout(setJson.optInt("timeoutMillis", 0));
{
String advModeString = setJson.optString("txPowerLevel", "ADVERTISE_TX_POWER_MEDIUM");
int advMode;
if(advModeString.equals("ADVERTISE_TX_POWER_ULTRA_LOW"))
advMode = AdvertiseSettings.ADVERTISE_TX_POWER_ULTRA_LOW;
else if(advModeString.equals("ADVERTISE_TX_POWER_LOW"))
advMode = AdvertiseSettings.ADVERTISE_TX_POWER_LOW;
else if(advModeString.equals("ADVERTISE_TX_POWER_MEDIUM"))
advMode = AdvertiseSettings.ADVERTISE_TX_POWER_MEDIUM;
else if(advModeString.equals("ADVERTISE_TX_POWER_HIGH"))
advMode = AdvertiseSettings.ADVERTISE_TX_POWER_HIGH;
else
throw new JSONException("Invalid txPowerLevel");
setBuild.setTxPowerLevel(advMode);
}
return setBuild.build();
}
private AdvertiseData buildAdvertiseData(JSONObject dataJson) throws JSONException
{
if(dataJson == null)
return null;
AdvertiseData.Builder dataBuild = new AdvertiseData.Builder();
dataBuild.setIncludeDeviceName(dataJson.optBoolean("includeDeviceName", false));
dataBuild.setIncludeTxPowerLevel(dataJson.optBoolean("includeTxPowerLevel", false));
JSONArray serviceUUIDs = dataJson.optJSONArray("serviceUUIDs");
if(serviceUUIDs != null) {
for(int i=0; i<serviceUUIDs.length(); i++) {
dataBuild.addServiceUuid(new ParcelUuid(UUID.fromString(serviceUUIDs.getString(i))));
}
}
JSONObject serviceData = dataJson.optJSONObject("serviceData");
if(serviceData != null) {
Iterator<String> keys = serviceData.keys();
while(keys.hasNext()) {
String key = keys.next();
ParcelUuid uuid = new ParcelUuid(UUID.fromString(key));
byte[] data = Base64.decode(serviceData.getString(key), Base64.DEFAULT);
dataBuild.addServiceData(uuid, data);
}
}
JSONObject manufacturerData = dataJson.optJSONObject("manufacturerData");
if(manufacturerData != null) {
Iterator<String> keys = manufacturerData.keys();
while(keys.hasNext()) {
String key = keys.next();
int id = Integer.parseInt(key);
byte[] data = Base64.decode(manufacturerData.getString(key), Base64.DEFAULT);
dataBuild.addManufacturerData(id, data);
}
}
return dataBuild.build();
}
private void startAdvertise(final CordovaArgs args, final CallbackContext cc) throws JSONException
{
if(mAdCallback != null) {
cc.error("Advertise must be stopped first!");
return;
}
final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if(!adapter.isMultipleAdvertisementSupported()) {
cc.error("BLE advertisement not supported by this device!");
return;
}
JSONObject setJson = args.getJSONObject(0);
// build settings. this checks arguments for validity.
final AdvertiseSettings settings = buildAdvertiseSettings(setJson);
// build data. this checks arguments for validity.
final AdvertiseData broadcastData = buildAdvertiseData(setJson.getJSONObject("broadcastData"));
final AdvertiseData scanResponseData = buildAdvertiseData(setJson.optJSONObject("scanResponseData"));
mAdCallback = new AdvertiseCallback()
{
@Override
public void onStartFailure(int errorCode)
{
mAdCallback = null;
// translate available error codes using reflection.
// we're looking for all fields typed "public static final int".
Field[] fields = AdvertiseCallback.class.getDeclaredFields();
String errorMessage = null;
for(int i=0; i<fields.length; i++) {
Field f = fields[i];
System.out.println("Field: Class "+f.getType().getName()+". Modifiers: "+Modifier.toString(f.getModifiers()));
if(f.getType() == int.class &&
f.getModifiers() == (Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL))
{
try {
if(f.getInt(null) == errorCode) {
errorMessage = f.getName();
break;
}
} catch(IllegalAccessException e) {
// if this happens, it is an internal error.
e.printStackTrace();
}
}
}
if(errorMessage == null) {
errorMessage = Integer.toString(errorCode);
}
cc.error("AdvertiseCallback.onStartFailure: "+errorMessage);
}
public void onStartSuccess(AdvertiseSettings settingsInEffect)
{
cc.success();
}
};
// ensure Bluetooth is powered on, then start advertising.
checkPowerState(adapter, cc, new Runnable()
{
@Override
public void run()
{
try {
mAdvertiser = adapter.getBluetoothLeAdvertiser();
if(scanResponseData != null) {
mAdvertiser.startAdvertising(settings, broadcastData, scanResponseData, mAdCallback);
} else {
mAdvertiser.startAdvertising(settings, broadcastData, mAdCallback);
}
} catch(Exception e) {
mAdCallback = null;
e.printStackTrace();
cc.error(e.toString());
}
}
});
}
private void stopAdvertise(final CordovaArgs args, final CallbackContext cc)
{
if(mAdvertiser != null && mAdCallback != null) {
mAdvertiser.stopAdvertising(mAdCallback);
mAdCallback = null;
}
cc.success();
}
private BluetoothGattServer mGattServer;
private MyBluetoothGattServerCallback mGattServerCallback;
private void startGattServer(final CordovaArgs args, final CallbackContext cc) throws JSONException
{
if(mGattServer != null) {
cc.error("GATT server already started!");
return;
}
JSONObject settings = args.getJSONObject(0);
mGattServerCallback = new MyBluetoothGattServerCallback(settings.getInt("nextHandle"), cc);
mGattServer = ((BluetoothManager)mContext.getSystemService(Context.BLUETOOTH_SERVICE))
.openGattServer(mContext, mGattServerCallback);
JSONArray services = settings.getJSONArray("services");
for(int i=0; i<services.length(); i++) {
JSONObject service = services.getJSONObject(i);
BluetoothGattService s = new BluetoothGattService(
UUID.fromString(service.getString("uuid")), service.getInt("type"));
JSONArray characteristics = service.optJSONArray("characteristics");
if(characteristics != null) {
for(int j=0; j<characteristics.length(); j++) {
JSONObject characteristic = characteristics.getJSONObject(j);
System.out.println("characteristic:"+characteristic.toString(1));
BluetoothGattCharacteristic c = new BluetoothGattCharacteristic(
UUID.fromString(characteristic.getString("uuid")),
characteristic.getInt("properties"), characteristic.getInt("permissions"));
mGattServerCallback.mReadHandles.put(c, characteristic.getInt("onReadRequestHandle"));
mGattServerCallback.mWriteHandles.put(c, characteristic.getInt("onWriteRequestHandle"));
JSONArray descriptors = characteristic.optJSONArray("descriptors");
if(descriptors != null) for(int k=0; k<descriptors.length(); k++) {
JSONObject descriptor = descriptors.getJSONObject(k);
System.out.println("descriptor:"+descriptor.toString(1));
BluetoothGattDescriptor d = new BluetoothGattDescriptor(
UUID.fromString(descriptor.getString("uuid")),
descriptor.getInt("permissions"));
c.addDescriptor(d);
mGattServerCallback.mReadHandles.put(d, descriptor.getInt("onReadRequestHandle"));
mGattServerCallback.mWriteHandles.put(d, descriptor.getInt("onWriteRequestHandle"));
}
s.addCharacteristic(c);
}
}
mGattServer.addService(s);
}
keepCallback(cc, new JSONObject().put("name", "win"));
}
private void stopGattServer(final CordovaArgs args, final CallbackContext cc)
{
if(mGattServer == null) {
cc.error("GATT server not started!");
return;
}
mGattServer.close();
mGattServer = null;
cc.success();
}
class MyBluetoothGattServerCallback extends BluetoothGattServerCallback
{
// Bidirectional maps; look up object from handle, or handle from object.
// The JavaScript side needs handles, the native side needs objects.
public HashMap<Integer, BluetoothDevice> mDevices;
public HashMap<Object, Integer> mDeviceHandles;
public HashMap<Object, Integer> mReadHandles;
public HashMap<Object, Integer> mWriteHandles;
int mNextHandle;
CallbackContext mCC;
CallbackContext mNotifyCC;
MyBluetoothGattServerCallback(int nextHandle, final CallbackContext cc)
{
mNextHandle = nextHandle;
mDevices = new HashMap<Integer, BluetoothDevice>();
mDeviceHandles = new HashMap<Object, Integer>();
mReadHandles = new HashMap<Object, Integer>();
mWriteHandles = new HashMap<Object, Integer>();
mCC = cc;
}
@Override
public void onConnectionStateChange(BluetoothDevice device, int status, int newState)
{
System.out.println("onConnectionStateChange("+device.getAddress()+", "+status+", "+newState+")");
Integer handle = mDeviceHandles.get(device);
if(handle == null) {
handle = new Integer(mNextHandle++);
mDeviceHandles.put(device, handle);
mDevices.put(handle, device);
}
try {
keepCallback(mCC, new JSONObject()
.put("name", "connection")
.put("deviceHandle", handle)
.put("connected", newState == BluetoothProfile.STATE_CONNECTED)
);
} catch(JSONException e) {
throw new Error(e);
}
}
@Override
public void onCharacteristicReadRequest(
BluetoothDevice device,
int requestId,
int offset,
BluetoothGattCharacteristic characteristic)
{
System.out.println("onCharacteristicReadRequest("+device.getAddress()+", "+requestId+", "+offset+")");
Integer handle = mDeviceHandles.get(device);
try {
keepCallback(mCC, new JSONObject()
.put("name", "read")
.put("deviceHandle", handle)
.put("requestId", requestId)
.put("callbackHandle", mReadHandles.get(characteristic))
);
} catch(JSONException e) {
throw new Error(e);
}
}
@Override
public void onDescriptorReadRequest(
BluetoothDevice device,
int requestId,
int offset,
BluetoothGattDescriptor descriptor)
{
System.out.println("onDescriptorReadRequest("+device.getAddress()+", "+requestId+", "+offset+")");
Integer handle = mDeviceHandles.get(device);
try {
keepCallback(mCC, new JSONObject()
.put("name", "read")
.put("deviceHandle", handle)
.put("requestId", requestId)
.put("callbackHandle", mReadHandles.get(descriptor))
);
} catch(JSONException e) {
throw new Error(e);
}
}
@Override
public void onCharacteristicWriteRequest(
BluetoothDevice device,
int requestId,
BluetoothGattCharacteristic characteristic,
boolean preparedWrite,
boolean responseNeeded,
int offset,
byte[] value)
{
System.out.println("onCharacteristicWriteRequest("+device.getAddress()+", "+requestId+", "+offset+")");
Integer handle = mDeviceHandles.get(device);
try {
keepCallback(mCC, new JSONObject()
.put("name", "write")
.put("deviceHandle", handle)
.put("requestId", requestId)
.put("data", value)
.put("callbackHandle", mWriteHandles.get(characteristic))
);
} catch(JSONException e) {
throw new Error(e);
}
}
@Override
public void onDescriptorWriteRequest(
BluetoothDevice device,
int requestId,
BluetoothGattDescriptor descriptor,
boolean preparedWrite,
boolean responseNeeded,
int offset,
byte[] value)
{
System.out.println("onDescriptorWriteRequest("+device.getAddress()+", "+requestId+", "+offset+")");
Integer handle = mDeviceHandles.get(device);
try {
keepCallback(mCC, new JSONObject()
.put("name", "write")
.put("deviceHandle", handle)
.put("requestId", requestId)
.put("data", value)
.put("callbackHandle", mWriteHandles.get(descriptor))
);
} catch(JSONException e) {
throw new Error(e);
}
}
@Override
public void onExecuteWrite(BluetoothDevice device, int requestId, boolean execute)
{
System.out.println("onExecuteWrite("+device.getAddress()+", "+requestId+", "+execute+")");
mGattServer.sendResponse(device, requestId, 0, 0, null);
}
@Override
public void onMtuChanged(BluetoothDevice device, int mtu)
{
System.out.println("onMtuChanged("+mtu+")");
}
@Override
public void onNotificationSent(BluetoothDevice device, int status)
{
System.out.println("onNotificationSent("+device.getAddress()+", "+status+")");
if(status == BluetoothGatt.GATT_SUCCESS)
mNotifyCC.success();
else
mNotifyCC.error(status);
mNotifyCC = null;
}
@Override
public void onServiceAdded(int status, BluetoothGattService service)
{
System.out.println("onServiceAdded("+status+")");
}
}
private void sendResponse(final CordovaArgs args, final CallbackContext cc) throws JSONException
{
if(mGattServer == null) {
cc.error("GATT server not started!");
return;
}
int deviceHandle = args.getInt(0);
int requestId = args.getInt(1);
byte[] data = args.getArrayBuffer(2);
boolean res = mGattServer.sendResponse(
mGattServerCallback.mDevices.get(deviceHandle),
requestId,
0,
0,
data);
System.out.println("sendResponse result: "+res);
cc.success();
}
private void notify(final CordovaArgs args, final CallbackContext cc) throws JSONException
{
if(mGattServer == null) {
cc.error("GATT server not started!");
return;
}
}
}
| Fixed bug that made notifications not being automatically enabled.
| src/android/BLE.java | Fixed bug that made notifications not being automatically enabled. |
|
Java | apache-2.0 | 751296aa67431ae33dfbd5c3ec3fd9befd80e0ef | 0 | FasterXML/jackson-databind,FasterXML/jackson-databind | package com.fasterxml.jackson.databind.util;
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.TreeMap;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.core.base.ParserMinimalBase;
import com.fasterxml.jackson.core.json.JsonWriteContext;
import com.fasterxml.jackson.core.util.ByteArrayBuilder;
import com.fasterxml.jackson.databind.*;
/**
* Utility class used for efficient storage of {@link JsonToken}
* sequences, needed for temporary buffering.
* Space efficient for different sequence lengths (especially so for smaller
* ones; but not significantly less efficient for larger), highly efficient
* for linear iteration and appending. Implemented as segmented/chunked
* linked list of tokens; only modifications are via appends.
*<p>
* Note that before version 2.0, this class was located in the "core"
* bundle, not data-binding; but since it was only used by data binding,
* was moved here to reduce size of core package
*/
public class TokenBuffer
/* Won't use JsonGeneratorBase, to minimize overhead for validity
* checking
*/
extends JsonGenerator
{
protected final static int DEFAULT_GENERATOR_FEATURES = JsonGenerator.Feature.collectDefaults();
/*
/**********************************************************
/* Configuration
/**********************************************************
*/
/**
* Object codec to use for stream-based object
* conversion through parser/generator interfaces. If null,
* such methods cannot be used.
*/
protected ObjectCodec _objectCodec;
/**
* Parse context from "parent" parser (one from which content to buffer is read,
* if specified). Used, if available, when reading content, to present full
* context as if content was read from the original parser: this is useful
* in error reporting and sometimes processing as well.
*/
protected JsonStreamContext _parentContext;
/**
* Bit flag composed of bits that indicate which
* {@link com.fasterxml.jackson.core.JsonGenerator.Feature}s
* are enabled.
*<p>
* NOTE: most features have no effect on this class
*/
protected int _generatorFeatures;
protected boolean _closed;
/**
* @since 2.3
*/
protected boolean _hasNativeTypeIds;
/**
* @since 2.3
*/
protected boolean _hasNativeObjectIds;
/**
* @since 2.3
*/
protected boolean _mayHaveNativeIds;
/**
* Flag set during construction, if use of {@link BigDecimal} is to be forced
* on all floating-point values.
*
* @since 2.7
*/
protected boolean _forceBigDecimal;
/*
/**********************************************************
/* Token buffering state
/**********************************************************
*/
/**
* First segment, for contents this buffer has
*/
protected Segment _first;
/**
* Last segment of this buffer, one that is used
* for appending more tokens
*/
protected Segment _last;
/**
* Offset within last segment,
*/
protected int _appendAt;
/**
* If native type ids supported, this is the id for following
* value (or first token of one) to be written.
*/
protected Object _typeId;
/**
* If native object ids supported, this is the id for following
* value (or first token of one) to be written.
*/
protected Object _objectId;
/**
* Do we currently have a native type or object id buffered?
*/
protected boolean _hasNativeId = false;
/*
/**********************************************************
/* Output state
/**********************************************************
*/
protected JsonWriteContext _writeContext;
/*
/**********************************************************
/* Life-cycle
/**********************************************************
*/
/**
* @param codec Object codec to use for stream-based object
* conversion through parser/generator interfaces. If null,
* such methods cannot be used.
* @param hasNativeIds Whether resulting {@link JsonParser} (if created)
* is considered to support native type and object ids
*/
public TokenBuffer(ObjectCodec codec, boolean hasNativeIds)
{
_objectCodec = codec;
_generatorFeatures = DEFAULT_GENERATOR_FEATURES;
_writeContext = JsonWriteContext.createRootContext(null);
// at first we have just one segment
_first = _last = new Segment();
_appendAt = 0;
_hasNativeTypeIds = hasNativeIds;
_hasNativeObjectIds = hasNativeIds;
_mayHaveNativeIds = _hasNativeTypeIds | _hasNativeObjectIds;
}
/**
* @since 2.3
*/
public TokenBuffer(JsonParser p) {
this(p, null);
}
/**
* @since 2.7
*/
public TokenBuffer(JsonParser p, DeserializationContext ctxt)
{
_objectCodec = p.getCodec();
_parentContext = p.getParsingContext();
_generatorFeatures = DEFAULT_GENERATOR_FEATURES;
_writeContext = JsonWriteContext.createRootContext(null);
// at first we have just one segment
_first = _last = new Segment();
_appendAt = 0;
_hasNativeTypeIds = p.canReadTypeId();
_hasNativeObjectIds = p.canReadObjectId();
_mayHaveNativeIds = _hasNativeTypeIds | _hasNativeObjectIds;
_forceBigDecimal = (ctxt == null) ? false
: ctxt.isEnabled(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
}
/**
* Convenience method, equivalent to:
*<pre>
* TokenBuffer b = new TokenBuffer(p);
* b.copyCurrentStructure(p);
* return b;
*</pre>
*
* @since 2.9
*/
public static TokenBuffer asCopyOfValue(JsonParser p) throws IOException {
TokenBuffer b = new TokenBuffer(p);
b.copyCurrentStructure(p);
return b;
}
/**
* Method that allows explicitly specifying parent parse context to associate
* with contents of this buffer. Usually context is assigned at construction,
* based on given parser; but it is not always available, and may not contain
* intended context.
*
* @since 2.9
*/
public TokenBuffer overrideParentContext(JsonStreamContext ctxt) {
_parentContext = ctxt;
return this;
}
/**
* @since 2.7
*/
public TokenBuffer forceUseOfBigDecimal(boolean b) {
_forceBigDecimal = b;
return this;
}
@Override
public Version version() {
return com.fasterxml.jackson.databind.cfg.PackageVersion.VERSION;
}
/**
* Method used to create a {@link JsonParser} that can read contents
* stored in this buffer. Will use default <code>_objectCodec</code> for
* object conversions.
*<p>
* Note: instances are not synchronized, that is, they are not thread-safe
* if there are concurrent appends to the underlying buffer.
*
* @return Parser that can be used for reading contents stored in this buffer
*/
public JsonParser asParser() {
return asParser(_objectCodec);
}
/**
* Same as:
*<pre>
* JsonParser p = asParser();
* p.nextToken();
* return p;
*</pre>
*
* @since 2.9
*/
public JsonParser asParserOnFirstToken() throws IOException {
JsonParser p = asParser(_objectCodec);
p.nextToken();
return p;
}
/**
* Method used to create a {@link JsonParser} that can read contents
* stored in this buffer.
*<p>
* Note: instances are not synchronized, that is, they are not thread-safe
* if there are concurrent appends to the underlying buffer.
*
* @param codec Object codec to use for stream-based object
* conversion through parser/generator interfaces. If null,
* such methods cannot be used.
*
* @return Parser that can be used for reading contents stored in this buffer
*/
public JsonParser asParser(ObjectCodec codec)
{
return new Parser(_first, codec, _hasNativeTypeIds, _hasNativeObjectIds, _parentContext);
}
/**
* @param src Parser to use for accessing source information
* like location, configured codec
*/
public JsonParser asParser(JsonParser src)
{
Parser p = new Parser(_first, src.getCodec(), _hasNativeTypeIds, _hasNativeObjectIds, _parentContext);
p.setLocation(src.getTokenLocation());
return p;
}
/*
/**********************************************************
/* Additional accessors
/**********************************************************
*/
public JsonToken firstToken() {
// no need to null check; never create without `_first`
return _first.type(0);
}
/*
/**********************************************************
/* Other custom methods not needed for implementing interfaces
/**********************************************************
*/
/**
* Helper method that will append contents of given buffer into this
* buffer.
* Not particularly optimized; can be made faster if there is need.
*
* @return This buffer
*/
@SuppressWarnings("resource")
public TokenBuffer append(TokenBuffer other) throws IOException
{
// Important? If source has native ids, need to store
if (!_hasNativeTypeIds) {
_hasNativeTypeIds = other.canWriteTypeId();
}
if (!_hasNativeObjectIds) {
_hasNativeObjectIds = other.canWriteObjectId();
}
_mayHaveNativeIds = _hasNativeTypeIds | _hasNativeObjectIds;
JsonParser p = other.asParser();
while (p.nextToken() != null) {
copyCurrentStructure(p);
}
return this;
}
/**
* Helper method that will write all contents of this buffer
* using given {@link JsonGenerator}.
*<p>
* Note: this method would be enough to implement
* <code>JsonSerializer</code> for <code>TokenBuffer</code> type;
* but we cannot have upwards
* references (from core to mapper package); and as such we also
* cannot take second argument.
*/
public void serialize(JsonGenerator gen) throws IOException
{
Segment segment = _first;
int ptr = -1;
final boolean checkIds = _mayHaveNativeIds;
boolean hasIds = checkIds && (segment.hasIds());
while (true) {
if (++ptr >= Segment.TOKENS_PER_SEGMENT) {
ptr = 0;
segment = segment.next();
if (segment == null) break;
hasIds = checkIds && (segment.hasIds());
}
JsonToken t = segment.type(ptr);
if (t == null) break;
if (hasIds) {
Object id = segment.findObjectId(ptr);
if (id != null) {
gen.writeObjectId(id);
}
id = segment.findTypeId(ptr);
if (id != null) {
gen.writeTypeId(id);
}
}
// Note: copied from 'copyCurrentEvent'...
switch (t) {
case START_OBJECT:
gen.writeStartObject();
break;
case END_OBJECT:
gen.writeEndObject();
break;
case START_ARRAY:
gen.writeStartArray();
break;
case END_ARRAY:
gen.writeEndArray();
break;
case FIELD_NAME:
{
// 13-Dec-2010, tatu: Maybe we should start using different type tokens to reduce casting?
Object ob = segment.get(ptr);
if (ob instanceof SerializableString) {
gen.writeFieldName((SerializableString) ob);
} else {
gen.writeFieldName((String) ob);
}
}
break;
case VALUE_STRING:
{
Object ob = segment.get(ptr);
if (ob instanceof SerializableString) {
gen.writeString((SerializableString) ob);
} else {
gen.writeString((String) ob);
}
}
break;
case VALUE_NUMBER_INT:
{
Object n = segment.get(ptr);
if (n instanceof Integer) {
gen.writeNumber((Integer) n);
} else if (n instanceof BigInteger) {
gen.writeNumber((BigInteger) n);
} else if (n instanceof Long) {
gen.writeNumber((Long) n);
} else if (n instanceof Short) {
gen.writeNumber((Short) n);
} else {
gen.writeNumber(((Number) n).intValue());
}
}
break;
case VALUE_NUMBER_FLOAT:
{
Object n = segment.get(ptr);
if (n instanceof Double) {
gen.writeNumber(((Double) n).doubleValue());
} else if (n instanceof BigDecimal) {
gen.writeNumber((BigDecimal) n);
} else if (n instanceof Float) {
gen.writeNumber(((Float) n).floatValue());
} else if (n == null) {
gen.writeNull();
} else if (n instanceof String) {
gen.writeNumber((String) n);
} else {
throw new JsonGenerationException(String.format(
"Unrecognized value type for VALUE_NUMBER_FLOAT: %s, cannot serialize",
n.getClass().getName()), gen);
}
}
break;
case VALUE_TRUE:
gen.writeBoolean(true);
break;
case VALUE_FALSE:
gen.writeBoolean(false);
break;
case VALUE_NULL:
gen.writeNull();
break;
case VALUE_EMBEDDED_OBJECT:
{
Object value = segment.get(ptr);
// 01-Sep-2016, tatu: as per [databind#1361], should use `writeEmbeddedObject()`;
// however, may need to consider alternatives for some well-known types
// first
if (value instanceof RawValue) {
((RawValue) value).serialize(gen);
} else if (value instanceof JsonSerializable) {
gen.writeObject(value);
} else {
gen.writeEmbeddedObject(value);
}
}
break;
default:
throw new RuntimeException("Internal error: should never end up through this code path");
}
}
}
/**
* Helper method used by standard deserializer.
*
* @since 2.3
*/
public TokenBuffer deserialize(JsonParser p, DeserializationContext ctxt) throws IOException
{
if (p.getCurrentTokenId() != JsonToken.FIELD_NAME.id()) {
copyCurrentStructure(p);
return this;
}
/* 28-Oct-2014, tatu: As per [databind#592], need to support a special case of starting from
* FIELD_NAME, which is taken to mean that we are missing START_OBJECT, but need
* to assume one did exist.
*/
JsonToken t;
writeStartObject();
do {
copyCurrentStructure(p);
} while ((t = p.nextToken()) == JsonToken.FIELD_NAME);
if (t != JsonToken.END_OBJECT) {
ctxt.reportWrongTokenException(TokenBuffer.class, JsonToken.END_OBJECT,
"Expected END_OBJECT after copying contents of a JsonParser into TokenBuffer, got "+t);
// never gets here
}
writeEndObject();
return this;
}
@Override
@SuppressWarnings("resource")
public String toString()
{
// Let's print up to 100 first tokens...
final int MAX_COUNT = 100;
StringBuilder sb = new StringBuilder();
sb.append("[TokenBuffer: ");
/*
sb.append("NativeTypeIds=").append(_hasNativeTypeIds).append(",");
sb.append("NativeObjectIds=").append(_hasNativeObjectIds).append(",");
*/
JsonParser jp = asParser();
int count = 0;
final boolean hasNativeIds = _hasNativeTypeIds || _hasNativeObjectIds;
while (true) {
JsonToken t;
try {
t = jp.nextToken();
if (t == null) break;
if (hasNativeIds) {
_appendNativeIds(sb);
}
if (count < MAX_COUNT) {
if (count > 0) {
sb.append(", ");
}
sb.append(t.toString());
if (t == JsonToken.FIELD_NAME) {
sb.append('(');
sb.append(jp.getCurrentName());
sb.append(')');
}
}
} catch (IOException ioe) { // should never occur
throw new IllegalStateException(ioe);
}
++count;
}
if (count >= MAX_COUNT) {
sb.append(" ... (truncated ").append(count-MAX_COUNT).append(" entries)");
}
sb.append(']');
return sb.toString();
}
private final void _appendNativeIds(StringBuilder sb)
{
Object objectId = _last.findObjectId(_appendAt-1);
if (objectId != null) {
sb.append("[objectId=").append(String.valueOf(objectId)).append(']');
}
Object typeId = _last.findTypeId(_appendAt-1);
if (typeId != null) {
sb.append("[typeId=").append(String.valueOf(typeId)).append(']');
}
}
/*
/**********************************************************
/* JsonGenerator implementation: configuration
/**********************************************************
*/
@Override
public JsonGenerator enable(Feature f) {
_generatorFeatures |= f.getMask();
return this;
}
@Override
public JsonGenerator disable(Feature f) {
_generatorFeatures &= ~f.getMask();
return this;
}
//public JsonGenerator configure(SerializationFeature f, boolean state) { }
@Override
public boolean isEnabled(Feature f) {
return (_generatorFeatures & f.getMask()) != 0;
}
@Override
public int getFeatureMask() {
return _generatorFeatures;
}
@Override
@Deprecated
public JsonGenerator setFeatureMask(int mask) {
_generatorFeatures = mask;
return this;
}
@Override
public JsonGenerator overrideStdFeatures(int values, int mask) {
int oldState = getFeatureMask();
_generatorFeatures = (oldState & ~mask) | (values & mask);
return this;
}
@Override
public JsonGenerator useDefaultPrettyPrinter() {
// No-op: we don't indent
return this;
}
@Override
public JsonGenerator setCodec(ObjectCodec oc) {
_objectCodec = oc;
return this;
}
@Override
public ObjectCodec getCodec() { return _objectCodec; }
@Override
public final JsonWriteContext getOutputContext() { return _writeContext; }
/*
/**********************************************************
/* JsonGenerator implementation: capability introspection
/**********************************************************
*/
/**
* Since we can efficiently store <code>byte[]</code>, yes.
*/
@Override
public boolean canWriteBinaryNatively() {
return true;
}
/*
/**********************************************************
/* JsonGenerator implementation: low-level output handling
/**********************************************************
*/
@Override
public void flush() throws IOException { /* NOP */ }
@Override
public void close() throws IOException {
_closed = true;
}
@Override
public boolean isClosed() { return _closed; }
/*
/**********************************************************
/* JsonGenerator implementation: write methods, structural
/**********************************************************
*/
@Override
public final void writeStartArray() throws IOException
{
_writeContext.writeValue();
_appendStartMarker(JsonToken.START_ARRAY);
_writeContext = _writeContext.createChildArrayContext();
}
@Override // since 2.10 (method added in 2.4)
public final void writeStartArray(int size) throws IOException
{
_writeContext.writeValue();
_appendStartMarker(JsonToken.START_ARRAY);
_writeContext = _writeContext.createChildArrayContext();
}
// // TODO: add 2 more `writeStartArray()` methods from 2.10 (in 2.11 or later)
@Override
public final void writeEndArray() throws IOException
{
_appendEndMarker(JsonToken.END_ARRAY);
// Let's allow unbalanced tho... i.e. not run out of root level, ever
JsonWriteContext c = _writeContext.getParent();
if (c != null) {
_writeContext = c;
}
}
@Override
public final void writeStartObject() throws IOException
{
_writeContext.writeValue();
_appendStartMarker(JsonToken.START_OBJECT);
_writeContext = _writeContext.createChildObjectContext();
}
@Override // since 2.8
public void writeStartObject(Object forValue) throws IOException
{
_writeContext.writeValue();
_appendStartMarker(JsonToken.START_OBJECT);
// 15-Aug-2019, tatu: Matching method only added in 2.10, don't yet call
JsonWriteContext ctxt = _writeContext.createChildObjectContext();
_writeContext = ctxt;
if (forValue != null) {
ctxt.setCurrentValue(forValue);
}
}
// // TODO: add 1 more `writeStartObject()` methods from 2.10 (in 2.11 or later)
@Override
public final void writeEndObject() throws IOException
{
_appendEndMarker(JsonToken.END_OBJECT);
// Let's allow unbalanced tho... i.e. not run out of root level, ever
JsonWriteContext c = _writeContext.getParent();
if (c != null) {
_writeContext = c;
}
}
@Override
public final void writeFieldName(String name) throws IOException
{
_writeContext.writeFieldName(name);
_appendFieldName(name);
}
@Override
public void writeFieldName(SerializableString name) throws IOException
{
_writeContext.writeFieldName(name.getValue());
_appendFieldName(name);
}
/*
/**********************************************************
/* JsonGenerator implementation: write methods, textual
/**********************************************************
*/
@Override
public void writeString(String text) throws IOException {
if (text == null) {
writeNull();
} else {
_appendValue(JsonToken.VALUE_STRING, text);
}
}
@Override
public void writeString(char[] text, int offset, int len) throws IOException {
writeString(new String(text, offset, len));
}
@Override
public void writeString(SerializableString text) throws IOException {
if (text == null) {
writeNull();
} else {
_appendValue(JsonToken.VALUE_STRING, text);
}
}
@Override
public void writeRawUTF8String(byte[] text, int offset, int length) throws IOException
{
// could add support for buffering if we really want it...
_reportUnsupportedOperation();
}
@Override
public void writeUTF8String(byte[] text, int offset, int length) throws IOException
{
// could add support for buffering if we really want it...
_reportUnsupportedOperation();
}
@Override
public void writeRaw(String text) throws IOException {
_reportUnsupportedOperation();
}
@Override
public void writeRaw(String text, int offset, int len) throws IOException {
_reportUnsupportedOperation();
}
@Override
public void writeRaw(SerializableString text) throws IOException {
_reportUnsupportedOperation();
}
@Override
public void writeRaw(char[] text, int offset, int len) throws IOException {
_reportUnsupportedOperation();
}
@Override
public void writeRaw(char c) throws IOException {
_reportUnsupportedOperation();
}
@Override
public void writeRawValue(String text) throws IOException {
_appendValue(JsonToken.VALUE_EMBEDDED_OBJECT, new RawValue(text));
}
@Override
public void writeRawValue(String text, int offset, int len) throws IOException {
if (offset > 0 || len != text.length()) {
text = text.substring(offset, offset+len);
}
_appendValue(JsonToken.VALUE_EMBEDDED_OBJECT, new RawValue(text));
}
@Override
public void writeRawValue(char[] text, int offset, int len) throws IOException {
_appendValue(JsonToken.VALUE_EMBEDDED_OBJECT, new String(text, offset, len));
}
/*
/**********************************************************
/* JsonGenerator implementation: write methods, primitive types
/**********************************************************
*/
@Override
public void writeNumber(short i) throws IOException {
_appendValue(JsonToken.VALUE_NUMBER_INT, Short.valueOf(i));
}
@Override
public void writeNumber(int i) throws IOException {
_appendValue(JsonToken.VALUE_NUMBER_INT, Integer.valueOf(i));
}
@Override
public void writeNumber(long l) throws IOException {
_appendValue(JsonToken.VALUE_NUMBER_INT, Long.valueOf(l));
}
@Override
public void writeNumber(double d) throws IOException {
_appendValue(JsonToken.VALUE_NUMBER_FLOAT, Double.valueOf(d));
}
@Override
public void writeNumber(float f) throws IOException {
_appendValue(JsonToken.VALUE_NUMBER_FLOAT, Float.valueOf(f));
}
@Override
public void writeNumber(BigDecimal dec) throws IOException {
if (dec == null) {
writeNull();
} else {
_appendValue(JsonToken.VALUE_NUMBER_FLOAT, dec);
}
}
@Override
public void writeNumber(BigInteger v) throws IOException {
if (v == null) {
writeNull();
} else {
_appendValue(JsonToken.VALUE_NUMBER_INT, v);
}
}
@Override
public void writeNumber(String encodedValue) throws IOException {
/* 03-Dec-2010, tatu: related to [JACKSON-423], should try to keep as numeric
* identity as long as possible
*/
_appendValue(JsonToken.VALUE_NUMBER_FLOAT, encodedValue);
}
@Override
public void writeBoolean(boolean state) throws IOException {
_appendValue(state ? JsonToken.VALUE_TRUE : JsonToken.VALUE_FALSE);
}
@Override
public void writeNull() throws IOException {
_appendValue(JsonToken.VALUE_NULL);
}
/*
/***********************************************************
/* JsonGenerator implementation: write methods for POJOs/trees
/***********************************************************
*/
@Override
public void writeObject(Object value) throws IOException
{
if (value == null) {
writeNull();
return;
}
Class<?> raw = value.getClass();
if (raw == byte[].class || (value instanceof RawValue)) {
_appendValue(JsonToken.VALUE_EMBEDDED_OBJECT, value);
return;
}
if (_objectCodec == null) {
/* 28-May-2014, tatu: Tricky choice here; if no codec, should we
* err out, or just embed? For now, do latter.
*/
// throw new JsonMappingException("No ObjectCodec configured for TokenBuffer, writeObject() called");
_appendValue(JsonToken.VALUE_EMBEDDED_OBJECT, value);
} else {
_objectCodec.writeValue(this, value);
}
}
@Override
public void writeTree(TreeNode node) throws IOException
{
if (node == null) {
writeNull();
return;
}
if (_objectCodec == null) {
// as with 'writeObject()', is codec optional?
_appendValue(JsonToken.VALUE_EMBEDDED_OBJECT, node);
} else {
_objectCodec.writeTree(this, node);
}
}
/*
/***********************************************************
/* JsonGenerator implementation; binary
/***********************************************************
*/
@Override
public void writeBinary(Base64Variant b64variant, byte[] data, int offset, int len) throws IOException
{
/* 31-Dec-2009, tatu: can do this using multiple alternatives; but for
* now, let's try to limit number of conversions.
* The only (?) tricky thing is that of whether to preserve variant,
* seems pointless, so let's not worry about it unless there's some
* compelling reason to.
*/
byte[] copy = new byte[len];
System.arraycopy(data, offset, copy, 0, len);
writeObject(copy);
}
/**
* Although we could support this method, it does not necessarily make
* sense: we cannot make good use of streaming because buffer must
* hold all the data. Because of this, currently this will simply
* throw {@link UnsupportedOperationException}
*/
@Override
public int writeBinary(Base64Variant b64variant, InputStream data, int dataLength) {
throw new UnsupportedOperationException();
}
/*
/***********************************************************
/* JsonGenerator implementation: native ids
/***********************************************************
*/
@Override
public boolean canWriteTypeId() {
return _hasNativeTypeIds;
}
@Override
public boolean canWriteObjectId() {
return _hasNativeObjectIds;
}
@Override
public void writeTypeId(Object id) {
_typeId = id;
_hasNativeId = true;
}
@Override
public void writeObjectId(Object id) {
_objectId = id;
_hasNativeId = true;
}
@Override // since 2.8
public void writeEmbeddedObject(Object object) throws IOException {
_appendValue(JsonToken.VALUE_EMBEDDED_OBJECT, object);
}
/*
/**********************************************************
/* JsonGenerator implementation; pass-through copy
/**********************************************************
*/
@Override
public void copyCurrentEvent(JsonParser p) throws IOException
{
if (_mayHaveNativeIds) {
_checkNativeIds(p);
}
switch (p.getCurrentToken()) {
case START_OBJECT:
writeStartObject();
break;
case END_OBJECT:
writeEndObject();
break;
case START_ARRAY:
writeStartArray();
break;
case END_ARRAY:
writeEndArray();
break;
case FIELD_NAME:
writeFieldName(p.getCurrentName());
break;
case VALUE_STRING:
if (p.hasTextCharacters()) {
writeString(p.getTextCharacters(), p.getTextOffset(), p.getTextLength());
} else {
writeString(p.getText());
}
break;
case VALUE_NUMBER_INT:
switch (p.getNumberType()) {
case INT:
writeNumber(p.getIntValue());
break;
case BIG_INTEGER:
writeNumber(p.getBigIntegerValue());
break;
default:
writeNumber(p.getLongValue());
}
break;
case VALUE_NUMBER_FLOAT:
if (_forceBigDecimal) {
// 10-Oct-2015, tatu: Ideally we would first determine whether underlying
// number is already decoded into a number (in which case might as well
// access as number); or is still retained as text (in which case we
// should further defer decoding that may not need BigDecimal):
writeNumber(p.getDecimalValue());
} else {
switch (p.getNumberType()) {
case BIG_DECIMAL:
writeNumber(p.getDecimalValue());
break;
case FLOAT:
writeNumber(p.getFloatValue());
break;
default:
writeNumber(p.getDoubleValue());
}
}
break;
case VALUE_TRUE:
writeBoolean(true);
break;
case VALUE_FALSE:
writeBoolean(false);
break;
case VALUE_NULL:
writeNull();
break;
case VALUE_EMBEDDED_OBJECT:
writeObject(p.getEmbeddedObject());
break;
default:
throw new RuntimeException("Internal error: unexpected token: "+p.getCurrentToken());
}
}
@Override
public void copyCurrentStructure(JsonParser p) throws IOException
{
JsonToken t = p.getCurrentToken();
// Let's handle field-name separately first
if (t == JsonToken.FIELD_NAME) {
if (_mayHaveNativeIds) {
_checkNativeIds(p);
}
writeFieldName(p.getCurrentName());
t = p.nextToken();
// fall-through to copy the associated value
} else if (t == null) {
throw new IllegalStateException("No token available from argument `JsonParser`");
}
// We'll do minor handling here to separate structured, scalar values,
// then delegate appropriately.
// Plus also deal with oddity of "dangling" END_OBJECT/END_ARRAY
switch (t) {
case START_ARRAY:
if (_mayHaveNativeIds) {
_checkNativeIds(p);
}
writeStartArray();
_copyContents(p);
break;
case START_OBJECT:
if (_mayHaveNativeIds) {
_checkNativeIds(p);
}
writeStartObject();
_copyContents(p);
break;
case END_ARRAY:
writeEndArray();
break;
case END_OBJECT:
writeEndObject();
break;
default: // others are simple:
_copyCurrentValue(p, t);
}
}
private final void _copyContents(JsonParser p) throws IOException
{
int depth = 1;
JsonToken t;
while ((t = p.nextToken()) != null) {
switch (t) {
case FIELD_NAME:
if (_mayHaveNativeIds) {
_checkNativeIds(p);
}
writeFieldName(p.getCurrentName());
break;
case START_ARRAY:
if (_mayHaveNativeIds) {
_checkNativeIds(p);
}
writeStartArray();
++depth;
break;
case START_OBJECT:
if (_mayHaveNativeIds) {
_checkNativeIds(p);
}
writeStartObject();
++depth;
break;
case END_ARRAY:
writeEndArray();
if (--depth == 0) {
return;
}
break;
case END_OBJECT:
writeEndObject();
if (--depth == 0) {
return;
}
break;
default:
_copyCurrentValue(p, t);
}
}
}
// NOTE: Copied from earlier `copyCurrentEvent()`
private void _copyCurrentValue(JsonParser p, JsonToken t) throws IOException
{
if (_mayHaveNativeIds) {
_checkNativeIds(p);
}
switch (t) {
case VALUE_STRING:
if (p.hasTextCharacters()) {
writeString(p.getTextCharacters(), p.getTextOffset(), p.getTextLength());
} else {
writeString(p.getText());
}
break;
case VALUE_NUMBER_INT:
switch (p.getNumberType()) {
case INT:
writeNumber(p.getIntValue());
break;
case BIG_INTEGER:
writeNumber(p.getBigIntegerValue());
break;
default:
writeNumber(p.getLongValue());
}
break;
case VALUE_NUMBER_FLOAT:
if (_forceBigDecimal) {
writeNumber(p.getDecimalValue());
} else {
switch (p.getNumberType()) {
case BIG_DECIMAL:
writeNumber(p.getDecimalValue());
break;
case FLOAT:
writeNumber(p.getFloatValue());
break;
default:
writeNumber(p.getDoubleValue());
}
}
break;
case VALUE_TRUE:
writeBoolean(true);
break;
case VALUE_FALSE:
writeBoolean(false);
break;
case VALUE_NULL:
writeNull();
break;
case VALUE_EMBEDDED_OBJECT:
writeObject(p.getEmbeddedObject());
break;
default:
throw new RuntimeException("Internal error: unexpected token: "+t);
}
}
private final void _checkNativeIds(JsonParser p) throws IOException
{
if ((_typeId = p.getTypeId()) != null) {
_hasNativeId = true;
}
if ((_objectId = p.getObjectId()) != null) {
_hasNativeId = true;
}
}
/*
/**********************************************************
/* Internal methods
/**********************************************************
*/
/*// Not used in / since 2.10
protected final void _append(JsonToken type)
{
Segment next;
if (_hasNativeId) {
next =_last.append(_appendAt, type, _objectId, _typeId);
} else {
next = _last.append(_appendAt, type);
}
if (next == null) {
++_appendAt;
} else {
_last = next;
_appendAt = 1; // since we added first at 0
}
}
protected final void _append(JsonToken type, Object value)
{
Segment next;
if (_hasNativeId) {
next = _last.append(_appendAt, type, value, _objectId, _typeId);
} else {
next = _last.append(_appendAt, type, value);
}
if (next == null) {
++_appendAt;
} else {
_last = next;
_appendAt = 1;
}
}
*/
/**
* Method used for appending token known to represent a "simple" scalar
* value where token is the only information
*
* @since 2.6.4
*/
protected final void _appendValue(JsonToken type)
{
_writeContext.writeValue();
Segment next;
if (_hasNativeId) {
next = _last.append(_appendAt, type, _objectId, _typeId);
} else {
next = _last.append(_appendAt, type);
}
if (next == null) {
++_appendAt;
} else {
_last = next;
_appendAt = 1; // since we added first at 0
}
}
/**
* Method used for appending token known to represent a scalar value
* where there is additional content (text, number) beyond type token
*
* @since 2.6.4
*/
protected final void _appendValue(JsonToken type, Object value)
{
_writeContext.writeValue();
Segment next;
if (_hasNativeId) {
next = _last.append(_appendAt, type, value, _objectId, _typeId);
} else {
next = _last.append(_appendAt, type, value);
}
if (next == null) {
++_appendAt;
} else {
_last = next;
_appendAt = 1;
}
}
/**
* Specialized method used for appending a field name, appending either
* {@link String} or {@link SerializableString}.
*
* @since 2.10
*/
protected final void _appendFieldName(Object value)
{
// NOTE: do NOT clear _objectId / _typeId
Segment next;
if (_hasNativeId) {
next = _last.append(_appendAt, JsonToken.FIELD_NAME, value, _objectId, _typeId);
} else {
next = _last.append(_appendAt, JsonToken.FIELD_NAME, value);
}
if (next == null) {
++_appendAt;
} else {
_last = next;
_appendAt = 1;
}
}
/**
* Specialized method used for appending a structural start Object/Array marker
*
* @since 2.10
*/
protected final void _appendStartMarker(JsonToken type)
{
Segment next;
if (_hasNativeId) {
next =_last.append(_appendAt, type, _objectId, _typeId);
} else {
next = _last.append(_appendAt, type);
}
if (next == null) {
++_appendAt;
} else {
_last = next;
_appendAt = 1; // since we added first at 0
}
}
/**
* Specialized method used for appending a structural end Object/Array marker
*
* @since 2.10
*/
protected final void _appendEndMarker(JsonToken type)
{
// NOTE: type/object id not relevant
Segment next = _last.append(_appendAt, type);
if (next == null) {
++_appendAt;
} else {
_last = next;
_appendAt = 1;
}
}
@Override
protected void _reportUnsupportedOperation() {
throw new UnsupportedOperationException("Called operation not supported for TokenBuffer");
}
/*
/**********************************************************
/* Supporting classes
/**********************************************************
*/
protected final static class Parser
extends ParserMinimalBase
{
/*
/**********************************************************
/* Configuration
/**********************************************************
*/
protected ObjectCodec _codec;
/**
* @since 2.3
*/
protected final boolean _hasNativeTypeIds;
/**
* @since 2.3
*/
protected final boolean _hasNativeObjectIds;
protected final boolean _hasNativeIds;
/*
/**********************************************************
/* Parsing state
/**********************************************************
*/
/**
* Currently active segment
*/
protected Segment _segment;
/**
* Pointer to current token within current segment
*/
protected int _segmentPtr;
/**
* Information about parser context, context in which
* the next token is to be parsed (root, array, object).
*/
protected TokenBufferReadContext _parsingContext;
protected boolean _closed;
protected transient ByteArrayBuilder _byteBuilder;
protected JsonLocation _location = null;
/*
/**********************************************************
/* Construction, init
/**********************************************************
*/
@Deprecated // since 2.9
public Parser(Segment firstSeg, ObjectCodec codec,
boolean hasNativeTypeIds, boolean hasNativeObjectIds)
{
this(firstSeg, codec, hasNativeTypeIds, hasNativeObjectIds, null);
}
public Parser(Segment firstSeg, ObjectCodec codec,
boolean hasNativeTypeIds, boolean hasNativeObjectIds,
JsonStreamContext parentContext)
{
super(0);
_segment = firstSeg;
_segmentPtr = -1; // not yet read
_codec = codec;
_parsingContext = TokenBufferReadContext.createRootContext(parentContext);
_hasNativeTypeIds = hasNativeTypeIds;
_hasNativeObjectIds = hasNativeObjectIds;
_hasNativeIds = (hasNativeTypeIds | hasNativeObjectIds);
}
public void setLocation(JsonLocation l) {
_location = l;
}
@Override
public ObjectCodec getCodec() { return _codec; }
@Override
public void setCodec(ObjectCodec c) { _codec = c; }
@Override
public Version version() {
return com.fasterxml.jackson.databind.cfg.PackageVersion.VERSION;
}
/*
/**********************************************************
/* Extended API beyond JsonParser
/**********************************************************
*/
public JsonToken peekNextToken() throws IOException
{
// closed? nothing more to peek, either
if (_closed) return null;
Segment seg = _segment;
int ptr = _segmentPtr+1;
if (ptr >= Segment.TOKENS_PER_SEGMENT) {
ptr = 0;
seg = (seg == null) ? null : seg.next();
}
return (seg == null) ? null : seg.type(ptr);
}
/*
/**********************************************************
/* Closeable implementation
/**********************************************************
*/
@Override
public void close() throws IOException {
if (!_closed) {
_closed = true;
}
}
/*
/**********************************************************
/* Public API, traversal
/**********************************************************
*/
@Override
public JsonToken nextToken() throws IOException
{
// If we are closed, nothing more to do
if (_closed || (_segment == null)) return null;
// Ok, then: any more tokens?
if (++_segmentPtr >= Segment.TOKENS_PER_SEGMENT) {
_segmentPtr = 0;
_segment = _segment.next();
if (_segment == null) {
return null;
}
}
_currToken = _segment.type(_segmentPtr);
// Field name? Need to update context
if (_currToken == JsonToken.FIELD_NAME) {
Object ob = _currentObject();
String name = (ob instanceof String) ? ((String) ob) : ob.toString();
_parsingContext.setCurrentName(name);
} else if (_currToken == JsonToken.START_OBJECT) {
_parsingContext = _parsingContext.createChildObjectContext();
} else if (_currToken == JsonToken.START_ARRAY) {
_parsingContext = _parsingContext.createChildArrayContext();
} else if (_currToken == JsonToken.END_OBJECT
|| _currToken == JsonToken.END_ARRAY) {
// Closing JSON Object/Array? Close matching context
_parsingContext = _parsingContext.parentOrCopy();
}
return _currToken;
}
@Override
public String nextFieldName() throws IOException
{
// inlined common case from nextToken()
if (_closed || (_segment == null)) {
return null;
}
int ptr = _segmentPtr+1;
if ((ptr < Segment.TOKENS_PER_SEGMENT) && (_segment.type(ptr) == JsonToken.FIELD_NAME)) {
_segmentPtr = ptr;
_currToken = JsonToken.FIELD_NAME;
Object ob = _segment.get(ptr); // inlined _currentObject();
String name = (ob instanceof String) ? ((String) ob) : ob.toString();
_parsingContext.setCurrentName(name);
return name;
}
return (nextToken() == JsonToken.FIELD_NAME) ? getCurrentName() : null;
}
@Override
public boolean isClosed() { return _closed; }
/*
/**********************************************************
/* Public API, token accessors
/**********************************************************
*/
@Override
public JsonStreamContext getParsingContext() { return _parsingContext; }
@Override
public JsonLocation getTokenLocation() { return getCurrentLocation(); }
@Override
public JsonLocation getCurrentLocation() {
return (_location == null) ? JsonLocation.NA : _location;
}
@Override
public String getCurrentName() {
// 25-Jun-2015, tatu: as per [databind#838], needs to be same as ParserBase
if (_currToken == JsonToken.START_OBJECT || _currToken == JsonToken.START_ARRAY) {
JsonStreamContext parent = _parsingContext.getParent();
return parent.getCurrentName();
}
return _parsingContext.getCurrentName();
}
@Override
public void overrideCurrentName(String name)
{
// Simple, but need to look for START_OBJECT/ARRAY's "off-by-one" thing:
JsonStreamContext ctxt = _parsingContext;
if (_currToken == JsonToken.START_OBJECT || _currToken == JsonToken.START_ARRAY) {
ctxt = ctxt.getParent();
}
if (ctxt instanceof TokenBufferReadContext) {
try {
((TokenBufferReadContext) ctxt).setCurrentName(name);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
/*
/**********************************************************
/* Public API, access to token information, text
/**********************************************************
*/
@Override
public String getText()
{
// common cases first:
if (_currToken == JsonToken.VALUE_STRING
|| _currToken == JsonToken.FIELD_NAME) {
Object ob = _currentObject();
if (ob instanceof String) {
return (String) ob;
}
return ClassUtil.nullOrToString(ob);
}
if (_currToken == null) {
return null;
}
switch (_currToken) {
case VALUE_NUMBER_INT:
case VALUE_NUMBER_FLOAT:
return ClassUtil.nullOrToString(_currentObject());
default:
return _currToken.asString();
}
}
@Override
public char[] getTextCharacters() {
String str = getText();
return (str == null) ? null : str.toCharArray();
}
@Override
public int getTextLength() {
String str = getText();
return (str == null) ? 0 : str.length();
}
@Override
public int getTextOffset() { return 0; }
@Override
public boolean hasTextCharacters() {
// We never have raw buffer available, so:
return false;
}
/*
/**********************************************************
/* Public API, access to token information, numeric
/**********************************************************
*/
@Override
public boolean isNaN() {
// can only occur for floating-point numbers
if (_currToken == JsonToken.VALUE_NUMBER_FLOAT) {
Object value = _currentObject();
if (value instanceof Double) {
Double v = (Double) value;
return v.isNaN() || v.isInfinite();
}
if (value instanceof Float) {
Float v = (Float) value;
return v.isNaN() || v.isInfinite();
}
}
return false;
}
@Override
public BigInteger getBigIntegerValue() throws IOException
{
Number n = getNumberValue();
if (n instanceof BigInteger) {
return (BigInteger) n;
}
if (getNumberType() == NumberType.BIG_DECIMAL) {
return ((BigDecimal) n).toBigInteger();
}
// int/long is simple, but let's also just truncate float/double:
return BigInteger.valueOf(n.longValue());
}
@Override
public BigDecimal getDecimalValue() throws IOException
{
Number n = getNumberValue();
if (n instanceof BigDecimal) {
return (BigDecimal) n;
}
switch (getNumberType()) {
case INT:
case LONG:
return BigDecimal.valueOf(n.longValue());
case BIG_INTEGER:
return new BigDecimal((BigInteger) n);
default:
}
// float or double
return BigDecimal.valueOf(n.doubleValue());
}
@Override
public double getDoubleValue() throws IOException {
return getNumberValue().doubleValue();
}
@Override
public float getFloatValue() throws IOException {
return getNumberValue().floatValue();
}
@Override
public int getIntValue() throws IOException
{
Number n = (_currToken == JsonToken.VALUE_NUMBER_INT) ?
((Number) _currentObject()) : getNumberValue();
if ((n instanceof Integer) || _smallerThanInt(n)) {
return n.intValue();
}
return _convertNumberToInt(n);
}
@Override
public long getLongValue() throws IOException {
Number n = (_currToken == JsonToken.VALUE_NUMBER_INT) ?
((Number) _currentObject()) : getNumberValue();
if ((n instanceof Long) || _smallerThanLong(n)) {
return n.longValue();
}
return _convertNumberToLong(n);
}
@Override
public NumberType getNumberType() throws IOException
{
Number n = getNumberValue();
if (n instanceof Integer) return NumberType.INT;
if (n instanceof Long) return NumberType.LONG;
if (n instanceof Double) return NumberType.DOUBLE;
if (n instanceof BigDecimal) return NumberType.BIG_DECIMAL;
if (n instanceof BigInteger) return NumberType.BIG_INTEGER;
if (n instanceof Float) return NumberType.FLOAT;
if (n instanceof Short) return NumberType.INT; // should be SHORT
return null;
}
@Override
public final Number getNumberValue() throws IOException {
_checkIsNumber();
Object value = _currentObject();
if (value instanceof Number) {
return (Number) value;
}
// Difficult to really support numbers-as-Strings; but let's try.
// NOTE: no access to DeserializationConfig, unfortunately, so cannot
// try to determine Double/BigDecimal preference...
if (value instanceof String) {
String str = (String) value;
if (str.indexOf('.') >= 0) {
return Double.parseDouble(str);
}
return Long.parseLong(str);
}
if (value == null) {
return null;
}
throw new IllegalStateException("Internal error: entry should be a Number, but is of type "
+value.getClass().getName());
}
private final boolean _smallerThanInt(Number n) {
return (n instanceof Short) || (n instanceof Byte);
}
private final boolean _smallerThanLong(Number n) {
return (n instanceof Integer) || (n instanceof Short) || (n instanceof Byte);
}
// 02-Jan-2017, tatu: Modified from method(s) in `ParserBase`
protected int _convertNumberToInt(Number n) throws IOException
{
if (n instanceof Long) {
long l = n.longValue();
int result = (int) l;
if (((long) result) != l) {
reportOverflowInt();
}
return result;
}
if (n instanceof BigInteger) {
BigInteger big = (BigInteger) n;
if (BI_MIN_INT.compareTo(big) > 0
|| BI_MAX_INT.compareTo(big) < 0) {
reportOverflowInt();
}
} else if ((n instanceof Double) || (n instanceof Float)) {
double d = n.doubleValue();
// Need to check boundaries
if (d < MIN_INT_D || d > MAX_INT_D) {
reportOverflowInt();
}
return (int) d;
} else if (n instanceof BigDecimal) {
BigDecimal big = (BigDecimal) n;
if (BD_MIN_INT.compareTo(big) > 0
|| BD_MAX_INT.compareTo(big) < 0) {
reportOverflowInt();
}
} else {
_throwInternal();
}
return n.intValue();
}
protected long _convertNumberToLong(Number n) throws IOException
{
if (n instanceof BigInteger) {
BigInteger big = (BigInteger) n;
if (BI_MIN_LONG.compareTo(big) > 0
|| BI_MAX_LONG.compareTo(big) < 0) {
reportOverflowLong();
}
} else if ((n instanceof Double) || (n instanceof Float)) {
double d = n.doubleValue();
// Need to check boundaries
if (d < MIN_LONG_D || d > MAX_LONG_D) {
reportOverflowLong();
}
return (long) d;
} else if (n instanceof BigDecimal) {
BigDecimal big = (BigDecimal) n;
if (BD_MIN_LONG.compareTo(big) > 0
|| BD_MAX_LONG.compareTo(big) < 0) {
reportOverflowLong();
}
} else {
_throwInternal();
}
return n.longValue();
}
/*
/**********************************************************
/* Public API, access to token information, other
/**********************************************************
*/
@Override
public Object getEmbeddedObject()
{
if (_currToken == JsonToken.VALUE_EMBEDDED_OBJECT) {
return _currentObject();
}
return null;
}
@Override
@SuppressWarnings("resource")
public byte[] getBinaryValue(Base64Variant b64variant) throws IOException, JsonParseException
{
// First: maybe we some special types?
if (_currToken == JsonToken.VALUE_EMBEDDED_OBJECT) {
// Embedded byte array would work nicely...
Object ob = _currentObject();
if (ob instanceof byte[]) {
return (byte[]) ob;
}
// fall through to error case
}
if (_currToken != JsonToken.VALUE_STRING) {
throw _constructError("Current token ("+_currToken+") not VALUE_STRING (or VALUE_EMBEDDED_OBJECT with byte[]), cannot access as binary");
}
final String str = getText();
if (str == null) {
return null;
}
ByteArrayBuilder builder = _byteBuilder;
if (builder == null) {
_byteBuilder = builder = new ByteArrayBuilder(100);
} else {
_byteBuilder.reset();
}
_decodeBase64(str, builder, b64variant);
return builder.toByteArray();
}
@Override
public int readBinaryValue(Base64Variant b64variant, OutputStream out) throws IOException
{
byte[] data = getBinaryValue(b64variant);
if (data != null) {
out.write(data, 0, data.length);
return data.length;
}
return 0;
}
/*
/**********************************************************
/* Public API, native ids
/**********************************************************
*/
@Override
public boolean canReadObjectId() {
return _hasNativeObjectIds;
}
@Override
public boolean canReadTypeId() {
return _hasNativeTypeIds;
}
@Override
public Object getTypeId() {
return _segment.findTypeId(_segmentPtr);
}
@Override
public Object getObjectId() {
return _segment.findObjectId(_segmentPtr);
}
/*
/**********************************************************
/* Internal methods
/**********************************************************
*/
protected final Object _currentObject() {
return _segment.get(_segmentPtr);
}
protected final void _checkIsNumber() throws JsonParseException
{
if (_currToken == null || !_currToken.isNumeric()) {
throw _constructError("Current token ("+_currToken+") not numeric, cannot use numeric value accessors");
}
}
@Override
protected void _handleEOF() throws JsonParseException {
_throwInternal();
}
}
/**
* Individual segment of TokenBuffer that can store up to 16 tokens
* (limited by 4 bits per token type marker requirement).
* Current implementation uses fixed length array; could alternatively
* use 16 distinct fields and switch statement (slightly more efficient
* storage, slightly slower access)
*/
protected final static class Segment
{
public final static int TOKENS_PER_SEGMENT = 16;
/**
* Static array used for fast conversion between token markers and
* matching {@link JsonToken} instances
*/
private final static JsonToken[] TOKEN_TYPES_BY_INDEX;
static {
// ... here we know that there are <= 15 values in JsonToken enum
TOKEN_TYPES_BY_INDEX = new JsonToken[16];
JsonToken[] t = JsonToken.values();
// and reserve entry 0 for "not available"
System.arraycopy(t, 1, TOKEN_TYPES_BY_INDEX, 1, Math.min(15, t.length - 1));
}
// // // Linking
protected Segment _next;
// // // State
/**
* Bit field used to store types of buffered tokens; 4 bits per token.
* Value 0 is reserved for "not in use"
*/
protected long _tokenTypes;
// Actual tokens
protected final Object[] _tokens = new Object[TOKENS_PER_SEGMENT];
/**
* Lazily constructed Map for storing native type and object ids, if any
*/
protected TreeMap<Integer,Object> _nativeIds;
public Segment() { }
// // // Accessors
public JsonToken type(int index)
{
long l = _tokenTypes;
if (index > 0) {
l >>= (index << 2);
}
int ix = ((int) l) & 0xF;
return TOKEN_TYPES_BY_INDEX[ix];
}
public int rawType(int index)
{
long l = _tokenTypes;
if (index > 0) {
l >>= (index << 2);
}
int ix = ((int) l) & 0xF;
return ix;
}
public Object get(int index) {
return _tokens[index];
}
public Segment next() { return _next; }
/**
* Accessor for checking whether this segment may have native
* type or object ids.
*/
public boolean hasIds() {
return _nativeIds != null;
}
// // // Mutators
public Segment append(int index, JsonToken tokenType)
{
if (index < TOKENS_PER_SEGMENT) {
set(index, tokenType);
return null;
}
_next = new Segment();
_next.set(0, tokenType);
return _next;
}
public Segment append(int index, JsonToken tokenType,
Object objectId, Object typeId)
{
if (index < TOKENS_PER_SEGMENT) {
set(index, tokenType, objectId, typeId);
return null;
}
_next = new Segment();
_next.set(0, tokenType, objectId, typeId);
return _next;
}
public Segment append(int index, JsonToken tokenType, Object value)
{
if (index < TOKENS_PER_SEGMENT) {
set(index, tokenType, value);
return null;
}
_next = new Segment();
_next.set(0, tokenType, value);
return _next;
}
public Segment append(int index, JsonToken tokenType, Object value,
Object objectId, Object typeId)
{
if (index < TOKENS_PER_SEGMENT) {
set(index, tokenType, value, objectId, typeId);
return null;
}
_next = new Segment();
_next.set(0, tokenType, value, objectId, typeId);
return _next;
}
/*
public Segment appendRaw(int index, int rawTokenType, Object value)
{
if (index < TOKENS_PER_SEGMENT) {
set(index, rawTokenType, value);
return null;
}
_next = new Segment();
_next.set(0, rawTokenType, value);
return _next;
}
public Segment appendRaw(int index, int rawTokenType, Object value,
Object objectId, Object typeId)
{
if (index < TOKENS_PER_SEGMENT) {
set(index, rawTokenType, value, objectId, typeId);
return null;
}
_next = new Segment();
_next.set(0, rawTokenType, value, objectId, typeId);
return _next;
}
private void set(int index, int rawTokenType, Object value, Object objectId, Object typeId)
{
_tokens[index] = value;
long typeCode = (long) rawTokenType;
if (index > 0) {
typeCode <<= (index << 2);
}
_tokenTypes |= typeCode;
assignNativeIds(index, objectId, typeId);
}
private void set(int index, int rawTokenType, Object value)
{
_tokens[index] = value;
long typeCode = (long) rawTokenType;
if (index > 0) {
typeCode <<= (index << 2);
}
_tokenTypes |= typeCode;
}
*/
private void set(int index, JsonToken tokenType)
{
/* Assumption here is that there are no overwrites, just appends;
* and so no masking is needed (nor explicit setting of null)
*/
long typeCode = tokenType.ordinal();
if (index > 0) {
typeCode <<= (index << 2);
}
_tokenTypes |= typeCode;
}
private void set(int index, JsonToken tokenType,
Object objectId, Object typeId)
{
long typeCode = tokenType.ordinal();
if (index > 0) {
typeCode <<= (index << 2);
}
_tokenTypes |= typeCode;
assignNativeIds(index, objectId, typeId);
}
private void set(int index, JsonToken tokenType, Object value)
{
_tokens[index] = value;
long typeCode = tokenType.ordinal();
if (index > 0) {
typeCode <<= (index << 2);
}
_tokenTypes |= typeCode;
}
private void set(int index, JsonToken tokenType, Object value,
Object objectId, Object typeId)
{
_tokens[index] = value;
long typeCode = tokenType.ordinal();
if (index > 0) {
typeCode <<= (index << 2);
}
_tokenTypes |= typeCode;
assignNativeIds(index, objectId, typeId);
}
private final void assignNativeIds(int index, Object objectId, Object typeId)
{
if (_nativeIds == null) {
_nativeIds = new TreeMap<Integer,Object>();
}
if (objectId != null) {
_nativeIds.put(_objectIdIndex(index), objectId);
}
if (typeId != null) {
_nativeIds.put(_typeIdIndex(index), typeId);
}
}
/**
* @since 2.3
*/
private Object findObjectId(int index) {
return (_nativeIds == null) ? null : _nativeIds.get(_objectIdIndex(index));
}
/**
* @since 2.3
*/
private Object findTypeId(int index) {
return (_nativeIds == null) ? null : _nativeIds.get(_typeIdIndex(index));
}
private final int _typeIdIndex(int i) { return i+i; }
private final int _objectIdIndex(int i) { return i+i+1; }
}
}
| src/main/java/com/fasterxml/jackson/databind/util/TokenBuffer.java | package com.fasterxml.jackson.databind.util;
import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.TreeMap;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.core.base.ParserMinimalBase;
import com.fasterxml.jackson.core.json.JsonWriteContext;
import com.fasterxml.jackson.core.util.ByteArrayBuilder;
import com.fasterxml.jackson.databind.*;
/**
* Utility class used for efficient storage of {@link JsonToken}
* sequences, needed for temporary buffering.
* Space efficient for different sequence lengths (especially so for smaller
* ones; but not significantly less efficient for larger), highly efficient
* for linear iteration and appending. Implemented as segmented/chunked
* linked list of tokens; only modifications are via appends.
*<p>
* Note that before version 2.0, this class was located in the "core"
* bundle, not data-binding; but since it was only used by data binding,
* was moved here to reduce size of core package
*/
public class TokenBuffer
/* Won't use JsonGeneratorBase, to minimize overhead for validity
* checking
*/
extends JsonGenerator
{
protected final static int DEFAULT_GENERATOR_FEATURES = JsonGenerator.Feature.collectDefaults();
/*
/**********************************************************
/* Configuration
/**********************************************************
*/
/**
* Object codec to use for stream-based object
* conversion through parser/generator interfaces. If null,
* such methods cannot be used.
*/
protected ObjectCodec _objectCodec;
/**
* Parse context from "parent" parser (one from which content to buffer is read,
* if specified). Used, if available, when reading content, to present full
* context as if content was read from the original parser: this is useful
* in error reporting and sometimes processing as well.
*/
protected JsonStreamContext _parentContext;
/**
* Bit flag composed of bits that indicate which
* {@link com.fasterxml.jackson.core.JsonGenerator.Feature}s
* are enabled.
*<p>
* NOTE: most features have no effect on this class
*/
protected int _generatorFeatures;
protected boolean _closed;
/**
* @since 2.3
*/
protected boolean _hasNativeTypeIds;
/**
* @since 2.3
*/
protected boolean _hasNativeObjectIds;
/**
* @since 2.3
*/
protected boolean _mayHaveNativeIds;
/**
* Flag set during construction, if use of {@link BigDecimal} is to be forced
* on all floating-point values.
*
* @since 2.7
*/
protected boolean _forceBigDecimal;
/*
/**********************************************************
/* Token buffering state
/**********************************************************
*/
/**
* First segment, for contents this buffer has
*/
protected Segment _first;
/**
* Last segment of this buffer, one that is used
* for appending more tokens
*/
protected Segment _last;
/**
* Offset within last segment,
*/
protected int _appendAt;
/**
* If native type ids supported, this is the id for following
* value (or first token of one) to be written.
*/
protected Object _typeId;
/**
* If native object ids supported, this is the id for following
* value (or first token of one) to be written.
*/
protected Object _objectId;
/**
* Do we currently have a native type or object id buffered?
*/
protected boolean _hasNativeId = false;
/*
/**********************************************************
/* Output state
/**********************************************************
*/
protected JsonWriteContext _writeContext;
/*
/**********************************************************
/* Life-cycle
/**********************************************************
*/
/**
* @param codec Object codec to use for stream-based object
* conversion through parser/generator interfaces. If null,
* such methods cannot be used.
* @param hasNativeIds Whether resulting {@link JsonParser} (if created)
* is considered to support native type and object ids
*/
public TokenBuffer(ObjectCodec codec, boolean hasNativeIds)
{
_objectCodec = codec;
_generatorFeatures = DEFAULT_GENERATOR_FEATURES;
_writeContext = JsonWriteContext.createRootContext(null);
// at first we have just one segment
_first = _last = new Segment();
_appendAt = 0;
_hasNativeTypeIds = hasNativeIds;
_hasNativeObjectIds = hasNativeIds;
_mayHaveNativeIds = _hasNativeTypeIds | _hasNativeObjectIds;
}
/**
* @since 2.3
*/
public TokenBuffer(JsonParser p) {
this(p, null);
}
/**
* @since 2.7
*/
public TokenBuffer(JsonParser p, DeserializationContext ctxt)
{
_objectCodec = p.getCodec();
_parentContext = p.getParsingContext();
_generatorFeatures = DEFAULT_GENERATOR_FEATURES;
_writeContext = JsonWriteContext.createRootContext(null);
// at first we have just one segment
_first = _last = new Segment();
_appendAt = 0;
_hasNativeTypeIds = p.canReadTypeId();
_hasNativeObjectIds = p.canReadObjectId();
_mayHaveNativeIds = _hasNativeTypeIds | _hasNativeObjectIds;
_forceBigDecimal = (ctxt == null) ? false
: ctxt.isEnabled(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
}
/**
* Convenience method, equivalent to:
*<pre>
* TokenBuffer b = new TokenBuffer(p);
* b.copyCurrentStructure(p);
* return b;
*</pre>
*
* @since 2.9
*/
public static TokenBuffer asCopyOfValue(JsonParser p) throws IOException {
TokenBuffer b = new TokenBuffer(p);
b.copyCurrentStructure(p);
return b;
}
/**
* Method that allows explicitly specifying parent parse context to associate
* with contents of this buffer. Usually context is assigned at construction,
* based on given parser; but it is not always available, and may not contain
* intended context.
*
* @since 2.9
*/
public TokenBuffer overrideParentContext(JsonStreamContext ctxt) {
_parentContext = ctxt;
return this;
}
/**
* @since 2.7
*/
public TokenBuffer forceUseOfBigDecimal(boolean b) {
_forceBigDecimal = b;
return this;
}
@Override
public Version version() {
return com.fasterxml.jackson.databind.cfg.PackageVersion.VERSION;
}
/**
* Method used to create a {@link JsonParser} that can read contents
* stored in this buffer. Will use default <code>_objectCodec</code> for
* object conversions.
*<p>
* Note: instances are not synchronized, that is, they are not thread-safe
* if there are concurrent appends to the underlying buffer.
*
* @return Parser that can be used for reading contents stored in this buffer
*/
public JsonParser asParser() {
return asParser(_objectCodec);
}
/**
* Same as:
*<pre>
* JsonParser p = asParser();
* p.nextToken();
* return p;
*</pre>
*
* @since 2.9
*/
public JsonParser asParserOnFirstToken() throws IOException {
JsonParser p = asParser(_objectCodec);
p.nextToken();
return p;
}
/**
* Method used to create a {@link JsonParser} that can read contents
* stored in this buffer.
*<p>
* Note: instances are not synchronized, that is, they are not thread-safe
* if there are concurrent appends to the underlying buffer.
*
* @param codec Object codec to use for stream-based object
* conversion through parser/generator interfaces. If null,
* such methods cannot be used.
*
* @return Parser that can be used for reading contents stored in this buffer
*/
public JsonParser asParser(ObjectCodec codec)
{
return new Parser(_first, codec, _hasNativeTypeIds, _hasNativeObjectIds, _parentContext);
}
/**
* @param src Parser to use for accessing source information
* like location, configured codec
*/
public JsonParser asParser(JsonParser src)
{
Parser p = new Parser(_first, src.getCodec(), _hasNativeTypeIds, _hasNativeObjectIds, _parentContext);
p.setLocation(src.getTokenLocation());
return p;
}
/*
/**********************************************************
/* Additional accessors
/**********************************************************
*/
public JsonToken firstToken() {
// no need to null check; never create without `_first`
return _first.type(0);
}
/*
/**********************************************************
/* Other custom methods not needed for implementing interfaces
/**********************************************************
*/
/**
* Helper method that will append contents of given buffer into this
* buffer.
* Not particularly optimized; can be made faster if there is need.
*
* @return This buffer
*/
@SuppressWarnings("resource")
public TokenBuffer append(TokenBuffer other) throws IOException
{
// Important? If source has native ids, need to store
if (!_hasNativeTypeIds) {
_hasNativeTypeIds = other.canWriteTypeId();
}
if (!_hasNativeObjectIds) {
_hasNativeObjectIds = other.canWriteObjectId();
}
_mayHaveNativeIds = _hasNativeTypeIds | _hasNativeObjectIds;
JsonParser p = other.asParser();
while (p.nextToken() != null) {
copyCurrentStructure(p);
}
return this;
}
/**
* Helper method that will write all contents of this buffer
* using given {@link JsonGenerator}.
*<p>
* Note: this method would be enough to implement
* <code>JsonSerializer</code> for <code>TokenBuffer</code> type;
* but we cannot have upwards
* references (from core to mapper package); and as such we also
* cannot take second argument.
*/
public void serialize(JsonGenerator gen) throws IOException
{
Segment segment = _first;
int ptr = -1;
final boolean checkIds = _mayHaveNativeIds;
boolean hasIds = checkIds && (segment.hasIds());
while (true) {
if (++ptr >= Segment.TOKENS_PER_SEGMENT) {
ptr = 0;
segment = segment.next();
if (segment == null) break;
hasIds = checkIds && (segment.hasIds());
}
JsonToken t = segment.type(ptr);
if (t == null) break;
if (hasIds) {
Object id = segment.findObjectId(ptr);
if (id != null) {
gen.writeObjectId(id);
}
id = segment.findTypeId(ptr);
if (id != null) {
gen.writeTypeId(id);
}
}
// Note: copied from 'copyCurrentEvent'...
switch (t) {
case START_OBJECT:
gen.writeStartObject();
break;
case END_OBJECT:
gen.writeEndObject();
break;
case START_ARRAY:
gen.writeStartArray();
break;
case END_ARRAY:
gen.writeEndArray();
break;
case FIELD_NAME:
{
// 13-Dec-2010, tatu: Maybe we should start using different type tokens to reduce casting?
Object ob = segment.get(ptr);
if (ob instanceof SerializableString) {
gen.writeFieldName((SerializableString) ob);
} else {
gen.writeFieldName((String) ob);
}
}
break;
case VALUE_STRING:
{
Object ob = segment.get(ptr);
if (ob instanceof SerializableString) {
gen.writeString((SerializableString) ob);
} else {
gen.writeString((String) ob);
}
}
break;
case VALUE_NUMBER_INT:
{
Object n = segment.get(ptr);
if (n instanceof Integer) {
gen.writeNumber((Integer) n);
} else if (n instanceof BigInteger) {
gen.writeNumber((BigInteger) n);
} else if (n instanceof Long) {
gen.writeNumber((Long) n);
} else if (n instanceof Short) {
gen.writeNumber((Short) n);
} else {
gen.writeNumber(((Number) n).intValue());
}
}
break;
case VALUE_NUMBER_FLOAT:
{
Object n = segment.get(ptr);
if (n instanceof Double) {
gen.writeNumber(((Double) n).doubleValue());
} else if (n instanceof BigDecimal) {
gen.writeNumber((BigDecimal) n);
} else if (n instanceof Float) {
gen.writeNumber(((Float) n).floatValue());
} else if (n == null) {
gen.writeNull();
} else if (n instanceof String) {
gen.writeNumber((String) n);
} else {
throw new JsonGenerationException(String.format(
"Unrecognized value type for VALUE_NUMBER_FLOAT: %s, cannot serialize",
n.getClass().getName()), gen);
}
}
break;
case VALUE_TRUE:
gen.writeBoolean(true);
break;
case VALUE_FALSE:
gen.writeBoolean(false);
break;
case VALUE_NULL:
gen.writeNull();
break;
case VALUE_EMBEDDED_OBJECT:
{
Object value = segment.get(ptr);
// 01-Sep-2016, tatu: as per [databind#1361], should use `writeEmbeddedObject()`;
// however, may need to consider alternatives for some well-known types
// first
if (value instanceof RawValue) {
((RawValue) value).serialize(gen);
} else if (value instanceof JsonSerializable) {
gen.writeObject(value);
} else {
gen.writeEmbeddedObject(value);
}
}
break;
default:
throw new RuntimeException("Internal error: should never end up through this code path");
}
}
}
/**
* Helper method used by standard deserializer.
*
* @since 2.3
*/
public TokenBuffer deserialize(JsonParser p, DeserializationContext ctxt) throws IOException
{
if (p.getCurrentTokenId() != JsonToken.FIELD_NAME.id()) {
copyCurrentStructure(p);
return this;
}
/* 28-Oct-2014, tatu: As per [databind#592], need to support a special case of starting from
* FIELD_NAME, which is taken to mean that we are missing START_OBJECT, but need
* to assume one did exist.
*/
JsonToken t;
writeStartObject();
do {
copyCurrentStructure(p);
} while ((t = p.nextToken()) == JsonToken.FIELD_NAME);
if (t != JsonToken.END_OBJECT) {
ctxt.reportWrongTokenException(TokenBuffer.class, JsonToken.END_OBJECT,
"Expected END_OBJECT after copying contents of a JsonParser into TokenBuffer, got "+t);
// never gets here
}
writeEndObject();
return this;
}
@Override
@SuppressWarnings("resource")
public String toString()
{
// Let's print up to 100 first tokens...
final int MAX_COUNT = 100;
StringBuilder sb = new StringBuilder();
sb.append("[TokenBuffer: ");
/*
sb.append("NativeTypeIds=").append(_hasNativeTypeIds).append(",");
sb.append("NativeObjectIds=").append(_hasNativeObjectIds).append(",");
*/
JsonParser jp = asParser();
int count = 0;
final boolean hasNativeIds = _hasNativeTypeIds || _hasNativeObjectIds;
while (true) {
JsonToken t;
try {
t = jp.nextToken();
if (t == null) break;
if (hasNativeIds) {
_appendNativeIds(sb);
}
if (count < MAX_COUNT) {
if (count > 0) {
sb.append(", ");
}
sb.append(t.toString());
if (t == JsonToken.FIELD_NAME) {
sb.append('(');
sb.append(jp.getCurrentName());
sb.append(')');
}
}
} catch (IOException ioe) { // should never occur
throw new IllegalStateException(ioe);
}
++count;
}
if (count >= MAX_COUNT) {
sb.append(" ... (truncated ").append(count-MAX_COUNT).append(" entries)");
}
sb.append(']');
return sb.toString();
}
private final void _appendNativeIds(StringBuilder sb)
{
Object objectId = _last.findObjectId(_appendAt-1);
if (objectId != null) {
sb.append("[objectId=").append(String.valueOf(objectId)).append(']');
}
Object typeId = _last.findTypeId(_appendAt-1);
if (typeId != null) {
sb.append("[typeId=").append(String.valueOf(typeId)).append(']');
}
}
/*
/**********************************************************
/* JsonGenerator implementation: configuration
/**********************************************************
*/
@Override
public JsonGenerator enable(Feature f) {
_generatorFeatures |= f.getMask();
return this;
}
@Override
public JsonGenerator disable(Feature f) {
_generatorFeatures &= ~f.getMask();
return this;
}
//public JsonGenerator configure(SerializationFeature f, boolean state) { }
@Override
public boolean isEnabled(Feature f) {
return (_generatorFeatures & f.getMask()) != 0;
}
@Override
public int getFeatureMask() {
return _generatorFeatures;
}
@Override
@Deprecated
public JsonGenerator setFeatureMask(int mask) {
_generatorFeatures = mask;
return this;
}
@Override
public JsonGenerator overrideStdFeatures(int values, int mask) {
int oldState = getFeatureMask();
_generatorFeatures = (oldState & ~mask) | (values & mask);
return this;
}
@Override
public JsonGenerator useDefaultPrettyPrinter() {
// No-op: we don't indent
return this;
}
@Override
public JsonGenerator setCodec(ObjectCodec oc) {
_objectCodec = oc;
return this;
}
@Override
public ObjectCodec getCodec() { return _objectCodec; }
@Override
public final JsonWriteContext getOutputContext() { return _writeContext; }
/*
/**********************************************************
/* JsonGenerator implementation: capability introspection
/**********************************************************
*/
/**
* Since we can efficiently store <code>byte[]</code>, yes.
*/
@Override
public boolean canWriteBinaryNatively() {
return true;
}
/*
/**********************************************************
/* JsonGenerator implementation: low-level output handling
/**********************************************************
*/
@Override
public void flush() throws IOException { /* NOP */ }
@Override
public void close() throws IOException {
_closed = true;
}
@Override
public boolean isClosed() { return _closed; }
/*
/**********************************************************
/* JsonGenerator implementation: write methods, structural
/**********************************************************
*/
@Override
public final void writeStartArray() throws IOException
{
_writeContext.writeValue();
_appendStartMarker(JsonToken.START_ARRAY);
_writeContext = _writeContext.createChildArrayContext();
}
@Override // since 2.10 (method added in 2.4)
public final void writeStartArray(int size) throws IOException
{
_writeContext.writeValue();
_appendStartMarker(JsonToken.START_ARRAY);
_writeContext = _writeContext.createChildArrayContext();
}
// // TODO: add 2 more `writeStartArray()` methods from 2.10 (in 2.11 or later)
@Override
public final void writeEndArray() throws IOException
{
_appendEndMarker(JsonToken.END_ARRAY);
// Let's allow unbalanced tho... i.e. not run out of root level, ever
JsonWriteContext c = _writeContext.getParent();
if (c != null) {
_writeContext = c;
}
}
@Override
public final void writeStartObject() throws IOException
{
_writeContext.writeValue();
_appendStartMarker(JsonToken.START_OBJECT);
_writeContext = _writeContext.createChildObjectContext();
}
@Override // since 2.8
public void writeStartObject(Object forValue) throws IOException
{
_writeContext.writeValue();
_appendStartMarker(JsonToken.START_OBJECT);
// 15-Aug-2019, tatu: Matching method only added in 2.10, don't yet call
JsonWriteContext ctxt = _writeContext.createChildObjectContext();
_writeContext = ctxt;
if (forValue != null) {
ctxt.setCurrentValue(forValue);
}
}
// // TODO: add 1 more `writeStartObject()` methods from 2.10 (in 2.11 or later)
@Override
public final void writeEndObject() throws IOException
{
_appendEndMarker(JsonToken.END_OBJECT);
// Let's allow unbalanced tho... i.e. not run out of root level, ever
JsonWriteContext c = _writeContext.getParent();
if (c != null) {
_writeContext = c;
}
}
@Override
public final void writeFieldName(String name) throws IOException
{
_writeContext.writeFieldName(name);
_appendFieldName(name);
}
@Override
public void writeFieldName(SerializableString name) throws IOException
{
_writeContext.writeFieldName(name.getValue());
_appendFieldName(name);
}
/*
/**********************************************************
/* JsonGenerator implementation: write methods, textual
/**********************************************************
*/
@Override
public void writeString(String text) throws IOException {
if (text == null) {
writeNull();
} else {
_appendValue(JsonToken.VALUE_STRING, text);
}
}
@Override
public void writeString(char[] text, int offset, int len) throws IOException {
writeString(new String(text, offset, len));
}
@Override
public void writeString(SerializableString text) throws IOException {
if (text == null) {
writeNull();
} else {
_appendValue(JsonToken.VALUE_STRING, text);
}
}
@Override
public void writeRawUTF8String(byte[] text, int offset, int length) throws IOException
{
// could add support for buffering if we really want it...
_reportUnsupportedOperation();
}
@Override
public void writeUTF8String(byte[] text, int offset, int length) throws IOException
{
// could add support for buffering if we really want it...
_reportUnsupportedOperation();
}
@Override
public void writeRaw(String text) throws IOException {
_reportUnsupportedOperation();
}
@Override
public void writeRaw(String text, int offset, int len) throws IOException {
_reportUnsupportedOperation();
}
@Override
public void writeRaw(SerializableString text) throws IOException {
_reportUnsupportedOperation();
}
@Override
public void writeRaw(char[] text, int offset, int len) throws IOException {
_reportUnsupportedOperation();
}
@Override
public void writeRaw(char c) throws IOException {
_reportUnsupportedOperation();
}
@Override
public void writeRawValue(String text) throws IOException {
_appendValue(JsonToken.VALUE_EMBEDDED_OBJECT, new RawValue(text));
}
@Override
public void writeRawValue(String text, int offset, int len) throws IOException {
if (offset > 0 || len != text.length()) {
text = text.substring(offset, offset+len);
}
_appendValue(JsonToken.VALUE_EMBEDDED_OBJECT, new RawValue(text));
}
@Override
public void writeRawValue(char[] text, int offset, int len) throws IOException {
_appendValue(JsonToken.VALUE_EMBEDDED_OBJECT, new String(text, offset, len));
}
/*
/**********************************************************
/* JsonGenerator implementation: write methods, primitive types
/**********************************************************
*/
@Override
public void writeNumber(short i) throws IOException {
_appendValue(JsonToken.VALUE_NUMBER_INT, Short.valueOf(i));
}
@Override
public void writeNumber(int i) throws IOException {
_appendValue(JsonToken.VALUE_NUMBER_INT, Integer.valueOf(i));
}
@Override
public void writeNumber(long l) throws IOException {
_appendValue(JsonToken.VALUE_NUMBER_INT, Long.valueOf(l));
}
@Override
public void writeNumber(double d) throws IOException {
_appendValue(JsonToken.VALUE_NUMBER_FLOAT, Double.valueOf(d));
}
@Override
public void writeNumber(float f) throws IOException {
_appendValue(JsonToken.VALUE_NUMBER_FLOAT, Float.valueOf(f));
}
@Override
public void writeNumber(BigDecimal dec) throws IOException {
if (dec == null) {
writeNull();
} else {
_appendValue(JsonToken.VALUE_NUMBER_FLOAT, dec);
}
}
@Override
public void writeNumber(BigInteger v) throws IOException {
if (v == null) {
writeNull();
} else {
_appendValue(JsonToken.VALUE_NUMBER_INT, v);
}
}
@Override
public void writeNumber(String encodedValue) throws IOException {
/* 03-Dec-2010, tatu: related to [JACKSON-423], should try to keep as numeric
* identity as long as possible
*/
_appendValue(JsonToken.VALUE_NUMBER_FLOAT, encodedValue);
}
@Override
public void writeBoolean(boolean state) throws IOException {
_appendValue(state ? JsonToken.VALUE_TRUE : JsonToken.VALUE_FALSE);
}
@Override
public void writeNull() throws IOException {
_appendValue(JsonToken.VALUE_NULL);
}
/*
/***********************************************************
/* JsonGenerator implementation: write methods for POJOs/trees
/***********************************************************
*/
@Override
public void writeObject(Object value) throws IOException
{
if (value == null) {
writeNull();
return;
}
Class<?> raw = value.getClass();
if (raw == byte[].class || (value instanceof RawValue)) {
_appendValue(JsonToken.VALUE_EMBEDDED_OBJECT, value);
return;
}
if (_objectCodec == null) {
/* 28-May-2014, tatu: Tricky choice here; if no codec, should we
* err out, or just embed? For now, do latter.
*/
// throw new JsonMappingException("No ObjectCodec configured for TokenBuffer, writeObject() called");
_appendValue(JsonToken.VALUE_EMBEDDED_OBJECT, value);
} else {
_objectCodec.writeValue(this, value);
}
}
@Override
public void writeTree(TreeNode node) throws IOException
{
if (node == null) {
writeNull();
return;
}
if (_objectCodec == null) {
// as with 'writeObject()', is codec optional?
_appendValue(JsonToken.VALUE_EMBEDDED_OBJECT, node);
} else {
_objectCodec.writeTree(this, node);
}
}
/*
/***********************************************************
/* JsonGenerator implementation; binary
/***********************************************************
*/
@Override
public void writeBinary(Base64Variant b64variant, byte[] data, int offset, int len) throws IOException
{
/* 31-Dec-2009, tatu: can do this using multiple alternatives; but for
* now, let's try to limit number of conversions.
* The only (?) tricky thing is that of whether to preserve variant,
* seems pointless, so let's not worry about it unless there's some
* compelling reason to.
*/
byte[] copy = new byte[len];
System.arraycopy(data, offset, copy, 0, len);
writeObject(copy);
}
/**
* Although we could support this method, it does not necessarily make
* sense: we cannot make good use of streaming because buffer must
* hold all the data. Because of this, currently this will simply
* throw {@link UnsupportedOperationException}
*/
@Override
public int writeBinary(Base64Variant b64variant, InputStream data, int dataLength) {
throw new UnsupportedOperationException();
}
/*
/***********************************************************
/* JsonGenerator implementation: native ids
/***********************************************************
*/
@Override
public boolean canWriteTypeId() {
return _hasNativeTypeIds;
}
@Override
public boolean canWriteObjectId() {
return _hasNativeObjectIds;
}
@Override
public void writeTypeId(Object id) {
_typeId = id;
_hasNativeId = true;
}
@Override
public void writeObjectId(Object id) {
_objectId = id;
_hasNativeId = true;
}
@Override // since 2.8
public void writeEmbeddedObject(Object object) throws IOException {
_appendValue(JsonToken.VALUE_EMBEDDED_OBJECT, object);
}
/*
/**********************************************************
/* JsonGenerator implementation; pass-through copy
/**********************************************************
*/
@Override
public void copyCurrentEvent(JsonParser p) throws IOException
{
if (_mayHaveNativeIds) {
_checkNativeIds(p);
}
switch (p.getCurrentToken()) {
case START_OBJECT:
writeStartObject();
break;
case END_OBJECT:
writeEndObject();
break;
case START_ARRAY:
writeStartArray();
break;
case END_ARRAY:
writeEndArray();
break;
case FIELD_NAME:
writeFieldName(p.getCurrentName());
break;
case VALUE_STRING:
if (p.hasTextCharacters()) {
writeString(p.getTextCharacters(), p.getTextOffset(), p.getTextLength());
} else {
writeString(p.getText());
}
break;
case VALUE_NUMBER_INT:
switch (p.getNumberType()) {
case INT:
writeNumber(p.getIntValue());
break;
case BIG_INTEGER:
writeNumber(p.getBigIntegerValue());
break;
default:
writeNumber(p.getLongValue());
}
break;
case VALUE_NUMBER_FLOAT:
if (_forceBigDecimal) {
// 10-Oct-2015, tatu: Ideally we would first determine whether underlying
// number is already decoded into a number (in which case might as well
// access as number); or is still retained as text (in which case we
// should further defer decoding that may not need BigDecimal):
writeNumber(p.getDecimalValue());
} else {
switch (p.getNumberType()) {
case BIG_DECIMAL:
writeNumber(p.getDecimalValue());
break;
case FLOAT:
writeNumber(p.getFloatValue());
break;
default:
writeNumber(p.getDoubleValue());
}
}
break;
case VALUE_TRUE:
writeBoolean(true);
break;
case VALUE_FALSE:
writeBoolean(false);
break;
case VALUE_NULL:
writeNull();
break;
case VALUE_EMBEDDED_OBJECT:
writeObject(p.getEmbeddedObject());
break;
default:
throw new RuntimeException("Internal error: should never end up through this code path");
}
}
@Override
public void copyCurrentStructure(JsonParser p) throws IOException
{
JsonToken t = p.getCurrentToken();
// Let's handle field-name separately first
if (t == JsonToken.FIELD_NAME) {
if (_mayHaveNativeIds) {
_checkNativeIds(p);
}
writeFieldName(p.getCurrentName());
t = p.nextToken();
// fall-through to copy the associated value
} else if (t == null) {
throw new IllegalStateException("No token available from argument `JsonParser`");
}
// We'll do minor handling here to separate structured, scalar values,
// then delegate appropriately
switch (t) {
case START_ARRAY:
if (_mayHaveNativeIds) {
_checkNativeIds(p);
}
writeStartArray();
_copyContents(p);
break;
case START_OBJECT:
if (_mayHaveNativeIds) {
_checkNativeIds(p);
}
writeStartObject();
_copyContents(p);
break;
default: // others are simple:
_copyCurrentValue(p, t);
}
}
private final void _copyContents(JsonParser p) throws IOException
{
int depth = 1;
JsonToken t;
while ((t = p.nextToken()) != null) {
switch (t) {
case FIELD_NAME:
if (_mayHaveNativeIds) {
_checkNativeIds(p);
}
writeFieldName(p.getCurrentName());
break;
case START_ARRAY:
if (_mayHaveNativeIds) {
_checkNativeIds(p);
}
writeStartArray();
++depth;
break;
case START_OBJECT:
if (_mayHaveNativeIds) {
_checkNativeIds(p);
}
writeStartObject();
++depth;
break;
case END_ARRAY:
if (--depth == 0) {
return;
}
writeEndArray();
break;
case END_OBJECT:
if (--depth == 0) {
return;
}
writeEndObject();
break;
default:
_copyCurrentValue(p, t);
}
}
}
// NOTE: Copied from earlier `copyCurrentEvent()`
private void _copyCurrentValue(JsonParser p, JsonToken t) throws IOException
{
if (_mayHaveNativeIds) {
_checkNativeIds(p);
}
switch (t) {
case VALUE_STRING:
if (p.hasTextCharacters()) {
writeString(p.getTextCharacters(), p.getTextOffset(), p.getTextLength());
} else {
writeString(p.getText());
}
break;
case VALUE_NUMBER_INT:
switch (p.getNumberType()) {
case INT:
writeNumber(p.getIntValue());
break;
case BIG_INTEGER:
writeNumber(p.getBigIntegerValue());
break;
default:
writeNumber(p.getLongValue());
}
break;
case VALUE_NUMBER_FLOAT:
if (_forceBigDecimal) {
writeNumber(p.getDecimalValue());
} else {
switch (p.getNumberType()) {
case BIG_DECIMAL:
writeNumber(p.getDecimalValue());
break;
case FLOAT:
writeNumber(p.getFloatValue());
break;
default:
writeNumber(p.getDoubleValue());
}
}
break;
case VALUE_TRUE:
writeBoolean(true);
break;
case VALUE_FALSE:
writeBoolean(false);
break;
case VALUE_NULL:
writeNull();
break;
case VALUE_EMBEDDED_OBJECT:
writeObject(p.getEmbeddedObject());
break;
default:
throw new RuntimeException("Internal error: should never end up through this code path");
}
}
private final void _checkNativeIds(JsonParser p) throws IOException
{
if ((_typeId = p.getTypeId()) != null) {
_hasNativeId = true;
}
if ((_objectId = p.getObjectId()) != null) {
_hasNativeId = true;
}
}
/*
/**********************************************************
/* Internal methods
/**********************************************************
*/
/*// Not used in / since 2.10
protected final void _append(JsonToken type)
{
Segment next;
if (_hasNativeId) {
next =_last.append(_appendAt, type, _objectId, _typeId);
} else {
next = _last.append(_appendAt, type);
}
if (next == null) {
++_appendAt;
} else {
_last = next;
_appendAt = 1; // since we added first at 0
}
}
protected final void _append(JsonToken type, Object value)
{
Segment next;
if (_hasNativeId) {
next = _last.append(_appendAt, type, value, _objectId, _typeId);
} else {
next = _last.append(_appendAt, type, value);
}
if (next == null) {
++_appendAt;
} else {
_last = next;
_appendAt = 1;
}
}
*/
/**
* Method used for appending token known to represent a "simple" scalar
* value where token is the only information
*
* @since 2.6.4
*/
protected final void _appendValue(JsonToken type)
{
_writeContext.writeValue();
Segment next;
if (_hasNativeId) {
next = _last.append(_appendAt, type, _objectId, _typeId);
} else {
next = _last.append(_appendAt, type);
}
if (next == null) {
++_appendAt;
} else {
_last = next;
_appendAt = 1; // since we added first at 0
}
}
/**
* Method used for appending token known to represent a scalar value
* where there is additional content (text, number) beyond type token
*
* @since 2.6.4
*/
protected final void _appendValue(JsonToken type, Object value)
{
_writeContext.writeValue();
Segment next;
if (_hasNativeId) {
next = _last.append(_appendAt, type, value, _objectId, _typeId);
} else {
next = _last.append(_appendAt, type, value);
}
if (next == null) {
++_appendAt;
} else {
_last = next;
_appendAt = 1;
}
}
/**
* Specialized method used for appending a field name, appending either
* {@link String} or {@link SerializableString}.
*
* @since 2.10
*/
protected final void _appendFieldName(Object value)
{
// NOTE: do NOT clear _objectId / _typeId
Segment next;
if (_hasNativeId) {
next = _last.append(_appendAt, JsonToken.FIELD_NAME, value, _objectId, _typeId);
} else {
next = _last.append(_appendAt, JsonToken.FIELD_NAME, value);
}
if (next == null) {
++_appendAt;
} else {
_last = next;
_appendAt = 1;
}
}
/**
* Specialized method used for appending a structural start Object/Array marker
*
* @since 2.10
*/
protected final void _appendStartMarker(JsonToken type)
{
Segment next;
if (_hasNativeId) {
next =_last.append(_appendAt, type, _objectId, _typeId);
} else {
next = _last.append(_appendAt, type);
}
if (next == null) {
++_appendAt;
} else {
_last = next;
_appendAt = 1; // since we added first at 0
}
}
/**
* Specialized method used for appending a structural end Object/Array marker
*
* @since 2.10
*/
protected final void _appendEndMarker(JsonToken type)
{
// NOTE: type/object id not relevant
Segment next = _last.append(_appendAt, type);
if (next == null) {
++_appendAt;
} else {
_last = next;
_appendAt = 1;
}
}
@Override
protected void _reportUnsupportedOperation() {
throw new UnsupportedOperationException("Called operation not supported for TokenBuffer");
}
/*
/**********************************************************
/* Supporting classes
/**********************************************************
*/
protected final static class Parser
extends ParserMinimalBase
{
/*
/**********************************************************
/* Configuration
/**********************************************************
*/
protected ObjectCodec _codec;
/**
* @since 2.3
*/
protected final boolean _hasNativeTypeIds;
/**
* @since 2.3
*/
protected final boolean _hasNativeObjectIds;
protected final boolean _hasNativeIds;
/*
/**********************************************************
/* Parsing state
/**********************************************************
*/
/**
* Currently active segment
*/
protected Segment _segment;
/**
* Pointer to current token within current segment
*/
protected int _segmentPtr;
/**
* Information about parser context, context in which
* the next token is to be parsed (root, array, object).
*/
protected TokenBufferReadContext _parsingContext;
protected boolean _closed;
protected transient ByteArrayBuilder _byteBuilder;
protected JsonLocation _location = null;
/*
/**********************************************************
/* Construction, init
/**********************************************************
*/
@Deprecated // since 2.9
public Parser(Segment firstSeg, ObjectCodec codec,
boolean hasNativeTypeIds, boolean hasNativeObjectIds)
{
this(firstSeg, codec, hasNativeTypeIds, hasNativeObjectIds, null);
}
public Parser(Segment firstSeg, ObjectCodec codec,
boolean hasNativeTypeIds, boolean hasNativeObjectIds,
JsonStreamContext parentContext)
{
super(0);
_segment = firstSeg;
_segmentPtr = -1; // not yet read
_codec = codec;
_parsingContext = TokenBufferReadContext.createRootContext(parentContext);
_hasNativeTypeIds = hasNativeTypeIds;
_hasNativeObjectIds = hasNativeObjectIds;
_hasNativeIds = (hasNativeTypeIds | hasNativeObjectIds);
}
public void setLocation(JsonLocation l) {
_location = l;
}
@Override
public ObjectCodec getCodec() { return _codec; }
@Override
public void setCodec(ObjectCodec c) { _codec = c; }
@Override
public Version version() {
return com.fasterxml.jackson.databind.cfg.PackageVersion.VERSION;
}
/*
/**********************************************************
/* Extended API beyond JsonParser
/**********************************************************
*/
public JsonToken peekNextToken() throws IOException
{
// closed? nothing more to peek, either
if (_closed) return null;
Segment seg = _segment;
int ptr = _segmentPtr+1;
if (ptr >= Segment.TOKENS_PER_SEGMENT) {
ptr = 0;
seg = (seg == null) ? null : seg.next();
}
return (seg == null) ? null : seg.type(ptr);
}
/*
/**********************************************************
/* Closeable implementation
/**********************************************************
*/
@Override
public void close() throws IOException {
if (!_closed) {
_closed = true;
}
}
/*
/**********************************************************
/* Public API, traversal
/**********************************************************
*/
@Override
public JsonToken nextToken() throws IOException
{
// If we are closed, nothing more to do
if (_closed || (_segment == null)) return null;
// Ok, then: any more tokens?
if (++_segmentPtr >= Segment.TOKENS_PER_SEGMENT) {
_segmentPtr = 0;
_segment = _segment.next();
if (_segment == null) {
return null;
}
}
_currToken = _segment.type(_segmentPtr);
// Field name? Need to update context
if (_currToken == JsonToken.FIELD_NAME) {
Object ob = _currentObject();
String name = (ob instanceof String) ? ((String) ob) : ob.toString();
_parsingContext.setCurrentName(name);
} else if (_currToken == JsonToken.START_OBJECT) {
_parsingContext = _parsingContext.createChildObjectContext();
} else if (_currToken == JsonToken.START_ARRAY) {
_parsingContext = _parsingContext.createChildArrayContext();
} else if (_currToken == JsonToken.END_OBJECT
|| _currToken == JsonToken.END_ARRAY) {
// Closing JSON Object/Array? Close matching context
_parsingContext = _parsingContext.parentOrCopy();
}
return _currToken;
}
@Override
public String nextFieldName() throws IOException
{
// inlined common case from nextToken()
if (_closed || (_segment == null)) {
return null;
}
int ptr = _segmentPtr+1;
if ((ptr < Segment.TOKENS_PER_SEGMENT) && (_segment.type(ptr) == JsonToken.FIELD_NAME)) {
_segmentPtr = ptr;
_currToken = JsonToken.FIELD_NAME;
Object ob = _segment.get(ptr); // inlined _currentObject();
String name = (ob instanceof String) ? ((String) ob) : ob.toString();
_parsingContext.setCurrentName(name);
return name;
}
return (nextToken() == JsonToken.FIELD_NAME) ? getCurrentName() : null;
}
@Override
public boolean isClosed() { return _closed; }
/*
/**********************************************************
/* Public API, token accessors
/**********************************************************
*/
@Override
public JsonStreamContext getParsingContext() { return _parsingContext; }
@Override
public JsonLocation getTokenLocation() { return getCurrentLocation(); }
@Override
public JsonLocation getCurrentLocation() {
return (_location == null) ? JsonLocation.NA : _location;
}
@Override
public String getCurrentName() {
// 25-Jun-2015, tatu: as per [databind#838], needs to be same as ParserBase
if (_currToken == JsonToken.START_OBJECT || _currToken == JsonToken.START_ARRAY) {
JsonStreamContext parent = _parsingContext.getParent();
return parent.getCurrentName();
}
return _parsingContext.getCurrentName();
}
@Override
public void overrideCurrentName(String name)
{
// Simple, but need to look for START_OBJECT/ARRAY's "off-by-one" thing:
JsonStreamContext ctxt = _parsingContext;
if (_currToken == JsonToken.START_OBJECT || _currToken == JsonToken.START_ARRAY) {
ctxt = ctxt.getParent();
}
if (ctxt instanceof TokenBufferReadContext) {
try {
((TokenBufferReadContext) ctxt).setCurrentName(name);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
/*
/**********************************************************
/* Public API, access to token information, text
/**********************************************************
*/
@Override
public String getText()
{
// common cases first:
if (_currToken == JsonToken.VALUE_STRING
|| _currToken == JsonToken.FIELD_NAME) {
Object ob = _currentObject();
if (ob instanceof String) {
return (String) ob;
}
return ClassUtil.nullOrToString(ob);
}
if (_currToken == null) {
return null;
}
switch (_currToken) {
case VALUE_NUMBER_INT:
case VALUE_NUMBER_FLOAT:
return ClassUtil.nullOrToString(_currentObject());
default:
return _currToken.asString();
}
}
@Override
public char[] getTextCharacters() {
String str = getText();
return (str == null) ? null : str.toCharArray();
}
@Override
public int getTextLength() {
String str = getText();
return (str == null) ? 0 : str.length();
}
@Override
public int getTextOffset() { return 0; }
@Override
public boolean hasTextCharacters() {
// We never have raw buffer available, so:
return false;
}
/*
/**********************************************************
/* Public API, access to token information, numeric
/**********************************************************
*/
@Override
public boolean isNaN() {
// can only occur for floating-point numbers
if (_currToken == JsonToken.VALUE_NUMBER_FLOAT) {
Object value = _currentObject();
if (value instanceof Double) {
Double v = (Double) value;
return v.isNaN() || v.isInfinite();
}
if (value instanceof Float) {
Float v = (Float) value;
return v.isNaN() || v.isInfinite();
}
}
return false;
}
@Override
public BigInteger getBigIntegerValue() throws IOException
{
Number n = getNumberValue();
if (n instanceof BigInteger) {
return (BigInteger) n;
}
if (getNumberType() == NumberType.BIG_DECIMAL) {
return ((BigDecimal) n).toBigInteger();
}
// int/long is simple, but let's also just truncate float/double:
return BigInteger.valueOf(n.longValue());
}
@Override
public BigDecimal getDecimalValue() throws IOException
{
Number n = getNumberValue();
if (n instanceof BigDecimal) {
return (BigDecimal) n;
}
switch (getNumberType()) {
case INT:
case LONG:
return BigDecimal.valueOf(n.longValue());
case BIG_INTEGER:
return new BigDecimal((BigInteger) n);
default:
}
// float or double
return BigDecimal.valueOf(n.doubleValue());
}
@Override
public double getDoubleValue() throws IOException {
return getNumberValue().doubleValue();
}
@Override
public float getFloatValue() throws IOException {
return getNumberValue().floatValue();
}
@Override
public int getIntValue() throws IOException
{
Number n = (_currToken == JsonToken.VALUE_NUMBER_INT) ?
((Number) _currentObject()) : getNumberValue();
if ((n instanceof Integer) || _smallerThanInt(n)) {
return n.intValue();
}
return _convertNumberToInt(n);
}
@Override
public long getLongValue() throws IOException {
Number n = (_currToken == JsonToken.VALUE_NUMBER_INT) ?
((Number) _currentObject()) : getNumberValue();
if ((n instanceof Long) || _smallerThanLong(n)) {
return n.longValue();
}
return _convertNumberToLong(n);
}
@Override
public NumberType getNumberType() throws IOException
{
Number n = getNumberValue();
if (n instanceof Integer) return NumberType.INT;
if (n instanceof Long) return NumberType.LONG;
if (n instanceof Double) return NumberType.DOUBLE;
if (n instanceof BigDecimal) return NumberType.BIG_DECIMAL;
if (n instanceof BigInteger) return NumberType.BIG_INTEGER;
if (n instanceof Float) return NumberType.FLOAT;
if (n instanceof Short) return NumberType.INT; // should be SHORT
return null;
}
@Override
public final Number getNumberValue() throws IOException {
_checkIsNumber();
Object value = _currentObject();
if (value instanceof Number) {
return (Number) value;
}
// Difficult to really support numbers-as-Strings; but let's try.
// NOTE: no access to DeserializationConfig, unfortunately, so cannot
// try to determine Double/BigDecimal preference...
if (value instanceof String) {
String str = (String) value;
if (str.indexOf('.') >= 0) {
return Double.parseDouble(str);
}
return Long.parseLong(str);
}
if (value == null) {
return null;
}
throw new IllegalStateException("Internal error: entry should be a Number, but is of type "
+value.getClass().getName());
}
private final boolean _smallerThanInt(Number n) {
return (n instanceof Short) || (n instanceof Byte);
}
private final boolean _smallerThanLong(Number n) {
return (n instanceof Integer) || (n instanceof Short) || (n instanceof Byte);
}
// 02-Jan-2017, tatu: Modified from method(s) in `ParserBase`
protected int _convertNumberToInt(Number n) throws IOException
{
if (n instanceof Long) {
long l = n.longValue();
int result = (int) l;
if (((long) result) != l) {
reportOverflowInt();
}
return result;
}
if (n instanceof BigInteger) {
BigInteger big = (BigInteger) n;
if (BI_MIN_INT.compareTo(big) > 0
|| BI_MAX_INT.compareTo(big) < 0) {
reportOverflowInt();
}
} else if ((n instanceof Double) || (n instanceof Float)) {
double d = n.doubleValue();
// Need to check boundaries
if (d < MIN_INT_D || d > MAX_INT_D) {
reportOverflowInt();
}
return (int) d;
} else if (n instanceof BigDecimal) {
BigDecimal big = (BigDecimal) n;
if (BD_MIN_INT.compareTo(big) > 0
|| BD_MAX_INT.compareTo(big) < 0) {
reportOverflowInt();
}
} else {
_throwInternal();
}
return n.intValue();
}
protected long _convertNumberToLong(Number n) throws IOException
{
if (n instanceof BigInteger) {
BigInteger big = (BigInteger) n;
if (BI_MIN_LONG.compareTo(big) > 0
|| BI_MAX_LONG.compareTo(big) < 0) {
reportOverflowLong();
}
} else if ((n instanceof Double) || (n instanceof Float)) {
double d = n.doubleValue();
// Need to check boundaries
if (d < MIN_LONG_D || d > MAX_LONG_D) {
reportOverflowLong();
}
return (long) d;
} else if (n instanceof BigDecimal) {
BigDecimal big = (BigDecimal) n;
if (BD_MIN_LONG.compareTo(big) > 0
|| BD_MAX_LONG.compareTo(big) < 0) {
reportOverflowLong();
}
} else {
_throwInternal();
}
return n.longValue();
}
/*
/**********************************************************
/* Public API, access to token information, other
/**********************************************************
*/
@Override
public Object getEmbeddedObject()
{
if (_currToken == JsonToken.VALUE_EMBEDDED_OBJECT) {
return _currentObject();
}
return null;
}
@Override
@SuppressWarnings("resource")
public byte[] getBinaryValue(Base64Variant b64variant) throws IOException, JsonParseException
{
// First: maybe we some special types?
if (_currToken == JsonToken.VALUE_EMBEDDED_OBJECT) {
// Embedded byte array would work nicely...
Object ob = _currentObject();
if (ob instanceof byte[]) {
return (byte[]) ob;
}
// fall through to error case
}
if (_currToken != JsonToken.VALUE_STRING) {
throw _constructError("Current token ("+_currToken+") not VALUE_STRING (or VALUE_EMBEDDED_OBJECT with byte[]), cannot access as binary");
}
final String str = getText();
if (str == null) {
return null;
}
ByteArrayBuilder builder = _byteBuilder;
if (builder == null) {
_byteBuilder = builder = new ByteArrayBuilder(100);
} else {
_byteBuilder.reset();
}
_decodeBase64(str, builder, b64variant);
return builder.toByteArray();
}
@Override
public int readBinaryValue(Base64Variant b64variant, OutputStream out) throws IOException
{
byte[] data = getBinaryValue(b64variant);
if (data != null) {
out.write(data, 0, data.length);
return data.length;
}
return 0;
}
/*
/**********************************************************
/* Public API, native ids
/**********************************************************
*/
@Override
public boolean canReadObjectId() {
return _hasNativeObjectIds;
}
@Override
public boolean canReadTypeId() {
return _hasNativeTypeIds;
}
@Override
public Object getTypeId() {
return _segment.findTypeId(_segmentPtr);
}
@Override
public Object getObjectId() {
return _segment.findObjectId(_segmentPtr);
}
/*
/**********************************************************
/* Internal methods
/**********************************************************
*/
protected final Object _currentObject() {
return _segment.get(_segmentPtr);
}
protected final void _checkIsNumber() throws JsonParseException
{
if (_currToken == null || !_currToken.isNumeric()) {
throw _constructError("Current token ("+_currToken+") not numeric, cannot use numeric value accessors");
}
}
@Override
protected void _handleEOF() throws JsonParseException {
_throwInternal();
}
}
/**
* Individual segment of TokenBuffer that can store up to 16 tokens
* (limited by 4 bits per token type marker requirement).
* Current implementation uses fixed length array; could alternatively
* use 16 distinct fields and switch statement (slightly more efficient
* storage, slightly slower access)
*/
protected final static class Segment
{
public final static int TOKENS_PER_SEGMENT = 16;
/**
* Static array used for fast conversion between token markers and
* matching {@link JsonToken} instances
*/
private final static JsonToken[] TOKEN_TYPES_BY_INDEX;
static {
// ... here we know that there are <= 15 values in JsonToken enum
TOKEN_TYPES_BY_INDEX = new JsonToken[16];
JsonToken[] t = JsonToken.values();
// and reserve entry 0 for "not available"
System.arraycopy(t, 1, TOKEN_TYPES_BY_INDEX, 1, Math.min(15, t.length - 1));
}
// // // Linking
protected Segment _next;
// // // State
/**
* Bit field used to store types of buffered tokens; 4 bits per token.
* Value 0 is reserved for "not in use"
*/
protected long _tokenTypes;
// Actual tokens
protected final Object[] _tokens = new Object[TOKENS_PER_SEGMENT];
/**
* Lazily constructed Map for storing native type and object ids, if any
*/
protected TreeMap<Integer,Object> _nativeIds;
public Segment() { }
// // // Accessors
public JsonToken type(int index)
{
long l = _tokenTypes;
if (index > 0) {
l >>= (index << 2);
}
int ix = ((int) l) & 0xF;
return TOKEN_TYPES_BY_INDEX[ix];
}
public int rawType(int index)
{
long l = _tokenTypes;
if (index > 0) {
l >>= (index << 2);
}
int ix = ((int) l) & 0xF;
return ix;
}
public Object get(int index) {
return _tokens[index];
}
public Segment next() { return _next; }
/**
* Accessor for checking whether this segment may have native
* type or object ids.
*/
public boolean hasIds() {
return _nativeIds != null;
}
// // // Mutators
public Segment append(int index, JsonToken tokenType)
{
if (index < TOKENS_PER_SEGMENT) {
set(index, tokenType);
return null;
}
_next = new Segment();
_next.set(0, tokenType);
return _next;
}
public Segment append(int index, JsonToken tokenType,
Object objectId, Object typeId)
{
if (index < TOKENS_PER_SEGMENT) {
set(index, tokenType, objectId, typeId);
return null;
}
_next = new Segment();
_next.set(0, tokenType, objectId, typeId);
return _next;
}
public Segment append(int index, JsonToken tokenType, Object value)
{
if (index < TOKENS_PER_SEGMENT) {
set(index, tokenType, value);
return null;
}
_next = new Segment();
_next.set(0, tokenType, value);
return _next;
}
public Segment append(int index, JsonToken tokenType, Object value,
Object objectId, Object typeId)
{
if (index < TOKENS_PER_SEGMENT) {
set(index, tokenType, value, objectId, typeId);
return null;
}
_next = new Segment();
_next.set(0, tokenType, value, objectId, typeId);
return _next;
}
/*
public Segment appendRaw(int index, int rawTokenType, Object value)
{
if (index < TOKENS_PER_SEGMENT) {
set(index, rawTokenType, value);
return null;
}
_next = new Segment();
_next.set(0, rawTokenType, value);
return _next;
}
public Segment appendRaw(int index, int rawTokenType, Object value,
Object objectId, Object typeId)
{
if (index < TOKENS_PER_SEGMENT) {
set(index, rawTokenType, value, objectId, typeId);
return null;
}
_next = new Segment();
_next.set(0, rawTokenType, value, objectId, typeId);
return _next;
}
private void set(int index, int rawTokenType, Object value, Object objectId, Object typeId)
{
_tokens[index] = value;
long typeCode = (long) rawTokenType;
if (index > 0) {
typeCode <<= (index << 2);
}
_tokenTypes |= typeCode;
assignNativeIds(index, objectId, typeId);
}
private void set(int index, int rawTokenType, Object value)
{
_tokens[index] = value;
long typeCode = (long) rawTokenType;
if (index > 0) {
typeCode <<= (index << 2);
}
_tokenTypes |= typeCode;
}
*/
private void set(int index, JsonToken tokenType)
{
/* Assumption here is that there are no overwrites, just appends;
* and so no masking is needed (nor explicit setting of null)
*/
long typeCode = tokenType.ordinal();
if (index > 0) {
typeCode <<= (index << 2);
}
_tokenTypes |= typeCode;
}
private void set(int index, JsonToken tokenType,
Object objectId, Object typeId)
{
long typeCode = tokenType.ordinal();
if (index > 0) {
typeCode <<= (index << 2);
}
_tokenTypes |= typeCode;
assignNativeIds(index, objectId, typeId);
}
private void set(int index, JsonToken tokenType, Object value)
{
_tokens[index] = value;
long typeCode = tokenType.ordinal();
if (index > 0) {
typeCode <<= (index << 2);
}
_tokenTypes |= typeCode;
}
private void set(int index, JsonToken tokenType, Object value,
Object objectId, Object typeId)
{
_tokens[index] = value;
long typeCode = tokenType.ordinal();
if (index > 0) {
typeCode <<= (index << 2);
}
_tokenTypes |= typeCode;
assignNativeIds(index, objectId, typeId);
}
private final void assignNativeIds(int index, Object objectId, Object typeId)
{
if (_nativeIds == null) {
_nativeIds = new TreeMap<Integer,Object>();
}
if (objectId != null) {
_nativeIds.put(_objectIdIndex(index), objectId);
}
if (typeId != null) {
_nativeIds.put(_typeIdIndex(index), typeId);
}
}
/**
* @since 2.3
*/
private Object findObjectId(int index) {
return (_nativeIds == null) ? null : _nativeIds.get(_objectIdIndex(index));
}
/**
* @since 2.3
*/
private Object findTypeId(int index) {
return (_nativeIds == null) ? null : _nativeIds.get(_typeIdIndex(index));
}
private final int _typeIdIndex(int i) { return i+i; }
private final int _objectIdIndex(int i) { return i+i+1; }
}
}
| Fix to TokenBuffer refactoring
| src/main/java/com/fasterxml/jackson/databind/util/TokenBuffer.java | Fix to TokenBuffer refactoring |
|
Java | apache-2.0 | 86051adea236ded48156d18217cddc7c3637ca88 | 0 | PingID-Samples/pingid-api-playground,pingidentity/pingid-api-playground | package com.pingidentity.developer.pingid;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;
import org.apache.commons.io.IOUtils;
import org.jose4j.base64url.Base64;
import org.jose4j.jws.AlgorithmIdentifiers;
import org.jose4j.jws.JsonWebSignature;
import org.jose4j.keys.HmacKey;
import org.jose4j.lang.JoseException;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import com.pingidentity.developer.pingid.User;
public class Operation {
private String name;
private String endpoint;
private String requestToken;
private String responseToken;
private int responseCode;
private Boolean wasSuccessful;
private long errorId;
private String errorMsg;
private String uniqueMsgId;
private String idpUrl = "https://idpxnyl3m.pingidentity.com/pingid";
private String orgAlias;
private String token;
private String useBase64Key;
private String lastActivationCode;
private String lastSessionId;
private Map<String, Object> values;
private String clientData;
private User user;
private final String apiVersion = "4.6";
public Operation() {
}
public Operation(String orgAlias, String token, String useBase64Key) {
this.orgAlias = orgAlias;
this.token = token;
this.useBase64Key = useBase64Key;
this.values = new HashMap<String, Object>();
}
public String getName() { return name; }
public String getEndpoint() { return endpoint; }
public String getRequestToken() { return requestToken; }
public String getResponseToken() { return responseToken; }
public int getResponseCode() { return responseCode; }
public Boolean getWasSuccessful() { return wasSuccessful; }
public String getLastActivationCode() { return this.lastActivationCode; }
public String getLastSessionId() { return this.lastSessionId; }
public long getErrorId() { return errorId; }
public String getErrorMsg() { return errorMsg; }
public String getUniqueMsgId() { return uniqueMsgId; }
public Map<String, Object> getReturnValues() { return values; }
public User getUser() { return user; }
public void setTargetUser(User user) { this.user = user; }
public void setTargetUser(String username) { this.user = new User(username); }
public void setLastActivationCode(String activationCode) { this.lastActivationCode = activationCode; }
public void setLastSessionId(String sessionId) { this.lastSessionId = sessionId; }
// public methods
@SuppressWarnings("unchecked")
public void AddUser(Boolean activateUser) {
this.name = "AddUser";
this.endpoint = idpUrl + "/rest/4/adduser/do";
JSONObject reqBody = new JSONObject();
reqBody.put("activateUser", activateUser);
reqBody.put("email", this.user.getEmail());
reqBody.put("fName", this.user.getFirstName());
reqBody.put("lname", this.user.getLastName());
reqBody.put("username", this.user.getUserName());
reqBody.put("role", this.user.getRole().getValue());
reqBody.put("clientData", this.clientData);
this.requestToken = buildRequestToken(reqBody);
sendRequest();
JSONObject response = parseResponse();
values.clear();
if (activateUser) {
this.lastActivationCode = (String)response.get("activationCode");
}
}
@SuppressWarnings("unchecked")
public void EditUser(Boolean activateUser) {
this.name = "EditUser";
this.endpoint = idpUrl + "/rest/4/edituser/do";
JSONObject reqBody = new JSONObject();
reqBody.put("activateUser", activateUser);
reqBody.put("email", this.user.getEmail());
reqBody.put("fName", this.user.getFirstName());
reqBody.put("lName", this.user.getLastName());
reqBody.put("userName", this.user.getUserName());
reqBody.put("role", this.user.getRole().getValue());
reqBody.put("clientData", this.clientData);
this.requestToken = buildRequestToken(reqBody);
sendRequest();
JSONObject response = parseResponse();
values.clear();
if (activateUser) {
this.lastActivationCode = (String)response.get("activationCode");
}
}
@SuppressWarnings("unchecked")
public void GetUserDetails() {
this.name = "GetUserDetails";
this.endpoint = idpUrl + "/rest/4/getuserdetails/do";
JSONObject reqBody = new JSONObject();
reqBody.put("getSameDeviceUsers", false);
reqBody.put("userName", this.user.getUserName());
reqBody.put("clientData", this.clientData);
this.requestToken = buildRequestToken(reqBody);
sendRequest();
values.clear();
JSONObject response = parseResponse();
JSONObject userDetails = (JSONObject)response.get("userDetails");
this.user = new User(userDetails);
DeviceDetails deviceDetails = new DeviceDetails((JSONObject)userDetails.get("deviceDetails"));
this.user.setDeviceDetails(deviceDetails);
}
@SuppressWarnings("unchecked")
public void DeleteUser() {
this.name = "DeleteUser";
this.endpoint = idpUrl + "/rest/4/deleteuser/do";
JSONObject reqBody = new JSONObject();
reqBody.put("userName", this.user.getUserName());
reqBody.put("clientData", this.clientData);
this.requestToken = buildRequestToken(reqBody);
sendRequest();
parseResponse();
values.clear();
}
@SuppressWarnings("unchecked")
public void SuspendUser() {
this.name = "SuspendUser";
this.endpoint = idpUrl + "/rest/4/suspenduser/do";
JSONObject reqBody = new JSONObject();
reqBody.put("userName", this.user.getUserName());
reqBody.put("clientData", this.clientData);
this.requestToken = buildRequestToken(reqBody);
sendRequest();
parseResponse();
values.clear();
}
@SuppressWarnings("unchecked")
public void ActivateUser() {
this.name = "ActivateUser";
this.endpoint = idpUrl + "/rest/4/activateuser/do";
JSONObject reqBody = new JSONObject();
reqBody.put("userName", this.user.getUserName());
reqBody.put("clientData", this.clientData);
this.requestToken = buildRequestToken(reqBody);
sendRequest();
parseResponse();
values.clear();
}
@SuppressWarnings("unchecked")
public void ToggleUserBypass(long until) {
this.name = "ToggleUserBypass";
this.endpoint = idpUrl + "/rest/4/userbypass/do";
JSONObject reqBody = new JSONObject();
reqBody.put("userName", this.user.getUserName());
reqBody.put("bypassUntil", (until != 0) ? until : null);
reqBody.put("clientData", this.clientData);
this.requestToken = buildRequestToken(reqBody);
sendRequest();
parseResponse();
values.clear();
}
@SuppressWarnings("unchecked")
public void UnpairDevice() {
this.name = "UnpairDevice";
this.endpoint = idpUrl + "/rest/4/unpairdevice/do";
JSONObject reqBody = new JSONObject();
reqBody.put("userName", this.user.getUserName());
reqBody.put("clientData", this.clientData);
this.requestToken = buildRequestToken(reqBody);
sendRequest();
parseResponse();
values.clear();
}
@SuppressWarnings("unchecked")
public void GetPairingStatus(String activationCode) {
this.name = "GetPairingStatus";
this.endpoint = idpUrl + "/rest/4/pairingstatus/do";
JSONObject reqBody = new JSONObject();
reqBody.put("activationCode", activationCode);
reqBody.put("clientData", this.clientData);
this.requestToken = buildRequestToken(reqBody);
sendRequest();
JSONObject response = parseResponse();
values.clear();
values.put("pairingStatus", (PairingStatus)PairingStatus.valueOf((String)response.get("pairingStatus")));
}
@SuppressWarnings("unchecked")
public void PairYubiKey(String otp) {
this.name = "PairYubiKey";
this.endpoint = idpUrl + "/rest/4/pairyubikey/do";
JSONObject reqBody = new JSONObject();
reqBody.put("otp", otp);
reqBody.put("username", this.user.getUserName());
reqBody.put("clientData", this.clientData);
this.requestToken = buildRequestToken(reqBody);
sendRequest();
parseResponse();
values.clear();
}
@SuppressWarnings("unchecked")
public void StartOfflinePairing(OfflinePairingMethod pairingMethod) {
this.name = "StartOfflinePairing";
this.endpoint = idpUrl + "/rest/4/startofflinepairing/do";
JSONObject reqBody = new JSONObject();
if (pairingMethod == OfflinePairingMethod.SMS) {
reqBody.put("type", OfflinePairingMethod.SMS.getValue());
reqBody.put("pairingData", this.user.getPhoneNumber());
} else if (pairingMethod == OfflinePairingMethod.VOICE) {
reqBody.put("type", OfflinePairingMethod.VOICE.getValue());
reqBody.put("pairingData", this.user.getPhoneNumber());
} else if (pairingMethod == OfflinePairingMethod.EMAIL) {
reqBody.put("type", OfflinePairingMethod.EMAIL.getValue());
reqBody.put("pairingData", this.user.getEmail());
}
reqBody.put("username", this.user.getUserName());
reqBody.put("clientData", this.clientData);
this.requestToken = buildRequestToken(reqBody);
sendRequest();
JSONObject response = parseResponse();
values.clear();
this.lastSessionId = (String)response.get("sessionId");
}
@SuppressWarnings("unchecked")
public void FinalizeOfflinePairing(String sessionId, String otp) {
this.name = "FinalizeOfflinePairing";
this.endpoint = idpUrl + "/rest/4/finalizeofflinepairing/do";
JSONObject reqBody = new JSONObject();
reqBody.put("otp", otp);
reqBody.put("sessionId", sessionId);
reqBody.put("clientData", this.clientData);
this.requestToken = buildRequestToken(reqBody);
sendRequest();
parseResponse();
values.clear();
}
@SuppressWarnings("unchecked")
public void GetActivationCode() {
this.name = "GetActivationCode";
this.endpoint = idpUrl + "/rest/4/getactivationcode/do";
JSONObject reqBody = new JSONObject();
reqBody.put("userName", this.user.getUserName());
reqBody.put("clientData", this.clientData);
this.requestToken = buildRequestToken(reqBody);
sendRequest();
JSONObject response = parseResponse();
values.clear();
this.lastActivationCode = (String)response.get("activationCode");
}
@SuppressWarnings("unchecked")
public void AuthenticateOnline(Application application, String authType) {
this.name = "AuthenticateOnline";
this.endpoint = idpUrl + "/rest/4/authonline/do";
JSONObject reqBody = new JSONObject();
reqBody.put("authType", authType);
reqBody.put("spAlias", application.getSpAlias());
reqBody.put("userName", this.user.getUserName());
reqBody.put("clientData", this.clientData);
JSONObject formParameters = new JSONObject();
formParameters.put("sp_name", application.getName());
if (application.getLogoUrl() != null || !application.getLogoUrl().isEmpty()) {
formParameters.put("sp_logo", application.getLogoUrl());
}
reqBody.put("formParameters", formParameters);
this.requestToken = buildRequestToken(reqBody);
sendRequest();
JSONObject response = parseResponse();
if (this.wasSuccessful) {
values.clear();
this.lastSessionId = (String)response.get("sessionId");
}
}
@SuppressWarnings("unchecked")
public void AuthenticateOffline(String sessionId, String otp) {
this.name = "AuthenticateOffline";
this.endpoint = idpUrl + "/rest/4/authoffline/do";
JSONObject reqBody = new JSONObject();
reqBody.put("spAlias", "web");
reqBody.put("otp", otp);
reqBody.put("userName", this.user.getUserName());
reqBody.put("sessionId", sessionId);
reqBody.put("clientData", this.clientData);
this.requestToken = buildRequestToken(reqBody);
sendRequest();
parseResponse();
values.clear();
}
//private methods
@SuppressWarnings("unchecked")
private String buildRequestToken(JSONObject requestBody) {
JSONObject requestHeader = buildRequestHeader();
JSONObject payload = new JSONObject();
payload.put("reqHeader", requestHeader);
payload.put("reqBody", requestBody);
JsonWebSignature jws = new JsonWebSignature();
jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);
jws.setHeader("org_alias", this.orgAlias);
jws.setHeader("token", this.token);
jws.setPayload(payload.toJSONString());
// Set the verification key
HmacKey key = new HmacKey(Base64.decode(this.useBase64Key));
jws.setKey(key);
String jwsCompactSerialization = null;
try {
jwsCompactSerialization = jws.getCompactSerialization();
} catch (JoseException e) {
e.printStackTrace();
}
this.requestToken = jwsCompactSerialization;
return jwsCompactSerialization;
}
@SuppressWarnings("unchecked")
private JSONObject buildRequestHeader() {
JSONObject reqHeader = new JSONObject();
reqHeader.put("locale", "en");
reqHeader.put("orgAlias", this.orgAlias);
reqHeader.put("secretKey", this.token);
reqHeader.put("timestamp", getCurrentTimeStamp());
reqHeader.put("version", this.apiVersion);
return reqHeader;
}
static String getCurrentTimeStamp() {
Date currentDate = new Date();
SimpleDateFormat PingIDDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
PingIDDateFormat.setTimeZone(TimeZone.getTimeZone("America/Denver"));
return PingIDDateFormat.format(currentDate);
}
private void sendRequest() {
try {
URL restUrl = new URL(this.getEndpoint());
HttpURLConnection urlConnection = (HttpURLConnection)restUrl.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.addRequestProperty("Content-Type", "application/json");
urlConnection.addRequestProperty("Accept", "*/*");
urlConnection.setDoOutput(true);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8");
outputStreamWriter.write(this.getRequestToken());
outputStreamWriter.flush();
outputStreamWriter.close();
int responseCode = urlConnection.getResponseCode();
this.responseCode = responseCode;
if (responseCode == 200) {
String encoding = urlConnection.getContentEncoding();
InputStream is = urlConnection.getInputStream();
String stringJWS = IOUtils.toString(is, encoding);
this.responseToken = stringJWS;
this.wasSuccessful = true;
urlConnection.disconnect();
} else {
String encoding = urlConnection.getContentEncoding();
InputStream is = urlConnection.getErrorStream();
String stringJWS = IOUtils.toString(is, encoding);
this.responseToken = stringJWS;
this.wasSuccessful = false;
urlConnection.disconnect();
}
} catch (Exception ex) {
this.responseCode = 500;
this.wasSuccessful = false;
}
}
private JSONObject parseResponse() {
JSONParser parser = new JSONParser();
JSONObject responsePayloadJSON = null;
try {
JsonWebSignature responseJWS = new JsonWebSignature();
responseJWS.setCompactSerialization(this.responseToken);
HmacKey key = new HmacKey(Base64.decode(this.useBase64Key));
responseJWS.setKey(key);
responsePayloadJSON = (JSONObject)parser.parse(responseJWS.getPayload());
// workaround for PingID API 4.5 beta
if (responsePayloadJSON.containsKey("responseBody")) {
responsePayloadJSON = (JSONObject)responsePayloadJSON.get("responseBody");
}
} catch (Exception e) {
e.printStackTrace();
}
if (responsePayloadJSON != null) {
this.errorId = (long)responsePayloadJSON.get("errorId");
this.errorMsg = (String)responsePayloadJSON.get("errorMsg");
this.uniqueMsgId = (String)responsePayloadJSON.get("uniqueMsgId");
this.clientData = (String)responsePayloadJSON.get("clientData");
} else {
this.errorId = 501;
this.errorMsg = "Could not parse JWS";
this.uniqueMsgId = "";
this.clientData = "";
this.wasSuccessful = false;
}
return responsePayloadJSON;
}
}
| src/main/java/com/pingidentity/developer/pingid/Operation.java | package com.pingidentity.developer.pingid;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;
import org.apache.commons.io.IOUtils;
import org.jose4j.base64url.Base64;
import org.jose4j.jws.AlgorithmIdentifiers;
import org.jose4j.jws.JsonWebSignature;
import org.jose4j.keys.HmacKey;
import org.jose4j.lang.JoseException;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import com.pingidentity.developer.pingid.User;
public class Operation {
private String name;
private String endpoint;
private String requestToken;
private String responseToken;
private int responseCode;
private Boolean wasSuccessful;
private long errorId;
private String errorMsg;
private String uniqueMsgId;
private String orgAlias;
private String token;
private String useBase64Key;
private String lastActivationCode;
private String lastSessionId;
private Map<String, Object> values;
private String clientData;
private User user;
private final String apiVersion = "4.6";
public Operation() {
}
public Operation(String orgAlias, String token, String useBase64Key) {
this.orgAlias = orgAlias;
this.token = token;
this.useBase64Key = useBase64Key;
this.values = new HashMap<String, Object>();
}
public String getName() { return name; }
public String getEndpoint() { return endpoint; }
public String getRequestToken() { return requestToken; }
public String getResponseToken() { return responseToken; }
public int getResponseCode() { return responseCode; }
public Boolean getWasSuccessful() { return wasSuccessful; }
public String getLastActivationCode() { return this.lastActivationCode; }
public String getLastSessionId() { return this.lastSessionId; }
public long getErrorId() { return errorId; }
public String getErrorMsg() { return errorMsg; }
public String getUniqueMsgId() { return uniqueMsgId; }
public Map<String, Object> getReturnValues() { return values; }
public User getUser() { return user; }
public void setTargetUser(User user) { this.user = user; }
public void setTargetUser(String username) { this.user = new User(username); }
public void setLastActivationCode(String activationCode) { this.lastActivationCode = activationCode; }
public void setLastSessionId(String sessionId) { this.lastSessionId = sessionId; }
// public methods
@SuppressWarnings("unchecked")
public void AddUser(Boolean activateUser) {
this.name = "AddUser";
this.endpoint = "https://idpxnyl3m.pingidentity.com/pingid/rest/4/adduser/do";
JSONObject reqBody = new JSONObject();
reqBody.put("activateUser", activateUser);
reqBody.put("email", this.user.getEmail());
reqBody.put("fName", this.user.getFirstName());
reqBody.put("lname", this.user.getLastName());
reqBody.put("username", this.user.getUserName());
reqBody.put("role", this.user.getRole().getValue());
reqBody.put("clientData", this.clientData);
this.requestToken = buildRequestToken(reqBody);
sendRequest();
JSONObject response = parseResponse();
values.clear();
if (activateUser) {
this.lastActivationCode = (String)response.get("activationCode");
}
}
@SuppressWarnings("unchecked")
public void EditUser(Boolean activateUser) {
this.name = "EditUser";
this.endpoint = "https://idpxnyl3m.pingidentity.com/pingid/rest/4/edituser/do";
JSONObject reqBody = new JSONObject();
reqBody.put("activateUser", activateUser);
reqBody.put("email", this.user.getEmail());
reqBody.put("fName", this.user.getFirstName());
reqBody.put("lName", this.user.getLastName());
reqBody.put("userName", this.user.getUserName());
reqBody.put("role", this.user.getRole().getValue());
reqBody.put("clientData", this.clientData);
this.requestToken = buildRequestToken(reqBody);
sendRequest();
JSONObject response = parseResponse();
values.clear();
if (activateUser) {
this.lastActivationCode = (String)response.get("activationCode");
}
}
@SuppressWarnings("unchecked")
public void GetUserDetails() {
this.name = "GetUserDetails";
this.endpoint = "https://idpxnyl3m.pingidentity.com/pingid/rest/4/getuserdetails/do";
JSONObject reqBody = new JSONObject();
reqBody.put("getSameDeviceUsers", false);
reqBody.put("userName", this.user.getUserName());
reqBody.put("clientData", this.clientData);
this.requestToken = buildRequestToken(reqBody);
sendRequest();
values.clear();
JSONObject response = parseResponse();
JSONObject userDetails = (JSONObject)response.get("userDetails");
this.user = new User(userDetails);
DeviceDetails deviceDetails = new DeviceDetails((JSONObject)userDetails.get("deviceDetails"));
this.user.setDeviceDetails(deviceDetails);
}
@SuppressWarnings("unchecked")
public void DeleteUser() {
this.name = "DeleteUser";
this.endpoint = "https://idpxnyl3m.pingidentity.com/pingid/rest/4/deleteuser/do";
JSONObject reqBody = new JSONObject();
reqBody.put("userName", this.user.getUserName());
reqBody.put("clientData", this.clientData);
this.requestToken = buildRequestToken(reqBody);
sendRequest();
parseResponse();
values.clear();
}
@SuppressWarnings("unchecked")
public void SuspendUser() {
this.name = "SuspendUser";
this.endpoint = "https://idpxnyl3m.pingidentity.com/pingid/rest/4/suspenduser/do";
JSONObject reqBody = new JSONObject();
reqBody.put("userName", this.user.getUserName());
reqBody.put("clientData", this.clientData);
this.requestToken = buildRequestToken(reqBody);
sendRequest();
parseResponse();
values.clear();
}
@SuppressWarnings("unchecked")
public void ActivateUser() {
this.name = "ActivateUser";
this.endpoint = "https://idpxnyl3m.pingidentity.com/pingid/rest/4/activateuser/do";
JSONObject reqBody = new JSONObject();
reqBody.put("userName", this.user.getUserName());
reqBody.put("clientData", this.clientData);
this.requestToken = buildRequestToken(reqBody);
sendRequest();
parseResponse();
values.clear();
}
@SuppressWarnings("unchecked")
public void ToggleUserBypass(long until) {
this.name = "ToggleUserBypass";
this.endpoint = "https://idpxnyl3m.pingidentity.com/pingid/rest/4/userbypass/do";
JSONObject reqBody = new JSONObject();
reqBody.put("userName", this.user.getUserName());
reqBody.put("bypassUntil", (until != 0) ? until : null);
reqBody.put("clientData", this.clientData);
this.requestToken = buildRequestToken(reqBody);
sendRequest();
parseResponse();
values.clear();
}
@SuppressWarnings("unchecked")
public void UnpairDevice() {
this.name = "UnpairDevice";
this.endpoint = "https://idpxnyl3m.pingidentity.com/pingid/rest/4/unpairdevice/do";
JSONObject reqBody = new JSONObject();
reqBody.put("userName", this.user.getUserName());
reqBody.put("clientData", this.clientData);
this.requestToken = buildRequestToken(reqBody);
sendRequest();
parseResponse();
values.clear();
}
@SuppressWarnings("unchecked")
public void GetPairingStatus(String activationCode) {
this.name = "GetPairingStatus";
this.endpoint = "https://idpxnyl3m.pingidentity.com/pingid/rest/4/pairingstatus/do";
JSONObject reqBody = new JSONObject();
reqBody.put("activationCode", activationCode);
reqBody.put("clientData", this.clientData);
this.requestToken = buildRequestToken(reqBody);
sendRequest();
JSONObject response = parseResponse();
values.clear();
values.put("pairingStatus", (PairingStatus)PairingStatus.valueOf((String)response.get("pairingStatus")));
}
@SuppressWarnings("unchecked")
public void PairYubiKey(String otp) {
this.name = "PairYubiKey";
this.endpoint = "https://idpxnyl3m.pingidentity.com/pingid/rest/4/pairyubikey/do";
JSONObject reqBody = new JSONObject();
reqBody.put("otp", otp);
reqBody.put("username", this.user.getUserName());
reqBody.put("clientData", this.clientData);
this.requestToken = buildRequestToken(reqBody);
sendRequest();
parseResponse();
values.clear();
}
@SuppressWarnings("unchecked")
public void StartOfflinePairing(OfflinePairingMethod pairingMethod) {
this.name = "StartOfflinePairing";
this.endpoint = "https://idpxnyl3m.pingidentity.com/pingid/rest/4/startofflinepairing/do";
JSONObject reqBody = new JSONObject();
if (pairingMethod == OfflinePairingMethod.SMS) {
reqBody.put("type", OfflinePairingMethod.SMS.getValue());
reqBody.put("pairingData", this.user.getPhoneNumber());
} else if (pairingMethod == OfflinePairingMethod.VOICE) {
reqBody.put("type", OfflinePairingMethod.VOICE.getValue());
reqBody.put("pairingData", this.user.getPhoneNumber());
} else if (pairingMethod == OfflinePairingMethod.EMAIL) {
reqBody.put("type", OfflinePairingMethod.EMAIL.getValue());
reqBody.put("pairingData", this.user.getEmail());
}
reqBody.put("username", this.user.getUserName());
reqBody.put("clientData", this.clientData);
this.requestToken = buildRequestToken(reqBody);
sendRequest();
JSONObject response = parseResponse();
values.clear();
this.lastSessionId = (String)response.get("sessionId");
}
@SuppressWarnings("unchecked")
public void FinalizeOfflinePairing(String sessionId, String otp) {
this.name = "FinalizeOfflinePairing";
this.endpoint = "https://idpxnyl3m.pingidentity.com/pingid/rest/4/finalizeofflinepairing/do";
JSONObject reqBody = new JSONObject();
reqBody.put("otp", otp);
reqBody.put("sessionId", sessionId);
reqBody.put("clientData", this.clientData);
this.requestToken = buildRequestToken(reqBody);
sendRequest();
parseResponse();
values.clear();
}
@SuppressWarnings("unchecked")
public void GetActivationCode() {
this.name = "GetActivationCode";
this.endpoint = "https://idpxnyl3m.pingidentity.com/pingid/rest/4/getactivationcode/do";
JSONObject reqBody = new JSONObject();
reqBody.put("userName", this.user.getUserName());
reqBody.put("clientData", this.clientData);
this.requestToken = buildRequestToken(reqBody);
sendRequest();
JSONObject response = parseResponse();
values.clear();
this.lastActivationCode = (String)response.get("activationCode");
}
@SuppressWarnings("unchecked")
public void AuthenticateOnline(Application application, String authType) {
this.name = "AuthenticateOnline";
this.endpoint = "https://idpxnyl3m.pingidentity.com/pingid/rest/4/authonline/do";
JSONObject reqBody = new JSONObject();
reqBody.put("authType", authType);
reqBody.put("spAlias", application.getSpAlias());
reqBody.put("userName", this.user.getUserName());
reqBody.put("clientData", this.clientData);
JSONObject formParameters = new JSONObject();
formParameters.put("sp_name", application.getName());
if (application.getLogoUrl() != null || !application.getLogoUrl().isEmpty()) {
formParameters.put("sp_logo", application.getLogoUrl());
}
reqBody.put("formParameters", formParameters);
this.requestToken = buildRequestToken(reqBody);
sendRequest();
JSONObject response = parseResponse();
if (this.wasSuccessful) {
values.clear();
this.lastSessionId = (String)response.get("sessionId");
}
}
@SuppressWarnings("unchecked")
public void AuthenticateOffline(String sessionId, String otp) {
this.name = "AuthenticateOffline";
this.endpoint = "https://idpxnyl3m.pingidentity.com/pingid/rest/4/authoffline/do";
JSONObject reqBody = new JSONObject();
reqBody.put("spAlias", "web");
reqBody.put("otp", otp);
reqBody.put("userName", this.user.getUserName());
reqBody.put("sessionId", sessionId);
reqBody.put("clientData", this.clientData);
this.requestToken = buildRequestToken(reqBody);
sendRequest();
parseResponse();
values.clear();
}
//private methods
@SuppressWarnings("unchecked")
private String buildRequestToken(JSONObject requestBody) {
JSONObject requestHeader = buildRequestHeader();
JSONObject payload = new JSONObject();
payload.put("reqHeader", requestHeader);
payload.put("reqBody", requestBody);
JsonWebSignature jws = new JsonWebSignature();
jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.HMAC_SHA256);
jws.setHeader("org_alias", this.orgAlias);
jws.setHeader("token", this.token);
jws.setPayload(payload.toJSONString());
// Set the verification key
HmacKey key = new HmacKey(Base64.decode(this.useBase64Key));
jws.setKey(key);
String jwsCompactSerialization = null;
try {
jwsCompactSerialization = jws.getCompactSerialization();
} catch (JoseException e) {
e.printStackTrace();
}
this.requestToken = jwsCompactSerialization;
return jwsCompactSerialization;
}
@SuppressWarnings("unchecked")
private JSONObject buildRequestHeader() {
JSONObject reqHeader = new JSONObject();
reqHeader.put("locale", "en");
reqHeader.put("orgAlias", this.orgAlias);
reqHeader.put("secretKey", this.token);
reqHeader.put("timestamp", getCurrentTimeStamp());
reqHeader.put("version", this.apiVersion);
return reqHeader;
}
static String getCurrentTimeStamp() {
Date currentDate = new Date();
SimpleDateFormat PingIDDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
PingIDDateFormat.setTimeZone(TimeZone.getTimeZone("America/Denver"));
return PingIDDateFormat.format(currentDate);
}
private void sendRequest() {
try {
URL restUrl = new URL(this.getEndpoint());
HttpURLConnection urlConnection = (HttpURLConnection)restUrl.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.addRequestProperty("Content-Type", "application/json");
urlConnection.addRequestProperty("Accept", "*/*");
urlConnection.setDoOutput(true);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8");
outputStreamWriter.write(this.getRequestToken());
outputStreamWriter.flush();
outputStreamWriter.close();
int responseCode = urlConnection.getResponseCode();
this.responseCode = responseCode;
if (responseCode == 200) {
String encoding = urlConnection.getContentEncoding();
InputStream is = urlConnection.getInputStream();
String stringJWS = IOUtils.toString(is, encoding);
this.responseToken = stringJWS;
this.wasSuccessful = true;
urlConnection.disconnect();
} else {
String encoding = urlConnection.getContentEncoding();
InputStream is = urlConnection.getErrorStream();
String stringJWS = IOUtils.toString(is, encoding);
this.responseToken = stringJWS;
this.wasSuccessful = false;
urlConnection.disconnect();
}
} catch (Exception ex) {
this.responseCode = 500;
this.wasSuccessful = false;
}
}
private JSONObject parseResponse() {
JSONParser parser = new JSONParser();
JSONObject responsePayloadJSON = null;
try {
JsonWebSignature responseJWS = new JsonWebSignature();
responseJWS.setCompactSerialization(this.responseToken);
HmacKey key = new HmacKey(Base64.decode(this.useBase64Key));
responseJWS.setKey(key);
responsePayloadJSON = (JSONObject)parser.parse(responseJWS.getPayload());
// workaround for PingID API 4.5 beta
if (responsePayloadJSON.containsKey("responseBody")) {
responsePayloadJSON = (JSONObject)responsePayloadJSON.get("responseBody");
}
} catch (Exception e) {
e.printStackTrace();
}
if (responsePayloadJSON != null) {
this.errorId = (long)responsePayloadJSON.get("errorId");
this.errorMsg = (String)responsePayloadJSON.get("errorMsg");
this.uniqueMsgId = (String)responsePayloadJSON.get("uniqueMsgId");
this.clientData = (String)responsePayloadJSON.get("clientData");
} else {
this.errorId = 501;
this.errorMsg = "Could not parse JWS";
this.uniqueMsgId = "";
this.clientData = "";
this.wasSuccessful = false;
}
return responsePayloadJSON;
}
}
| minor refactor (extract idpUrl into a separate var)
| src/main/java/com/pingidentity/developer/pingid/Operation.java | minor refactor (extract idpUrl into a separate var) |
|
Java | apache-2.0 | d8e1f5927b7f5173a1ecdbf6d0a62f6e43e671b4 | 0 | electrum/presto,raghavsethi/presto,ptkool/presto,mvp/presto,dain/presto,ebyhr/presto,Praveen2112/presto,raghavsethi/presto,martint/presto,11xor6/presto,losipiuk/presto,miniway/presto,arhimondr/presto,Teradata/presto,haozhun/presto,mvp/presto,EvilMcJerkface/presto,erichwang/presto,erichwang/presto,hgschmie/presto,prestodb/presto,prateek1306/presto,nezihyigitbasi/presto,youngwookim/presto,nezihyigitbasi/presto,martint/presto,miniway/presto,hgschmie/presto,EvilMcJerkface/presto,arhimondr/presto,prestodb/presto,yuananf/presto,electrum/presto,twitter-forks/presto,zzhao0/presto,Yaliang/presto,Yaliang/presto,haozhun/presto,wyukawa/presto,smartnews/presto,youngwookim/presto,yuananf/presto,treasure-data/presto,11xor6/presto,hgschmie/presto,Teradata/presto,nezihyigitbasi/presto,sopel39/presto,twitter-forks/presto,treasure-data/presto,prateek1306/presto,youngwookim/presto,shixuan-fan/presto,losipiuk/presto,erichwang/presto,mvp/presto,treasure-data/presto,stewartpark/presto,stewartpark/presto,youngwookim/presto,dain/presto,yuananf/presto,prateek1306/presto,sopel39/presto,miniway/presto,mvp/presto,Teradata/presto,11xor6/presto,miniway/presto,electrum/presto,treasure-data/presto,EvilMcJerkface/presto,losipiuk/presto,prateek1306/presto,raghavsethi/presto,wyukawa/presto,Praveen2112/presto,nezihyigitbasi/presto,smartnews/presto,zzhao0/presto,ebyhr/presto,stewartpark/presto,raghavsethi/presto,Yaliang/presto,arhimondr/presto,twitter-forks/presto,haozhun/presto,EvilMcJerkface/presto,facebook/presto,EvilMcJerkface/presto,dain/presto,ptkool/presto,prestodb/presto,dain/presto,Yaliang/presto,stewartpark/presto,zzhao0/presto,Yaliang/presto,mvp/presto,haozhun/presto,sopel39/presto,Praveen2112/presto,erichwang/presto,yuananf/presto,dain/presto,martint/presto,11xor6/presto,ebyhr/presto,shixuan-fan/presto,zzhao0/presto,smartnews/presto,facebook/presto,treasure-data/presto,prestodb/presto,youngwookim/presto,stewartpark/presto,Praveen2112/presto,Teradata/presto,shixuan-fan/presto,yuananf/presto,hgschmie/presto,Praveen2112/presto,treasure-data/presto,ebyhr/presto,hgschmie/presto,nezihyigitbasi/presto,martint/presto,facebook/presto,ptkool/presto,wyukawa/presto,haozhun/presto,sopel39/presto,11xor6/presto,ptkool/presto,arhimondr/presto,martint/presto,electrum/presto,wyukawa/presto,facebook/presto,twitter-forks/presto,zzhao0/presto,wyukawa/presto,prestodb/presto,erichwang/presto,prestodb/presto,losipiuk/presto,shixuan-fan/presto,smartnews/presto,sopel39/presto,raghavsethi/presto,Teradata/presto,electrum/presto,smartnews/presto,prateek1306/presto,ebyhr/presto,twitter-forks/presto,miniway/presto,arhimondr/presto,ptkool/presto,losipiuk/presto,shixuan-fan/presto,facebook/presto | /*
* 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.facebook.presto.sql.planner.iterative.rule.test;
import com.facebook.presto.connector.ConnectorId;
import com.facebook.presto.metadata.IndexHandle;
import com.facebook.presto.metadata.Metadata;
import com.facebook.presto.metadata.Signature;
import com.facebook.presto.metadata.TableHandle;
import com.facebook.presto.metadata.TableLayoutHandle;
import com.facebook.presto.spi.ColumnHandle;
import com.facebook.presto.spi.SchemaTableName;
import com.facebook.presto.spi.block.SortOrder;
import com.facebook.presto.spi.predicate.TupleDomain;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.sql.ExpressionUtils;
import com.facebook.presto.sql.analyzer.TypeSignatureProvider;
import com.facebook.presto.sql.parser.SqlParser;
import com.facebook.presto.sql.planner.Partitioning;
import com.facebook.presto.sql.planner.PartitioningScheme;
import com.facebook.presto.sql.planner.PlanNodeIdAllocator;
import com.facebook.presto.sql.planner.Symbol;
import com.facebook.presto.sql.planner.TestingConnectorIndexHandle;
import com.facebook.presto.sql.planner.TestingConnectorTransactionHandle;
import com.facebook.presto.sql.planner.TestingWriterTarget;
import com.facebook.presto.sql.planner.plan.AggregationNode;
import com.facebook.presto.sql.planner.plan.AggregationNode.Aggregation;
import com.facebook.presto.sql.planner.plan.AggregationNode.Step;
import com.facebook.presto.sql.planner.plan.ApplyNode;
import com.facebook.presto.sql.planner.plan.Assignments;
import com.facebook.presto.sql.planner.plan.DeleteNode;
import com.facebook.presto.sql.planner.plan.EnforceSingleRowNode;
import com.facebook.presto.sql.planner.plan.ExchangeNode;
import com.facebook.presto.sql.planner.plan.FilterNode;
import com.facebook.presto.sql.planner.plan.IndexJoinNode;
import com.facebook.presto.sql.planner.plan.IndexSourceNode;
import com.facebook.presto.sql.planner.plan.JoinNode;
import com.facebook.presto.sql.planner.plan.LateralJoinNode;
import com.facebook.presto.sql.planner.plan.LimitNode;
import com.facebook.presto.sql.planner.plan.MarkDistinctNode;
import com.facebook.presto.sql.planner.plan.OutputNode;
import com.facebook.presto.sql.planner.plan.PlanNode;
import com.facebook.presto.sql.planner.plan.ProjectNode;
import com.facebook.presto.sql.planner.plan.SampleNode;
import com.facebook.presto.sql.planner.plan.SemiJoinNode;
import com.facebook.presto.sql.planner.plan.TableFinishNode;
import com.facebook.presto.sql.planner.plan.TableScanNode;
import com.facebook.presto.sql.planner.plan.TableWriterNode;
import com.facebook.presto.sql.planner.plan.TopNNode;
import com.facebook.presto.sql.planner.plan.UnionNode;
import com.facebook.presto.sql.planner.plan.ValuesNode;
import com.facebook.presto.sql.planner.plan.WindowNode;
import com.facebook.presto.sql.tree.Expression;
import com.facebook.presto.sql.tree.FunctionCall;
import com.facebook.presto.sql.tree.NullLiteral;
import com.facebook.presto.testing.TestingMetadata.TestingTableHandle;
import com.google.common.base.Functions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Maps;
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 java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Stream;
import static com.facebook.presto.spi.type.BigintType.BIGINT;
import static com.facebook.presto.spi.type.VarbinaryType.VARBINARY;
import static com.facebook.presto.sql.planner.SystemPartitioningHandle.FIXED_HASH_DISTRIBUTION;
import static com.facebook.presto.sql.planner.SystemPartitioningHandle.SINGLE_DISTRIBUTION;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static java.lang.String.format;
import static java.util.Collections.emptyList;
public class PlanBuilder
{
private final PlanNodeIdAllocator idAllocator;
private final Metadata metadata;
private final Map<Symbol, Type> symbols = new HashMap<>();
public PlanBuilder(PlanNodeIdAllocator idAllocator, Metadata metadata)
{
this.idAllocator = idAllocator;
this.metadata = metadata;
}
public OutputNode output(List<String> columnNames, List<Symbol> outputs, PlanNode source)
{
return new OutputNode(
idAllocator.getNextId(),
source,
columnNames,
outputs);
}
public ValuesNode values(Symbol... columns)
{
return new ValuesNode(
idAllocator.getNextId(),
ImmutableList.copyOf(columns),
ImmutableList.of());
}
public ValuesNode values(List<Symbol> columns, List<List<Expression>> rows)
{
return new ValuesNode(idAllocator.getNextId(), columns, rows);
}
public EnforceSingleRowNode enforceSingleRow(PlanNode source)
{
return new EnforceSingleRowNode(idAllocator.getNextId(), source);
}
public LimitNode limit(long limit, PlanNode source)
{
return new LimitNode(idAllocator.getNextId(), source, limit, false);
}
public MarkDistinctNode markDistinct(PlanNode source, Symbol markerSymbol, List<Symbol> distinctSymbols)
{
return new MarkDistinctNode(idAllocator.getNextId(), source, markerSymbol, distinctSymbols, Optional.empty());
}
public TopNNode topN(long count, List<Symbol> orderBy, PlanNode source)
{
return new TopNNode(
idAllocator.getNextId(),
source,
count,
orderBy,
Maps.toMap(orderBy, Functions.constant(SortOrder.ASC_NULLS_FIRST)),
TopNNode.Step.SINGLE);
}
public SampleNode sample(double sampleRatio, SampleNode.Type type, PlanNode source)
{
return new SampleNode(idAllocator.getNextId(), source, sampleRatio, type);
}
public ProjectNode project(Assignments assignments, PlanNode source)
{
return new ProjectNode(idAllocator.getNextId(), source, assignments);
}
public MarkDistinctNode markDistinct(Symbol markerSymbol, List<Symbol> distinctSymbols, PlanNode source)
{
return new MarkDistinctNode(idAllocator.getNextId(), source, markerSymbol, distinctSymbols, Optional.empty());
}
public MarkDistinctNode markDistinct(Symbol markerSymbol, List<Symbol> distinctSymbols, Symbol hashSymbol, PlanNode source)
{
return new MarkDistinctNode(idAllocator.getNextId(), source, markerSymbol, distinctSymbols, Optional.of(hashSymbol));
}
public FilterNode filter(Expression predicate, PlanNode source)
{
return new FilterNode(idAllocator.getNextId(), source, predicate);
}
public AggregationNode aggregation(Consumer<AggregationBuilder> aggregationBuilderConsumer)
{
AggregationBuilder aggregationBuilder = new AggregationBuilder();
aggregationBuilderConsumer.accept(aggregationBuilder);
return aggregationBuilder.build();
}
public class AggregationBuilder
{
private PlanNode source;
private Map<Symbol, Aggregation> assignments = new HashMap<>();
private List<List<Symbol>> groupingSets = new ArrayList<>();
private Step step = Step.SINGLE;
private Optional<Symbol> hashSymbol = Optional.empty();
private Optional<Symbol> groupIdSymbol = Optional.empty();
public AggregationBuilder source(PlanNode source)
{
this.source = source;
return this;
}
public AggregationBuilder addAggregation(Symbol output, Expression expression, List<Type> inputTypes)
{
return addAggregation(output, expression, inputTypes, Optional.empty());
}
public AggregationBuilder addAggregation(Symbol output, Expression expression, List<Type> inputTypes, Symbol mask)
{
return addAggregation(output, expression, inputTypes, Optional.of(mask));
}
private AggregationBuilder addAggregation(Symbol output, Expression expression, List<Type> inputTypes, Optional<Symbol> mask)
{
checkArgument(expression instanceof FunctionCall);
FunctionCall aggregation = (FunctionCall) expression;
Signature signature = metadata.getFunctionRegistry().resolveFunction(aggregation.getName(), TypeSignatureProvider.fromTypes(inputTypes));
return addAggregation(output, new Aggregation(aggregation, signature, mask));
}
public AggregationBuilder addAggregation(Symbol output, Aggregation aggregation)
{
assignments.put(output, aggregation);
return this;
}
public AggregationBuilder globalGrouping()
{
return groupingSets(ImmutableList.of(ImmutableList.of()));
}
public AggregationBuilder groupingSets(List<List<Symbol>> groupingSets)
{
checkState(this.groupingSets.isEmpty(), "groupingSets already defined");
this.groupingSets.addAll(groupingSets);
return this;
}
public AggregationBuilder addGroupingSet(Symbol... symbols)
{
return addGroupingSet(ImmutableList.copyOf(symbols));
}
public AggregationBuilder addGroupingSet(List<Symbol> symbols)
{
groupingSets.add(ImmutableList.copyOf(symbols));
return this;
}
public AggregationBuilder step(Step step)
{
this.step = step;
return this;
}
public AggregationBuilder hashSymbol(Symbol hashSymbol)
{
this.hashSymbol = Optional.of(hashSymbol);
return this;
}
public AggregationBuilder groupIdSymbol(Symbol groupIdSymbol)
{
this.groupIdSymbol = Optional.of(groupIdSymbol);
return this;
}
protected AggregationNode build()
{
checkState(!groupingSets.isEmpty(), "No grouping sets defined; use globalGrouping/addGroupingSet/addEmptyGroupingSet method");
return new AggregationNode(
idAllocator.getNextId(),
source,
assignments,
groupingSets,
step,
hashSymbol,
groupIdSymbol);
}
}
public ApplyNode apply(Assignments subqueryAssignments, List<Symbol> correlation, PlanNode input, PlanNode subquery)
{
NullLiteral originSubquery = new NullLiteral(); // does not matter for tests
return new ApplyNode(idAllocator.getNextId(), input, subquery, subqueryAssignments, correlation, originSubquery);
}
public LateralJoinNode lateral(List<Symbol> correlation, PlanNode input, PlanNode subquery)
{
NullLiteral originSubquery = new NullLiteral(); // does not matter for tests
return new LateralJoinNode(idAllocator.getNextId(), input, subquery, correlation, LateralJoinNode.Type.INNER, originSubquery);
}
public TableScanNode tableScan(List<Symbol> symbols, Map<Symbol, ColumnHandle> assignments)
{
return tableScan(symbols, assignments, null);
}
public TableScanNode tableScan(List<Symbol> symbols, Map<Symbol, ColumnHandle> assignments, Expression originalConstraint)
{
TableHandle tableHandle = new TableHandle(new ConnectorId("testConnector"), new TestingTableHandle());
return tableScan(tableHandle, symbols, assignments, originalConstraint);
}
public TableScanNode tableScan(TableHandle tableHandle, List<Symbol> symbols, Map<Symbol, ColumnHandle> assignments)
{
return tableScan(tableHandle, symbols, assignments, null);
}
public TableScanNode tableScan(TableHandle tableHandle, List<Symbol> symbols, Map<Symbol, ColumnHandle> assignments, Expression originalConstraint)
{
return tableScan(tableHandle, symbols, assignments, originalConstraint, Optional.empty());
}
public TableScanNode tableScan(
TableHandle tableHandle,
List<Symbol> symbols,
Map<Symbol, ColumnHandle> assignments,
Expression originalConstraint,
Optional<TableLayoutHandle> tableLayout)
{
return new TableScanNode(
idAllocator.getNextId(),
tableHandle,
symbols,
assignments,
tableLayout,
TupleDomain.all(),
originalConstraint);
}
public TableFinishNode tableDelete(SchemaTableName schemaTableName, PlanNode deleteSource, Symbol deleteRowId)
{
TableWriterNode.DeleteHandle deleteHandle = new TableWriterNode.DeleteHandle(
new TableHandle(
new ConnectorId("testConnector"),
new TestingTableHandle()),
schemaTableName);
return new TableFinishNode(
idAllocator.getNextId(),
exchange(e -> e
.addSource(new DeleteNode(
idAllocator.getNextId(),
deleteSource,
deleteHandle,
deleteRowId,
ImmutableList.of(deleteRowId)))
.addInputsSet(deleteRowId)
.singleDistributionPartitioningScheme(deleteRowId)),
deleteHandle,
ImmutableList.of(deleteRowId));
}
public ExchangeNode gatheringExchange(ExchangeNode.Scope scope, PlanNode child)
{
return exchange(builder -> builder.type(ExchangeNode.Type.GATHER)
.scope(scope)
.singleDistributionPartitioningScheme(child.getOutputSymbols())
.addSource(child)
.addInputsSet(child.getOutputSymbols()));
}
public SemiJoinNode semiJoin(
Symbol sourceJoinSymbol,
Symbol filteringSourceJoinSymbol,
Symbol semiJoinOutput,
Optional<Symbol> sourceHashSymbol,
Optional<Symbol> filteringSourceHashSymbol,
PlanNode source,
PlanNode filteringSource)
{
return new SemiJoinNode(idAllocator.getNextId(),
source,
filteringSource,
sourceJoinSymbol,
filteringSourceJoinSymbol,
semiJoinOutput,
sourceHashSymbol,
filteringSourceHashSymbol,
Optional.empty());
}
public IndexSourceNode indexSource(
TableHandle tableHandle,
Set<Symbol> lookupSymbols,
List<Symbol> outputSymbols,
Map<Symbol, ColumnHandle> assignments,
TupleDomain<ColumnHandle> effectiveTupleDomain)
{
return new IndexSourceNode(
idAllocator.getNextId(),
new IndexHandle(
tableHandle.getConnectorId(),
TestingConnectorTransactionHandle.INSTANCE,
TestingConnectorIndexHandle.INSTANCE),
tableHandle,
Optional.empty(),
lookupSymbols,
outputSymbols,
assignments,
effectiveTupleDomain);
}
public ExchangeNode exchange(Consumer<ExchangeBuilder> exchangeBuilderConsumer)
{
ExchangeBuilder exchangeBuilder = new ExchangeBuilder();
exchangeBuilderConsumer.accept(exchangeBuilder);
return exchangeBuilder.build();
}
public class ExchangeBuilder
{
private ExchangeNode.Type type = ExchangeNode.Type.GATHER;
private ExchangeNode.Scope scope = ExchangeNode.Scope.REMOTE;
private PartitioningScheme partitioningScheme;
private List<PlanNode> sources = new ArrayList<>();
private List<List<Symbol>> inputs = new ArrayList<>();
public ExchangeBuilder type(ExchangeNode.Type type)
{
this.type = type;
return this;
}
public ExchangeBuilder scope(ExchangeNode.Scope scope)
{
this.scope = scope;
return this;
}
public ExchangeBuilder singleDistributionPartitioningScheme(Symbol... outputSymbols)
{
return singleDistributionPartitioningScheme(Arrays.asList(outputSymbols));
}
public ExchangeBuilder singleDistributionPartitioningScheme(List<Symbol> outputSymbols)
{
return partitioningScheme(new PartitioningScheme(Partitioning.create(SINGLE_DISTRIBUTION, ImmutableList.of()), outputSymbols));
}
public ExchangeBuilder fixedHashDistributionParitioningScheme(List<Symbol> outputSymbols, List<Symbol> partitioningSymbols)
{
return partitioningScheme(new PartitioningScheme(Partitioning.create(
FIXED_HASH_DISTRIBUTION,
ImmutableList.copyOf(partitioningSymbols)),
ImmutableList.copyOf(outputSymbols)));
}
public ExchangeBuilder fixedHashDistributionParitioningScheme(List<Symbol> outputSymbols, List<Symbol> partitioningSymbols, Symbol hashSymbol)
{
return partitioningScheme(new PartitioningScheme(Partitioning.create(
FIXED_HASH_DISTRIBUTION,
ImmutableList.copyOf(partitioningSymbols)),
ImmutableList.copyOf(outputSymbols),
Optional.of(hashSymbol)));
}
public ExchangeBuilder partitioningScheme(PartitioningScheme partitioningScheme)
{
this.partitioningScheme = partitioningScheme;
return this;
}
public ExchangeBuilder addSource(PlanNode source)
{
this.sources.add(source);
return this;
}
public ExchangeBuilder addInputsSet(Symbol... inputs)
{
return addInputsSet(Arrays.asList(inputs));
}
public ExchangeBuilder addInputsSet(List<Symbol> inputs)
{
this.inputs.add(inputs);
return this;
}
protected ExchangeNode build()
{
return new ExchangeNode(idAllocator.getNextId(), type, scope, partitioningScheme, sources, inputs);
}
}
public JoinNode join(JoinNode.Type joinType, PlanNode left, PlanNode right, JoinNode.EquiJoinClause... criteria)
{
return join(joinType, left, right, Optional.empty(), criteria);
}
public JoinNode join(JoinNode.Type joinType, PlanNode left, PlanNode right, Expression filter, JoinNode.EquiJoinClause... criteria)
{
return join(joinType, left, right, Optional.of(filter), criteria);
}
private JoinNode join(JoinNode.Type joinType, PlanNode left, PlanNode right, Optional<Expression> filter, JoinNode.EquiJoinClause... criteria)
{
return join(
joinType,
left,
right,
ImmutableList.copyOf(criteria),
ImmutableList.<Symbol>builder()
.addAll(left.getOutputSymbols())
.addAll(right.getOutputSymbols())
.build(),
filter,
Optional.empty(),
Optional.empty());
}
public JoinNode join(
JoinNode.Type type,
PlanNode left,
PlanNode right,
List<JoinNode.EquiJoinClause> criteria,
List<Symbol> outputSymbols,
Optional<Expression> filter,
Optional<Symbol> leftHashSymbol,
Optional<Symbol> rightHashSymbol)
{
return new JoinNode(idAllocator.getNextId(), type, left, right, criteria, outputSymbols, filter, leftHashSymbol, rightHashSymbol, Optional.empty());
}
public PlanNode indexJoin(IndexJoinNode.Type type, TableScanNode probe, TableScanNode index)
{
return new IndexJoinNode(
idAllocator.getNextId(),
type,
probe,
index,
emptyList(),
Optional.empty(),
Optional.empty());
}
public UnionNode union(ListMultimap<Symbol, Symbol> outputsToInputs, List<PlanNode> sources)
{
ImmutableList<Symbol> outputs = outputsToInputs.keySet().stream().collect(toImmutableList());
return new UnionNode(idAllocator.getNextId(), sources, outputsToInputs, outputs);
}
public TableWriterNode tableWriter(List<Symbol> columns, List<String> columnNames, PlanNode source)
{
return new TableWriterNode(
idAllocator.getNextId(),
source,
new TestingWriterTarget(),
columns,
columnNames,
ImmutableList.of(symbol("partialrows", BIGINT), symbol("fragment", VARBINARY)),
Optional.empty());
}
public Symbol symbol(String name)
{
return symbol(name, BIGINT);
}
public Symbol symbol(String name, Type type)
{
Symbol symbol = new Symbol(name);
Type old = symbols.put(symbol, type);
if (old != null && !old.equals(type)) {
throw new IllegalArgumentException(format("Symbol '%s' already registered with type '%s'", name, old));
}
if (old == null) {
symbols.put(symbol, type);
}
return symbol;
}
public WindowNode window(WindowNode.Specification specification, Map<Symbol, WindowNode.Function> functions, PlanNode source)
{
return new WindowNode(
idAllocator.getNextId(),
source,
specification,
ImmutableMap.copyOf(functions),
Optional.empty(),
ImmutableSet.of(),
0);
}
public WindowNode window(WindowNode.Specification specification, Map<Symbol, WindowNode.Function> functions, Symbol hashSymbol, PlanNode source)
{
return new WindowNode(
idAllocator.getNextId(),
source,
specification,
ImmutableMap.copyOf(functions),
Optional.of(hashSymbol),
ImmutableSet.of(),
0);
}
public static Expression expression(String sql)
{
return ExpressionUtils.rewriteIdentifiersToSymbolReferences(new SqlParser().createExpression(sql));
}
public static List<Expression> expressions(String... expressions)
{
return Stream.of(expressions)
.map(PlanBuilder::expression)
.collect(toImmutableList());
}
public Map<Symbol, Type> getSymbols()
{
return Collections.unmodifiableMap(symbols);
}
}
| presto-main/src/test/java/com/facebook/presto/sql/planner/iterative/rule/test/PlanBuilder.java | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.sql.planner.iterative.rule.test;
import com.facebook.presto.connector.ConnectorId;
import com.facebook.presto.metadata.IndexHandle;
import com.facebook.presto.metadata.Metadata;
import com.facebook.presto.metadata.Signature;
import com.facebook.presto.metadata.TableHandle;
import com.facebook.presto.metadata.TableLayoutHandle;
import com.facebook.presto.spi.ColumnHandle;
import com.facebook.presto.spi.SchemaTableName;
import com.facebook.presto.spi.block.SortOrder;
import com.facebook.presto.spi.predicate.TupleDomain;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.sql.ExpressionUtils;
import com.facebook.presto.sql.analyzer.TypeSignatureProvider;
import com.facebook.presto.sql.parser.SqlParser;
import com.facebook.presto.sql.planner.Partitioning;
import com.facebook.presto.sql.planner.PartitioningScheme;
import com.facebook.presto.sql.planner.PlanNodeIdAllocator;
import com.facebook.presto.sql.planner.Symbol;
import com.facebook.presto.sql.planner.TestingConnectorIndexHandle;
import com.facebook.presto.sql.planner.TestingConnectorTransactionHandle;
import com.facebook.presto.sql.planner.TestingWriterTarget;
import com.facebook.presto.sql.planner.plan.AggregationNode;
import com.facebook.presto.sql.planner.plan.AggregationNode.Aggregation;
import com.facebook.presto.sql.planner.plan.AggregationNode.Step;
import com.facebook.presto.sql.planner.plan.ApplyNode;
import com.facebook.presto.sql.planner.plan.Assignments;
import com.facebook.presto.sql.planner.plan.DeleteNode;
import com.facebook.presto.sql.planner.plan.EnforceSingleRowNode;
import com.facebook.presto.sql.planner.plan.ExchangeNode;
import com.facebook.presto.sql.planner.plan.FilterNode;
import com.facebook.presto.sql.planner.plan.IndexJoinNode;
import com.facebook.presto.sql.planner.plan.IndexSourceNode;
import com.facebook.presto.sql.planner.plan.JoinNode;
import com.facebook.presto.sql.planner.plan.LateralJoinNode;
import com.facebook.presto.sql.planner.plan.LimitNode;
import com.facebook.presto.sql.planner.plan.MarkDistinctNode;
import com.facebook.presto.sql.planner.plan.OutputNode;
import com.facebook.presto.sql.planner.plan.PlanNode;
import com.facebook.presto.sql.planner.plan.ProjectNode;
import com.facebook.presto.sql.planner.plan.SampleNode;
import com.facebook.presto.sql.planner.plan.SemiJoinNode;
import com.facebook.presto.sql.planner.plan.TableFinishNode;
import com.facebook.presto.sql.planner.plan.TableScanNode;
import com.facebook.presto.sql.planner.plan.TableWriterNode;
import com.facebook.presto.sql.planner.plan.TopNNode;
import com.facebook.presto.sql.planner.plan.UnionNode;
import com.facebook.presto.sql.planner.plan.ValuesNode;
import com.facebook.presto.sql.planner.plan.WindowNode;
import com.facebook.presto.sql.tree.Expression;
import com.facebook.presto.sql.tree.FunctionCall;
import com.facebook.presto.sql.tree.NullLiteral;
import com.facebook.presto.testing.TestingMetadata.TestingTableHandle;
import com.google.common.base.Functions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Maps;
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 java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Stream;
import static com.facebook.presto.spi.type.BigintType.BIGINT;
import static com.facebook.presto.spi.type.VarbinaryType.VARBINARY;
import static com.facebook.presto.sql.planner.SystemPartitioningHandle.FIXED_HASH_DISTRIBUTION;
import static com.facebook.presto.sql.planner.SystemPartitioningHandle.SINGLE_DISTRIBUTION;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static java.lang.String.format;
import static java.util.Collections.emptyList;
public class PlanBuilder
{
private final PlanNodeIdAllocator idAllocator;
private final Metadata metadata;
private final Map<Symbol, Type> symbols = new HashMap<>();
public PlanBuilder(PlanNodeIdAllocator idAllocator, Metadata metadata)
{
this.idAllocator = idAllocator;
this.metadata = metadata;
}
public OutputNode output(List<String> columnNames, List<Symbol> outputs, PlanNode source)
{
return new OutputNode(
idAllocator.getNextId(),
source,
columnNames,
outputs);
}
public ValuesNode values(Symbol... columns)
{
return new ValuesNode(
idAllocator.getNextId(),
ImmutableList.copyOf(columns),
ImmutableList.of());
}
public ValuesNode values(List<Symbol> columns, List<List<Expression>> rows)
{
return new ValuesNode(idAllocator.getNextId(), columns, rows);
}
public EnforceSingleRowNode enforceSingleRow(PlanNode source)
{
return new EnforceSingleRowNode(idAllocator.getNextId(), source);
}
public LimitNode limit(long limit, PlanNode source)
{
return new LimitNode(idAllocator.getNextId(), source, limit, false);
}
public MarkDistinctNode markDistinct(PlanNode source, Symbol markerSymbol, List<Symbol> distinctSymbols)
{
return new MarkDistinctNode(idAllocator.getNextId(), source, markerSymbol, distinctSymbols, Optional.empty());
}
public TopNNode topN(long count, List<Symbol> orderBy, PlanNode source)
{
return new TopNNode(
idAllocator.getNextId(),
source,
count,
orderBy,
Maps.toMap(orderBy, Functions.constant(SortOrder.ASC_NULLS_FIRST)),
TopNNode.Step.SINGLE);
}
public SampleNode sample(double sampleRatio, SampleNode.Type type, PlanNode source)
{
return new SampleNode(idAllocator.getNextId(), source, sampleRatio, type);
}
public ProjectNode project(Assignments assignments, PlanNode source)
{
return new ProjectNode(idAllocator.getNextId(), source, assignments);
}
public MarkDistinctNode markDistinct(Symbol markerSymbol, List<Symbol> distinctSymbols, PlanNode source)
{
return new MarkDistinctNode(idAllocator.getNextId(), source, markerSymbol, distinctSymbols, Optional.empty());
}
public MarkDistinctNode markDistinct(Symbol markerSymbol, List<Symbol> distinctSymbols, Symbol hashSymbol, PlanNode source)
{
return new MarkDistinctNode(idAllocator.getNextId(), source, markerSymbol, distinctSymbols, Optional.of(hashSymbol));
}
public FilterNode filter(Expression predicate, PlanNode source)
{
return new FilterNode(idAllocator.getNextId(), source, predicate);
}
public AggregationNode aggregation(Consumer<AggregationBuilder> aggregationBuilderConsumer)
{
AggregationBuilder aggregationBuilder = new AggregationBuilder();
aggregationBuilderConsumer.accept(aggregationBuilder);
return aggregationBuilder.build();
}
public class AggregationBuilder
{
private PlanNode source;
private Map<Symbol, Aggregation> assignments = new HashMap<>();
private List<List<Symbol>> groupingSets = new ArrayList<>();
private Step step = Step.SINGLE;
private Optional<Symbol> hashSymbol = Optional.empty();
private Optional<Symbol> groupIdSymbol = Optional.empty();
public AggregationBuilder source(PlanNode source)
{
this.source = source;
return this;
}
public AggregationBuilder addAggregation(Symbol output, Expression expression, List<Type> inputTypes)
{
return addAggregation(output, expression, inputTypes, Optional.empty());
}
public AggregationBuilder addAggregation(Symbol output, Expression expression, List<Type> inputTypes, Symbol mask)
{
return addAggregation(output, expression, inputTypes, Optional.of(mask));
}
private AggregationBuilder addAggregation(Symbol output, Expression expression, List<Type> inputTypes, Optional<Symbol> mask)
{
checkArgument(expression instanceof FunctionCall);
FunctionCall aggregation = (FunctionCall) expression;
Signature signature = metadata.getFunctionRegistry().resolveFunction(aggregation.getName(), TypeSignatureProvider.fromTypes(inputTypes));
return addAggregation(output, new Aggregation(aggregation, signature, mask));
}
public AggregationBuilder addAggregation(Symbol output, Aggregation aggregation)
{
assignments.put(output, aggregation);
return this;
}
public AggregationBuilder globalGrouping()
{
return groupingSets(ImmutableList.of(ImmutableList.of()));
}
public AggregationBuilder groupingSets(List<List<Symbol>> groupingSets)
{
checkState(this.groupingSets.isEmpty(), "groupingSets already defined");
this.groupingSets.addAll(groupingSets);
return this;
}
public AggregationBuilder addGroupingSet(Symbol... symbols)
{
return addGroupingSet(ImmutableList.copyOf(symbols));
}
public AggregationBuilder addGroupingSet(List<Symbol> symbols)
{
groupingSets.add(ImmutableList.copyOf(symbols));
return this;
}
public AggregationBuilder step(Step step)
{
this.step = step;
return this;
}
public AggregationBuilder hashSymbol(Symbol hashSymbol)
{
this.hashSymbol = Optional.of(hashSymbol);
return this;
}
public AggregationBuilder groupIdSymbol(Symbol groupIdSymbol)
{
this.groupIdSymbol = Optional.of(groupIdSymbol);
return this;
}
protected AggregationNode build()
{
checkState(!groupingSets.isEmpty(), "No grouping sets defined; use globalGrouping/addGroupingSet/addEmptyGroupingSet method");
return new AggregationNode(
idAllocator.getNextId(),
source,
assignments,
groupingSets,
step,
hashSymbol,
groupIdSymbol);
}
}
public ApplyNode apply(Assignments subqueryAssignments, List<Symbol> correlation, PlanNode input, PlanNode subquery)
{
NullLiteral originSubquery = new NullLiteral(); // does not matter for tests
return new ApplyNode(idAllocator.getNextId(), input, subquery, subqueryAssignments, correlation, originSubquery);
}
public LateralJoinNode lateral(List<Symbol> correlation, PlanNode input, PlanNode subquery)
{
NullLiteral originSubquery = new NullLiteral(); // does not matter for tests
return new LateralJoinNode(idAllocator.getNextId(), input, subquery, correlation, LateralJoinNode.Type.INNER, originSubquery);
}
public TableScanNode tableScan(List<Symbol> symbols, Map<Symbol, ColumnHandle> assignments)
{
return tableScan(symbols, assignments, null);
}
public TableScanNode tableScan(List<Symbol> symbols, Map<Symbol, ColumnHandle> assignments, Expression originalConstraint)
{
TableHandle tableHandle = new TableHandle(new ConnectorId("testConnector"), new TestingTableHandle());
return tableScan(tableHandle, symbols, assignments, originalConstraint);
}
public TableScanNode tableScan(TableHandle tableHandle, List<Symbol> symbols, Map<Symbol, ColumnHandle> assignments)
{
return tableScan(tableHandle, symbols, assignments, null);
}
public TableScanNode tableScan(TableHandle tableHandle, List<Symbol> symbols, Map<Symbol, ColumnHandle> assignments, Expression originalConstraint)
{
return tableScan(tableHandle, symbols, assignments, originalConstraint, Optional.empty());
}
public TableScanNode tableScan(TableHandle tableHandle, List<Symbol> symbols, Map<Symbol, ColumnHandle> assignments, Expression originalConstraint, Optional<TableLayoutHandle> tableLayout)
{
return new TableScanNode(
idAllocator.getNextId(),
tableHandle,
symbols,
assignments,
tableLayout,
TupleDomain.all(),
originalConstraint);
}
public TableFinishNode tableDelete(SchemaTableName schemaTableName, PlanNode deleteSource, Symbol deleteRowId)
{
TableWriterNode.DeleteHandle deleteHandle = new TableWriterNode.DeleteHandle(
new TableHandle(
new ConnectorId("testConnector"),
new TestingTableHandle()),
schemaTableName);
return new TableFinishNode(
idAllocator.getNextId(),
exchange(e -> e
.addSource(new DeleteNode(
idAllocator.getNextId(),
deleteSource,
deleteHandle,
deleteRowId,
ImmutableList.of(deleteRowId)))
.addInputsSet(deleteRowId)
.singleDistributionPartitioningScheme(deleteRowId)),
deleteHandle,
ImmutableList.of(deleteRowId));
}
public ExchangeNode gatheringExchange(ExchangeNode.Scope scope, PlanNode child)
{
return exchange(builder -> builder.type(ExchangeNode.Type.GATHER)
.scope(scope)
.singleDistributionPartitioningScheme(child.getOutputSymbols())
.addSource(child)
.addInputsSet(child.getOutputSymbols()));
}
public SemiJoinNode semiJoin(
Symbol sourceJoinSymbol,
Symbol filteringSourceJoinSymbol,
Symbol semiJoinOutput,
Optional<Symbol> sourceHashSymbol,
Optional<Symbol> filteringSourceHashSymbol,
PlanNode source,
PlanNode filteringSource)
{
return new SemiJoinNode(idAllocator.getNextId(),
source,
filteringSource,
sourceJoinSymbol,
filteringSourceJoinSymbol,
semiJoinOutput,
sourceHashSymbol,
filteringSourceHashSymbol,
Optional.empty());
}
public IndexSourceNode indexSource(
TableHandle tableHandle,
Set<Symbol> lookupSymbols,
List<Symbol> outputSymbols,
Map<Symbol, ColumnHandle> assignments,
TupleDomain<ColumnHandle> effectiveTupleDomain)
{
return new IndexSourceNode(
idAllocator.getNextId(),
new IndexHandle(
tableHandle.getConnectorId(),
TestingConnectorTransactionHandle.INSTANCE,
TestingConnectorIndexHandle.INSTANCE),
tableHandle,
Optional.empty(),
lookupSymbols,
outputSymbols,
assignments,
effectiveTupleDomain);
}
public ExchangeNode exchange(Consumer<ExchangeBuilder> exchangeBuilderConsumer)
{
ExchangeBuilder exchangeBuilder = new ExchangeBuilder();
exchangeBuilderConsumer.accept(exchangeBuilder);
return exchangeBuilder.build();
}
public class ExchangeBuilder
{
private ExchangeNode.Type type = ExchangeNode.Type.GATHER;
private ExchangeNode.Scope scope = ExchangeNode.Scope.REMOTE;
private PartitioningScheme partitioningScheme;
private List<PlanNode> sources = new ArrayList<>();
private List<List<Symbol>> inputs = new ArrayList<>();
public ExchangeBuilder type(ExchangeNode.Type type)
{
this.type = type;
return this;
}
public ExchangeBuilder scope(ExchangeNode.Scope scope)
{
this.scope = scope;
return this;
}
public ExchangeBuilder singleDistributionPartitioningScheme(Symbol... outputSymbols)
{
return singleDistributionPartitioningScheme(Arrays.asList(outputSymbols));
}
public ExchangeBuilder singleDistributionPartitioningScheme(List<Symbol> outputSymbols)
{
return partitioningScheme(new PartitioningScheme(Partitioning.create(SINGLE_DISTRIBUTION, ImmutableList.of()), outputSymbols));
}
public ExchangeBuilder fixedHashDistributionParitioningScheme(List<Symbol> outputSymbols, List<Symbol> partitioningSymbols)
{
return partitioningScheme(new PartitioningScheme(Partitioning.create(FIXED_HASH_DISTRIBUTION, ImmutableList.copyOf(partitioningSymbols)), ImmutableList.copyOf(outputSymbols)));
}
public ExchangeBuilder fixedHashDistributionParitioningScheme(List<Symbol> outputSymbols, List<Symbol> partitioningSymbols, Symbol hashSymbol)
{
return partitioningScheme(new PartitioningScheme(Partitioning.create(FIXED_HASH_DISTRIBUTION, ImmutableList.copyOf(partitioningSymbols)), ImmutableList.copyOf(outputSymbols), Optional.of(hashSymbol)));
}
public ExchangeBuilder partitioningScheme(PartitioningScheme partitioningScheme)
{
this.partitioningScheme = partitioningScheme;
return this;
}
public ExchangeBuilder addSource(PlanNode source)
{
this.sources.add(source);
return this;
}
public ExchangeBuilder addInputsSet(Symbol... inputs)
{
return addInputsSet(Arrays.asList(inputs));
}
public ExchangeBuilder addInputsSet(List<Symbol> inputs)
{
this.inputs.add(inputs);
return this;
}
protected ExchangeNode build()
{
return new ExchangeNode(idAllocator.getNextId(), type, scope, partitioningScheme, sources, inputs);
}
}
public JoinNode join(JoinNode.Type joinType, PlanNode left, PlanNode right, JoinNode.EquiJoinClause... criteria)
{
return join(joinType, left, right, Optional.empty(), criteria);
}
public JoinNode join(JoinNode.Type joinType, PlanNode left, PlanNode right, Expression filter, JoinNode.EquiJoinClause... criteria)
{
return join(joinType, left, right, Optional.of(filter), criteria);
}
private JoinNode join(JoinNode.Type joinType, PlanNode left, PlanNode right, Optional<Expression> filter, JoinNode.EquiJoinClause... criteria)
{
return join(
joinType,
left,
right,
ImmutableList.copyOf(criteria),
ImmutableList.<Symbol>builder()
.addAll(left.getOutputSymbols())
.addAll(right.getOutputSymbols())
.build(),
filter,
Optional.empty(),
Optional.empty());
}
public JoinNode join(
JoinNode.Type type,
PlanNode left,
PlanNode right,
List<JoinNode.EquiJoinClause> criteria,
List<Symbol> outputSymbols,
Optional<Expression> filter,
Optional<Symbol> leftHashSymbol,
Optional<Symbol> rightHashSymbol)
{
return new JoinNode(idAllocator.getNextId(), type, left, right, criteria, outputSymbols, filter, leftHashSymbol, rightHashSymbol, Optional.empty());
}
public PlanNode indexJoin(IndexJoinNode.Type type, TableScanNode probe, TableScanNode index)
{
return new IndexJoinNode(
idAllocator.getNextId(),
type,
probe,
index,
emptyList(),
Optional.empty(),
Optional.empty());
}
public UnionNode union(ListMultimap<Symbol, Symbol> outputsToInputs, List<PlanNode> sources)
{
ImmutableList<Symbol> outputs = outputsToInputs.keySet().stream().collect(toImmutableList());
return new UnionNode(idAllocator.getNextId(), sources, outputsToInputs, outputs);
}
public TableWriterNode tableWriter(List<Symbol> columns, List<String> columnNames, PlanNode source)
{
return new TableWriterNode(
idAllocator.getNextId(),
source,
new TestingWriterTarget(),
columns,
columnNames,
ImmutableList.of(symbol("partialrows", BIGINT), symbol("fragment", VARBINARY)),
Optional.empty());
}
public Symbol symbol(String name)
{
return symbol(name, BIGINT);
}
public Symbol symbol(String name, Type type)
{
Symbol symbol = new Symbol(name);
Type old = symbols.put(symbol, type);
if (old != null && !old.equals(type)) {
throw new IllegalArgumentException(format("Symbol '%s' already registered with type '%s'", name, old));
}
if (old == null) {
symbols.put(symbol, type);
}
return symbol;
}
public WindowNode window(WindowNode.Specification specification, Map<Symbol, WindowNode.Function> functions, PlanNode source)
{
return new WindowNode(
idAllocator.getNextId(),
source,
specification,
ImmutableMap.copyOf(functions),
Optional.empty(),
ImmutableSet.of(),
0);
}
public WindowNode window(WindowNode.Specification specification, Map<Symbol, WindowNode.Function> functions, Symbol hashSymbol, PlanNode source)
{
return new WindowNode(
idAllocator.getNextId(),
source,
specification,
ImmutableMap.copyOf(functions),
Optional.of(hashSymbol),
ImmutableSet.of(),
0);
}
public static Expression expression(String sql)
{
return ExpressionUtils.rewriteIdentifiersToSymbolReferences(new SqlParser().createExpression(sql));
}
public static List<Expression> expressions(String... expressions)
{
return Stream.of(expressions)
.map(PlanBuilder::expression)
.collect(toImmutableList());
}
public Map<Symbol, Type> getSymbols()
{
return Collections.unmodifiableMap(symbols);
}
}
| Fix formatting
| presto-main/src/test/java/com/facebook/presto/sql/planner/iterative/rule/test/PlanBuilder.java | Fix formatting |
|
Java | apache-2.0 | 7032d14c070a86bdcdc1c0099120437ce407f84f | 0 | dzungductran/blaster | /*
Copyright © 2015-2016 Dzung Tran ([email protected])
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.notalenthack.blaster;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.DialogFragment;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;
import com.notalenthack.blaster.dialog.EditCommandDialog;
import com.notalenthack.blaster.dialog.LaunchCommandDialog;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
/**
* Class that displays all the commands
*/
public class CommandActivity extends Activity implements EditCommandDialog.CommandCallback, View.OnClickListener {
private static final String TAG = "CommandActivity";
private static final boolean D = false;
private EdisonDevice mDevice;
// Broadcast receiver for receiving intents
private BroadcastReceiver mReceiver;
// fields in the layout
private TextView mModelName;
private TextView mCores;
private TextView mCacheSize;
private TextView mConnectStatus;
private ImageView mDeviceStatus;
private ImageView mBatteryStatus;
private ListView mCmdListView;
private Button mBtnExecAll;
private Activity mThisActivity;
private View mPrevSlideOut = null;
private CommandListAdapter mListAdapter;
private static BluetoothSerialService mSerialService = null;
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mThisActivity = this;
final Intent launchingIntent = getIntent();
// Retrieve the Query Type and Position from the intent or bundle
if (savedInstanceState != null) {
mDevice = savedInstanceState.getParcelable(Constants.KEY_DEVICE_STATE);
} else if (launchingIntent != null) {
mDevice = launchingIntent.getParcelableExtra(Constants.KEY_DEVICE_STATE);
}
setContentView(R.layout.commands);
// get the fields
mModelName = (TextView) findViewById(R.id.modelName);
mCores = (TextView) findViewById(R.id.cores);
mCacheSize = (TextView) findViewById(R.id.cacheSize);
mConnectStatus = (TextView) findViewById(R.id.status);
mDeviceStatus = (ImageView) findViewById(R.id.deviceStatusIcon);
mBatteryStatus = (ImageView) findViewById(R.id.batteryStatus);
mCmdListView = (ListView) findViewById(R.id.listView);;
mBtnExecAll = (Button)findViewById(R.id.btnExecAll);
if (mDevice != null) {
getActionBar().setHomeButtonEnabled(true);
getActionBar().setIcon(R.drawable.ic_action_navigation_previous_item);
mSerialService = new BluetoothSerialService(this, mHandlerBT);
mSerialService.connect(mDevice.getBluetoothDevice());
// Execute all the commands
mBtnExecAll.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// do a quick status update on the commands
List<Command> commands = mListAdapter.getCommands();
// this list should be in the same order as in the ListBox
for (Command cmd : commands) {
if (!cmd.getCommandStart().equalsIgnoreCase(Command.OBEX_FTP_START)) {
String outType = Constants.SERIAL_TYPE_STDERR;
if (cmd.getDisplayOutput()) {
outType = Constants.SERIAL_TYPE_STDOUT_ERR; // capture stdout+stderr
}
mSerialService.sendCommand(Constants.SERIAL_CMD_START,
cmd.getCommandStart(), outType);
}
}
}
});
setupCommandList();
} else {
Log.e(TAG, "Bluetooth device is not initialized");
finish();
}
}
private void setupCommandList() {
mListAdapter = new CommandListAdapter(this);
// read from storage and initialze the adapter.
restoreCommands();
mCmdListView.setAdapter(mListAdapter);
mCmdListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
handlePlayCommand(position);
}
});
// do a quick status update on the commands
List<Command> commands = mListAdapter.getCommands();
// this list should be in the same order as in the ListBox
int i = 0;
for (Command cmd : commands) {
mSerialService.sendStatusCommand(cmd.getCommandStat(), i, true);
i++;
}
}
// The Handler that gets information back from the BluetoothService
private final Handler mHandlerBT = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case Constants.MESSAGE_STATE_CHANGE_CMD:
if (D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
switch (msg.arg1) {
case BluetoothSerialService.STATE_CONNECTING:
mDeviceStatus.setImageResource(R.drawable.ic_bluetooth_paired);
mConnectStatus.setText(R.string.connecting);
break;
case BluetoothSerialService.STATE_CONNECTED:
mDeviceStatus.setImageResource(R.drawable.ic_bluetooth_connected);
mConnectStatus.setText(R.string.connected);
// connected, so ask for CPU Info
mSerialService.sendCommand(Constants.SERIAL_CMD_CPU_INFO);
break;
case BluetoothSerialService.STATE_NONE:
//case BluetoothSerialService.STATE_CANTCONNECT:
mDeviceStatus.setImageResource(R.drawable.ic_bluetooth_disabled);
mConnectStatus.setText(R.string.none);
break;
}
break;
case Constants.MESSAGE_WRITE_CMD:
// data is in
if (D) {
byte[] writeBuf = (byte[]) msg.obj;
Log.d(TAG, "write data: " + writeBuf);
}
break;
case Constants.MESSAGE_READ_CMD:
if (D) {
Log.d(TAG, "read data: " + msg.obj);
}
break;
// command coming back from device
case Constants.MESSAGE_DEVICE_SERIAL_CMD:
String jsonStr = msg.getData().getString(Constants.KEY_JSON_STR);
try {
JSONObject jsonObject = new JSONObject(jsonStr);
int cmd = jsonObject.getInt(Constants.KEY_COMMAND_TYPE);
switch (cmd) {
case Constants.SERIAL_CMD_ERROR:
String errStr = jsonObject.getString(Constants.KEY_TOAST);
Toast.makeText(getApplicationContext(), errStr, Toast.LENGTH_SHORT).show();
break;
case Constants.SERIAL_CMD_CLOSE:
finish(); // assuming that onDestroy is called to clean up
break;
case Constants.SERIAL_CMD_STATUS:
int percent = jsonObject.getInt(Constants.KEY_PERCENT);
int id = jsonObject.getInt(Constants.KEY_IDENTIFIER);
String state = jsonObject.getString(Constants.KEY_PROCESS_STATE);
boolean quick = jsonObject.getInt(Constants.KEY_QUICK_STATUS) == 1 ? true : false;
if (!quick) {
mListAdapter.updateCpuUsage(id, percent);
}
mListAdapter.updateStatus(id, getStatusFromState(state));
mListAdapter.notifyDataSetChanged();
break;
case Constants.SERIAL_CMD_CPU_INFO:
String modelName = jsonObject.getString(Constants.KEY_MODEL_NAME);
int cores = jsonObject.getInt(Constants.KEY_CPU_CORES);
String cacheSize = jsonObject.getString(Constants.KEY_CACHE_SIZE);
mModelName.setText(modelName);
mCores.setText(cores + " cores");
mCacheSize.setText(cacheSize + " cache");
break;
}
} catch (JSONException ex) {
Log.e(TAG, "Invalid JSON " + ex.getMessage());
Toast.makeText(getApplicationContext(),
"Invalid JSON commadn from device " + ex.getMessage(), Toast.LENGTH_LONG).show();
}
break;
case Constants.MESSAGE_DEVICE_NAME_CMD:
// save the connected device's name
String deviceName = msg.getData().getString(Constants.KEY_DEVICE_NAME);
Toast.makeText(getApplicationContext(), getString(R.string.toast_connected_to) + " "
+ deviceName, Toast.LENGTH_SHORT).show();
break;
case Constants.MESSAGE_TOAST_CMD:
Toast.makeText(getApplicationContext(),
msg.getData().getString(Constants.KEY_TOAST), Toast.LENGTH_LONG).show();
break;
}
}
};
@Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
if (mDevice != null) {
savedInstanceState.putParcelable(Constants.KEY_DEVICE_STATE, mDevice);
}
super.onSaveInstanceState(savedInstanceState);
}
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mDevice = savedInstanceState.getParcelable(Constants.KEY_DEVICE_STATE);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.add_command, menu);
// Calling super after populating the menu is necessary here to ensure that the
// action bar helpers have a chance to handle this event.
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
mSerialService.sendCommand(Constants.SERIAL_CMD_CLOSE);
mSerialService.stop();
finish();
} else if (item.getItemId() == R.id.menu_add_command) {
Command cmd = new Command();
editCommand(cmd);
}
return super.onOptionsItemSelected(item);
}
@Override
public synchronized void onResume() {
super.onResume();
if (mSerialService != null) {
// Only if the state is STATE_NONE, do we know that we haven't started already
if (mSerialService.getState() == BluetoothSerialService.STATE_NONE) {
// Start the Bluetooth services
mSerialService.start();
}
}
setupFilter();
startStatusUpdate();
}
@Override
protected void onDestroy() {
super.onDestroy();
cancelStatusUpdate();
if (mReceiver != null)
unregisterReceiver(mReceiver);
mReceiver = null;
if (mSerialService != null)
mSerialService.stop();
}
public void send(byte[] out) {
out = Utils.handleEndOfLineChars(out);
if (out.length > 0) {
mSerialService.write(out);
}
}
/* Mapping Linux state to our Enum status
* http://man7.org/linux/man-pages/man5/proc.5.html
*
* R Running
* S Sleeping in an interruptible wait
* D Waiting in uninterruptible disk sleep
* Z Zombie
* T Stopped (on a signal) or (before Linux 2.6.33) trace stopped
* t Tracing stop (Linux 2.6.33 onward)
* X Dead (from Linux 2.6.0 onward)
*/
private Command.Status getStatusFromState(String state) {
// only care about R, S, Z
byte[] s = state.getBytes();
switch (s[0]) {
case 'R': return Command.Status.RUNNING;
case 'S': return Command.Status.SLEEPING;
case 'Z': return Command.Status.ZOMBIE;
default: return Command.Status.NOT_RUNNING;
}
}
private void editCommand(Command command) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
Fragment prev = getFragmentManager().findFragmentByTag(EditCommandDialog.TAG_EDIT_COMMAND_DIALOG);
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
// Create and show the dialog.
DialogFragment newFragment = EditCommandDialog.newInstance(command, this);
newFragment.show(ft, EditCommandDialog.TAG_EDIT_COMMAND_DIALOG);
}
private void launchCommand() {
FragmentTransaction ft = getFragmentManager().beginTransaction();
Fragment prev = getFragmentManager().findFragmentByTag(LaunchCommandDialog.TAG_LAUNCH_DIALOG);
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
// Create and show the dialog.
DialogFragment newFragment = LaunchCommandDialog.newInstance();
newFragment.show(ft, LaunchCommandDialog.TAG_LAUNCH_DIALOG);
}
@Override
public void onClick(View v) {
Integer position = (Integer) v.getTag();
if (v.getId() == R.id.btnEditCommand) {
final Command cmd = mListAdapter.getCommand(position);
Log.d(TAG, "Edit button click for position " + position);
//Creating the instance of PopupMenu
PopupMenu popup = new PopupMenu(this, v);
//Inflating the Popup using xml file
popup.getMenuInflater().inflate(R.menu.edit_delete, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
if (item.getItemId() == R.id.edit) {
editCommand(cmd);
} else if (item.getItemId() == R.id.delete) {
mListAdapter.deleteCommand(cmd);
} else {
return false;
}
saveCommands(); // update commands in pref for presistent
mListAdapter.notifyDataSetChanged();
return true;
}
});
// show the popup
popup.show();
} else if (v.getId() == R.id.btnCommandAction) {
Log.d(TAG, "Play button click for position " + position);
handlePlayCommand(position);
}
}
// Callback when a command is created
public void newCommand(Command command, boolean bNew) {
if (D) Log.d(TAG, "command is done " + command.getName());
if (bNew) {
mListAdapter.addCommand(1, command);
}
mListAdapter.notifyDataSetChanged();
saveCommands();
}
private void handlePlayCommand(int position) {
Command command = mListAdapter.getCommand(position);
if (command != null) {
if (D) Log.d(TAG, "command " + command.getCommandStart());
if (command.getCommandStart().equalsIgnoreCase(Command.OBEX_FTP_START)) {
Intent launchingIntent = new Intent(mThisActivity, FileListActivity.class);
launchingIntent.putExtra(Constants.KEY_DEVICE_STATE, mDevice);
if (D) Log.d(TAG, "Launch file list screen: " + mDevice.getName());
startActivity(launchingIntent);
} else {
Command.Status status = command.getStatus();
String outType = Constants.SERIAL_TYPE_STDERR;
if (command.getDisplayOutput()) {
outType = Constants.SERIAL_TYPE_STDOUT_ERR; // capture stdout+stderr
}
if (status == Command.Status.NOT_RUNNING) {
mSerialService.sendCommand(Constants.SERIAL_CMD_START,
handleFileSubstitution(command.getCommandStart()), outType);
} else if (status == Command.Status.ZOMBIE) {
mSerialService.sendCommand(Constants.SERIAL_CMD_KILL,
command.getCommandStart(), outType);
} else if (status == Command.Status.RUNNING || status == Command.Status.SLEEPING) {
if (command.getCommandStop().isEmpty()) {
if (command.getKillMethod() == Command.KillMethod.TERMINATE) {
mSerialService.sendCommand(Constants.SERIAL_CMD_TERM,
command.getCommandStart(), outType);
} else if (command.getKillMethod() == Command.KillMethod.KILL) {
mSerialService.sendCommand(Constants.SERIAL_CMD_KILL,
command.getCommandStart(), outType);
} else {
Toast.makeText(getApplicationContext(), "Unknown stop command: "
+ command.getKillMethod(), Toast.LENGTH_SHORT).show();
}
} else {
mSerialService.sendCommand(Constants.SERIAL_CMD_START,
command.getCommandStop(), outType);
}
} else {
Toast.makeText(getApplicationContext(), "Unknown command state: "
+ status, Toast.LENGTH_SHORT).show();
return;
}
mSerialService.sendStatusCommand(command.getCommandStat(), position, true);
}
}
}
// Setup receiver to get message from alarm
private void setupFilter() {
final IntentFilter filter = new IntentFilter();
filter.addAction(Constants.ACTION_REFRESH_STATUS);
mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Got intent to clean up
if (intent.getAction().equals(Constants.ACTION_REFRESH_STATUS)) {
if (D) Log.d(TAG, "onReceive intent " + intent.toString());
List<Command> commands = mListAdapter.getCommands();
// this list should be in the same order as in the ListBox
int i=0;
for (Command cmd : commands) {
if (cmd.getDisplayStatus()) {
mSerialService.sendStatusCommand(cmd.getCommandStat(), i, false);
}
i++;
}
}
}
};
registerReceiver(mReceiver, filter);
}
private String handleFileSubstitution(String command) {
if (command.contains("%f")) {
return command.replace("%f", getTimeStamp(new Date()));
} else {
return command;
}
}
private String getTimeStamp(Date date) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
return simpleDateFormat.format(date);
}
private void startStatusUpdate() {
// Setup expiration if we never get a message from the service
AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent();
intent.setAction(Constants.ACTION_REFRESH_STATUS);
PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Set repeating updating of status, will need to cancel if activity is gone
Calendar cal = Calendar.getInstance();
am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
Constants.UPATE_STATUS_PERIOD * 1000, pi);
}
private void cancelStatusUpdate() {
// Setup expiration if we never get a message from the service
AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent();
intent.setAction(Constants.ACTION_REFRESH_STATUS);
PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
am.cancel(pi);
}
private void saveCommands() {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(mDevice.getAddress(), mListAdapter.getCommandsAsJSONArray().toString());
editor.commit();
}
private void restoreCommands() {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
// Get the stored command
String jsonArrStr = preferences.getString(mDevice.getAddress(), getDefaultCommands().toString());
try {
JSONArray jsonArray = new JSONArray(jsonArrStr);
int len = jsonArray.length();
for(int i = 0; i < len; ++i) {
JSONObject json = jsonArray.getJSONObject(i);
Command command = new Command(json);
command.setStatus(Command.Status.NOT_RUNNING);
command.setCpuUsage(0);
mListAdapter.addCommand(command);
}
} catch (JSONException ex) {
Log.e(TAG, "Bad JSON " + ex.getMessage());
}
}
// default set of commands
private JSONArray getDefaultCommands() {
Command cmd;
JSONArray jsonArray = new JSONArray();
try {
cmd = new Command("Download files", R.drawable.ic_sample_3, Command.OBEX_FTP_START,
Command.OBEX_FTP_STOP, Command.KillMethod.NONE, Command.OBEX_FTP_STAT, false, true, true);
jsonArray.put(cmd.toJSON());
cmd = new Command("Video recording", R.drawable.ic_sample_10, "/bin/ls %f.mp4",
"", Command.KillMethod.TERMINATE, "", false, false, false);
jsonArray.put(cmd.toJSON());
cmd = new Command("Record GPS data", R.drawable.ic_sample_8, Command.LSM9DS0_START,
Command.LSM9DS0_STOP, Command.KillMethod.NONE, Command.LSM9DS0_STAT, false, false, false);
jsonArray.put(cmd.toJSON());
cmd = new Command("Launch Rocket", R.drawable.ic_launcher, Command.LAUNCHER_START,
Command.LAUNCHER_STOP, Command.KillMethod.NONE, Command.LAUNCHER_STAT, false, false, false);
jsonArray.put(cmd.toJSON());
} catch (JSONException ex) {
Log.e(TAG, "Bad JSON object " + ex.toString());
return null;
}
return jsonArray;
}
} | app/src/main/java/com/notalenthack/blaster/CommandActivity.java | /*
Copyright © 2015-2016 Dzung Tran ([email protected])
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.notalenthack.blaster;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.DialogFragment;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;
import com.notalenthack.blaster.dialog.EditCommandDialog;
import com.notalenthack.blaster.dialog.LaunchCommandDialog;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Calendar;
import java.util.List;
/**
* Class that displays all the commands
*/
public class CommandActivity extends Activity implements EditCommandDialog.CommandCallback, View.OnClickListener {
private static final String TAG = "CommandActivity";
private static final boolean D = false;
private EdisonDevice mDevice;
// Broadcast receiver for receiving intents
private BroadcastReceiver mReceiver;
// fields in the layout
private TextView mModelName;
private TextView mCores;
private TextView mCacheSize;
private TextView mConnectStatus;
private ImageView mDeviceStatus;
private ImageView mBatteryStatus;
private ListView mCmdListView;
private Button mBtnExecAll;
private Activity mThisActivity;
private View mPrevSlideOut = null;
private CommandListAdapter mListAdapter;
private static BluetoothSerialService mSerialService = null;
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mThisActivity = this;
final Intent launchingIntent = getIntent();
// Retrieve the Query Type and Position from the intent or bundle
if (savedInstanceState != null) {
mDevice = savedInstanceState.getParcelable(Constants.KEY_DEVICE_STATE);
} else if (launchingIntent != null) {
mDevice = launchingIntent.getParcelableExtra(Constants.KEY_DEVICE_STATE);
}
setContentView(R.layout.commands);
// get the fields
mModelName = (TextView) findViewById(R.id.modelName);
mCores = (TextView) findViewById(R.id.cores);
mCacheSize = (TextView) findViewById(R.id.cacheSize);
mConnectStatus = (TextView) findViewById(R.id.status);
mDeviceStatus = (ImageView) findViewById(R.id.deviceStatusIcon);
mBatteryStatus = (ImageView) findViewById(R.id.batteryStatus);
mCmdListView = (ListView) findViewById(R.id.listView);;
mBtnExecAll = (Button)findViewById(R.id.btnExecAll);
if (mDevice != null) {
getActionBar().setHomeButtonEnabled(true);
getActionBar().setIcon(R.drawable.ic_action_navigation_previous_item);
mSerialService = new BluetoothSerialService(this, mHandlerBT);
mSerialService.connect(mDevice.getBluetoothDevice());
// Execute all the commands
mBtnExecAll.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// do a quick status update on the commands
List<Command> commands = mListAdapter.getCommands();
// this list should be in the same order as in the ListBox
for (Command cmd : commands) {
if (!cmd.getCommandStart().equalsIgnoreCase(Command.OBEX_FTP_START)) {
String outType = Constants.SERIAL_TYPE_STDERR;
if (cmd.getDisplayOutput()) {
outType = Constants.SERIAL_TYPE_STDOUT_ERR; // capture stdout+stderr
}
mSerialService.sendCommand(Constants.SERIAL_CMD_START,
cmd.getCommandStart(), outType);
}
}
}
});
setupCommandList();
} else {
Log.e(TAG, "Bluetooth device is not initialized");
finish();
}
}
private void setupCommandList() {
mListAdapter = new CommandListAdapter(this);
// read from storage and initialze the adapter.
restoreCommands();
mCmdListView.setAdapter(mListAdapter);
mCmdListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
handlePlayCommand(position);
}
});
// do a quick status update on the commands
List<Command> commands = mListAdapter.getCommands();
// this list should be in the same order as in the ListBox
int i = 0;
for (Command cmd : commands) {
mSerialService.sendStatusCommand(cmd.getCommandStat(), i, true);
i++;
}
}
// The Handler that gets information back from the BluetoothService
private final Handler mHandlerBT = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case Constants.MESSAGE_STATE_CHANGE_CMD:
if (D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
switch (msg.arg1) {
case BluetoothSerialService.STATE_CONNECTING:
mDeviceStatus.setImageResource(R.drawable.ic_bluetooth_paired);
mConnectStatus.setText(R.string.connecting);
break;
case BluetoothSerialService.STATE_CONNECTED:
mDeviceStatus.setImageResource(R.drawable.ic_bluetooth_connected);
mConnectStatus.setText(R.string.connected);
// connected, so ask for CPU Info
mSerialService.sendCommand(Constants.SERIAL_CMD_CPU_INFO);
break;
case BluetoothSerialService.STATE_NONE:
//case BluetoothSerialService.STATE_CANTCONNECT:
mDeviceStatus.setImageResource(R.drawable.ic_bluetooth_disabled);
mConnectStatus.setText(R.string.none);
break;
}
break;
case Constants.MESSAGE_WRITE_CMD:
// data is in
if (D) {
byte[] writeBuf = (byte[]) msg.obj;
Log.d(TAG, "write data: " + writeBuf);
}
break;
case Constants.MESSAGE_READ_CMD:
if (D) {
Log.d(TAG, "read data: " + msg.obj);
}
break;
// command coming back from device
case Constants.MESSAGE_DEVICE_SERIAL_CMD:
String jsonStr = msg.getData().getString(Constants.KEY_JSON_STR);
try {
JSONObject jsonObject = new JSONObject(jsonStr);
int cmd = jsonObject.getInt(Constants.KEY_COMMAND_TYPE);
switch (cmd) {
case Constants.SERIAL_CMD_ERROR:
String errStr = jsonObject.getString(Constants.KEY_TOAST);
Toast.makeText(getApplicationContext(), errStr, Toast.LENGTH_SHORT).show();
break;
case Constants.SERIAL_CMD_CLOSE:
finish(); // assuming that onDestroy is called to clean up
break;
case Constants.SERIAL_CMD_STATUS:
int percent = jsonObject.getInt(Constants.KEY_PERCENT);
int id = jsonObject.getInt(Constants.KEY_IDENTIFIER);
String state = jsonObject.getString(Constants.KEY_PROCESS_STATE);
boolean quick = jsonObject.getInt(Constants.KEY_QUICK_STATUS) == 1 ? true : false;
if (!quick) {
mListAdapter.updateCpuUsage(id, percent);
}
mListAdapter.updateStatus(id, getStatusFromState(state));
mListAdapter.notifyDataSetChanged();
break;
case Constants.SERIAL_CMD_CPU_INFO:
String modelName = jsonObject.getString(Constants.KEY_MODEL_NAME);
int cores = jsonObject.getInt(Constants.KEY_CPU_CORES);
String cacheSize = jsonObject.getString(Constants.KEY_CACHE_SIZE);
mModelName.setText(modelName);
mCores.setText(cores + " cores");
mCacheSize.setText(cacheSize + " cache");
break;
}
} catch (JSONException ex) {
Log.e(TAG, "Invalid JSON " + ex.getMessage());
Toast.makeText(getApplicationContext(),
"Invalid JSON commadn from device " + ex.getMessage(), Toast.LENGTH_LONG).show();
}
break;
case Constants.MESSAGE_DEVICE_NAME_CMD:
// save the connected device's name
String deviceName = msg.getData().getString(Constants.KEY_DEVICE_NAME);
Toast.makeText(getApplicationContext(), getString(R.string.toast_connected_to) + " "
+ deviceName, Toast.LENGTH_SHORT).show();
break;
case Constants.MESSAGE_TOAST_CMD:
Toast.makeText(getApplicationContext(),
msg.getData().getString(Constants.KEY_TOAST), Toast.LENGTH_LONG).show();
break;
}
}
};
@Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
if (mDevice != null) {
savedInstanceState.putParcelable(Constants.KEY_DEVICE_STATE, mDevice);
}
super.onSaveInstanceState(savedInstanceState);
}
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mDevice = savedInstanceState.getParcelable(Constants.KEY_DEVICE_STATE);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.add_command, menu);
// Calling super after populating the menu is necessary here to ensure that the
// action bar helpers have a chance to handle this event.
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
mSerialService.sendCommand(Constants.SERIAL_CMD_CLOSE);
mSerialService.stop();
finish();
} else if (item.getItemId() == R.id.menu_add_command) {
Command cmd = new Command();
editCommand(cmd);
}
return super.onOptionsItemSelected(item);
}
@Override
public synchronized void onResume() {
super.onResume();
if (mSerialService != null) {
// Only if the state is STATE_NONE, do we know that we haven't started already
if (mSerialService.getState() == BluetoothSerialService.STATE_NONE) {
// Start the Bluetooth services
mSerialService.start();
}
}
setupFilter();
startStatusUpdate();
}
@Override
protected void onDestroy() {
super.onDestroy();
cancelStatusUpdate();
if (mReceiver != null)
unregisterReceiver(mReceiver);
mReceiver = null;
if (mSerialService != null)
mSerialService.stop();
}
public void send(byte[] out) {
out = Utils.handleEndOfLineChars(out);
if (out.length > 0) {
mSerialService.write(out);
}
}
/* Mapping Linux state to our Enum status
* http://man7.org/linux/man-pages/man5/proc.5.html
*
* R Running
* S Sleeping in an interruptible wait
* D Waiting in uninterruptible disk sleep
* Z Zombie
* T Stopped (on a signal) or (before Linux 2.6.33) trace stopped
* t Tracing stop (Linux 2.6.33 onward)
* X Dead (from Linux 2.6.0 onward)
*/
private Command.Status getStatusFromState(String state) {
// only care about R, S, Z
byte[] s = state.getBytes();
switch (s[0]) {
case 'R': return Command.Status.RUNNING;
case 'S': return Command.Status.SLEEPING;
case 'Z': return Command.Status.ZOMBIE;
default: return Command.Status.NOT_RUNNING;
}
}
private void editCommand(Command command) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
Fragment prev = getFragmentManager().findFragmentByTag(EditCommandDialog.TAG_EDIT_COMMAND_DIALOG);
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
// Create and show the dialog.
DialogFragment newFragment = EditCommandDialog.newInstance(command, this);
newFragment.show(ft, EditCommandDialog.TAG_EDIT_COMMAND_DIALOG);
}
private void launchCommand() {
FragmentTransaction ft = getFragmentManager().beginTransaction();
Fragment prev = getFragmentManager().findFragmentByTag(LaunchCommandDialog.TAG_LAUNCH_DIALOG);
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
// Create and show the dialog.
DialogFragment newFragment = LaunchCommandDialog.newInstance();
newFragment.show(ft, LaunchCommandDialog.TAG_LAUNCH_DIALOG);
}
@Override
public void onClick(View v) {
Integer position = (Integer) v.getTag();
if (v.getId() == R.id.btnEditCommand) {
final Command cmd = mListAdapter.getCommand(position);
Log.d(TAG, "Edit button click for position " + position);
//Creating the instance of PopupMenu
PopupMenu popup = new PopupMenu(this, v);
//Inflating the Popup using xml file
popup.getMenuInflater().inflate(R.menu.edit_delete, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
if (item.getItemId() == R.id.edit) {
editCommand(cmd);
} else if (item.getItemId() == R.id.delete) {
mListAdapter.deleteCommand(cmd);
} else {
return false;
}
saveCommands(); // update commands in pref for presistent
mListAdapter.notifyDataSetChanged();
return true;
}
});
// show the popup
popup.show();
} else if (v.getId() == R.id.btnCommandAction) {
Log.d(TAG, "Play button click for position " + position);
handlePlayCommand(position);
}
}
// Callback when a command is created
public void newCommand(Command command, boolean bNew) {
if (D) Log.d(TAG, "command is done " + command.getName());
if (bNew) {
mListAdapter.addCommand(1, command);
}
mListAdapter.notifyDataSetChanged();
saveCommands();
}
private void handlePlayCommand(int position) {
Command command = mListAdapter.getCommand(position);
if (command != null) {
if (D) Log.d(TAG, "command " + command.getCommandStart());
if (command.getCommandStart().equalsIgnoreCase(Command.OBEX_FTP_START)) {
Intent launchingIntent = new Intent(mThisActivity, FileListActivity.class);
launchingIntent.putExtra(Constants.KEY_DEVICE_STATE, mDevice);
if (D) Log.d(TAG, "Launch file list screen: " + mDevice.getName());
startActivity(launchingIntent);
} else {
Command.Status status = command.getStatus();
String outType = Constants.SERIAL_TYPE_STDERR;
if (command.getDisplayOutput()) {
outType = Constants.SERIAL_TYPE_STDOUT_ERR; // capture stdout+stderr
}
if (status == Command.Status.NOT_RUNNING) {
mSerialService.sendCommand(Constants.SERIAL_CMD_START,
command.getCommandStart(), outType);
} else if (status == Command.Status.ZOMBIE) {
mSerialService.sendCommand(Constants.SERIAL_CMD_KILL,
command.getCommandStart(), outType);
} else if (status == Command.Status.RUNNING || status == Command.Status.SLEEPING) {
if (command.getCommandStop().isEmpty()) {
if (command.getKillMethod() == Command.KillMethod.TERMINATE) {
mSerialService.sendCommand(Constants.SERIAL_CMD_TERM,
command.getCommandStart(), outType);
} else if (command.getKillMethod() == Command.KillMethod.KILL) {
mSerialService.sendCommand(Constants.SERIAL_CMD_KILL,
command.getCommandStart(), outType);
} else {
Toast.makeText(getApplicationContext(), "Unknown stop command: "
+ command.getKillMethod(), Toast.LENGTH_SHORT).show();
}
} else {
mSerialService.sendCommand(Constants.SERIAL_CMD_START,
command.getCommandStop(), outType);
}
} else {
Toast.makeText(getApplicationContext(), "Unknown command state: "
+ status, Toast.LENGTH_SHORT).show();
return;
}
mSerialService.sendStatusCommand(command.getCommandStat(), position, true);
}
}
}
// Setup receiver to get message from alarm
private void setupFilter() {
final IntentFilter filter = new IntentFilter();
filter.addAction(Constants.ACTION_REFRESH_STATUS);
mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Got intent to clean up
if (intent.getAction().equals(Constants.ACTION_REFRESH_STATUS)) {
if (D) Log.d(TAG, "onReceive intent " + intent.toString());
List<Command> commands = mListAdapter.getCommands();
// this list should be in the same order as in the ListBox
int i=0;
for (Command cmd : commands) {
if (cmd.getDisplayStatus()) {
mSerialService.sendStatusCommand(cmd.getCommandStat(), i, false);
}
i++;
}
}
}
};
registerReceiver(mReceiver, filter);
}
private void startStatusUpdate() {
// Setup expiration if we never get a message from the service
AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent();
intent.setAction(Constants.ACTION_REFRESH_STATUS);
PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Set repeating updating of status, will need to cancel if activity is gone
Calendar cal = Calendar.getInstance();
am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
Constants.UPATE_STATUS_PERIOD * 1000, pi);
}
private void cancelStatusUpdate() {
// Setup expiration if we never get a message from the service
AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent();
intent.setAction(Constants.ACTION_REFRESH_STATUS);
PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
am.cancel(pi);
}
private void saveCommands() {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(mDevice.getAddress(), mListAdapter.getCommandsAsJSONArray().toString());
editor.commit();
}
private void restoreCommands() {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
// Get the stored command
String jsonArrStr = preferences.getString(mDevice.getAddress(), getDefaultCommands().toString());
try {
JSONArray jsonArray = new JSONArray(jsonArrStr);
int len = jsonArray.length();
for(int i = 0; i < len; ++i) {
JSONObject json = jsonArray.getJSONObject(i);
Command command = new Command(json);
command.setStatus(Command.Status.NOT_RUNNING);
command.setCpuUsage(0);
mListAdapter.addCommand(command);
}
} catch (JSONException ex) {
Log.e(TAG, "Bad JSON " + ex.getMessage());
}
}
// default set of commands
private JSONArray getDefaultCommands() {
Command cmd;
JSONArray jsonArray = new JSONArray();
try {
cmd = new Command("Download files", R.drawable.ic_sample_3, Command.OBEX_FTP_START,
Command.OBEX_FTP_STOP, Command.KillMethod.NONE, Command.OBEX_FTP_STAT, false, true, true);
jsonArray.put(cmd.toJSON());
cmd = new Command("Video recording", R.drawable.ic_sample_10, "/bin/ls",
"", Command.KillMethod.TERMINATE, "", false, false, false);
jsonArray.put(cmd.toJSON());
cmd = new Command("Record GPS data", R.drawable.ic_sample_8, Command.LSM9DS0_START,
Command.LSM9DS0_STOP, Command.KillMethod.NONE, Command.LSM9DS0_STAT, false, false, false);
jsonArray.put(cmd.toJSON());
cmd = new Command("Launch Rocket", R.drawable.ic_launcher, Command.LAUNCHER_START,
Command.LAUNCHER_STOP, Command.KillMethod.NONE, Command.LAUNCHER_STAT, false, false, false);
jsonArray.put(cmd.toJSON());
} catch (JSONException ex) {
Log.e(TAG, "Bad JSON object " + ex.toString());
return null;
}
return jsonArray;
}
} | Handle file substituion for %f = time
| app/src/main/java/com/notalenthack/blaster/CommandActivity.java | Handle file substituion for %f = time |
|
Java | apache-2.0 | 9e17e36f2fe6bd1a5dd5280a8cc7eae2a13d0923 | 0 | hellojavaer/ddr,hellojavaer/ddal | /*
* Copyright 2016-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hellojavaer.ddal.ddr.datasource.security.metadata;
import org.hellojavaer.ddal.ddr.datasource.exception.IllegalMetaDataException;
import org.hellojavaer.ddal.ddr.utils.DDRJSONUtils;
import org.hellojavaer.ddal.ddr.utils.DDRStringUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
/**
*
* @author <a href="mailto:[email protected]">Kaiming Zou</a>,created on 25/12/2016.
*/
public class DefaultMetaDataChecker implements MetaDataChecker {
private static final String MYSQL_AND_ORACLE = "SELECT table_name FROM information_schema.tables WHERE table_schema = ? ";
private static final String SQL_SERVER = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_CATALOG = ? ";
private static final Map<String, String> map = new LinkedHashMap<String, String>();
/**
* 检查指定schema下是否包含指定的table
*
* @throws IllegalMetaDataException
*/
@Override
public void check(Connection conn, String scName, String tbName) throws IllegalMetaDataException {
if (scName == null) {
throw new IllegalArgumentException("[Check MetaData Failed] parameter 'scName' can't be null");
}
if (tbName == null) {
throw new IllegalArgumentException("[Check MetaData Failed] parameter 'tbName' can't be null");
}
try {
Set<String> set = getAllTables(conn, scName);
if (set == null || set.isEmpty()) {
throw new IllegalMetaDataException(
"[Check MetaData Failed] Schema:'"
+ scName
+ "' has nothing tables. but in your configuration it requires table:"
+ tbName);
}
if (!set.contains(tbName)) {
throw new IllegalMetaDataException("[Check MetaData Failed] Schema:'" + scName + "' only has tables:"
+ DDRJSONUtils.toJSONString(set)
+ ", but in your configuration it requires table:"
+ tbName);
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
private static Set<String> getAllTables(Connection conn, String scName) throws SQLException {
String sql = get(conn);
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, scName);
ResultSet rs = statement.executeQuery();
Set<String> tabs = new HashSet<>();
while (rs.next()) {
tabs.add(DDRStringUtils.toLowerCase(rs.getString(1)));
}
return tabs;
}
private static String get(Connection conn) {
String connPackage = conn.getClass().getPackage().getName();
if (connPackage.contains("mysql")) {
return MYSQL_AND_ORACLE;
} else if (connPackage.contains("oracle")) {
return MYSQL_AND_ORACLE;
} else if (connPackage.contains("sqlserver")) {
return SQL_SERVER;
} else {
for (Map.Entry<String, String> entry : map.entrySet()) {
if (connPackage.contains(entry.getKey())) {
return entry.getValue();
}
}
return MYSQL_AND_ORACLE;
}
}
public static void registerQueryMetaDataSQL(String keyWord, String sql) {
map.put(keyWord, sql);
}
}
| ddal-ddr/src/main/java/org/hellojavaer/ddal/ddr/datasource/security/metadata/DefaultMetaDataChecker.java | /*
* Copyright 2016-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hellojavaer.ddal.ddr.datasource.security.metadata;
import org.hellojavaer.ddal.ddr.datasource.exception.IllegalMetaDataException;
import org.hellojavaer.ddal.ddr.utils.DDRJSONUtils;
import org.hellojavaer.ddal.ddr.utils.DDRStringUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
/**
*
* @author <a href="mailto:[email protected]">Kaiming Zou</a>,created on 25/12/2016.
*/
public class DefaultMetaDataChecker implements MetaDataChecker {
private static final String MYSQL_AND_ORACLE = "SELECT table_name FROM information_schema.tables WHERE table_schema = ? ";
private static final String SQL_SERVER = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_CATALOG = ? ";
private static final Map<String, String> map = new LinkedHashMap<String, String>();
/**
* 检查指定schema下是否包含指定的table
*
* @throws IllegalMetaDataException
*/
@Override
public void check(Connection conn, String scName, String tbName) throws IllegalMetaDataException {
if(true){
return;
}
if (scName == null) {
throw new IllegalArgumentException("[Check MetaData Failed] parameter 'scName' can't be null");
}
if (tbName == null) {
throw new IllegalArgumentException("[Check MetaData Failed] parameter 'tbName' can't be null");
}
try {
Set<String> set = getAllTables(conn, scName);
if (set == null || set.isEmpty()) {
throw new IllegalMetaDataException(
"[Check MetaData Failed] Schema:'"
+ scName
+ "' has nothing tables. but in your configuration it requires table:"
+ tbName);
}
if (!set.contains(tbName)) {
throw new IllegalMetaDataException("[Check MetaData Failed] Schema:'" + scName + "' only has tables:"
+ DDRJSONUtils.toJSONString(set)
+ ", but in your configuration it requires table:"
+ tbName);
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
private static Set<String> getAllTables(Connection conn, String scName) throws SQLException {
String sql = get(conn);
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, scName);
ResultSet rs = statement.executeQuery();
Set<String> tabs = new HashSet<>();
while (rs.next()) {
tabs.add(DDRStringUtils.toLowerCase(rs.getString(1)));
}
return tabs;
}
private static String get(Connection conn) {
String connPackage = conn.getClass().getPackage().getName();
if (connPackage.contains("mysql")) {
return MYSQL_AND_ORACLE;
} else if (connPackage.contains("oracle")) {
return MYSQL_AND_ORACLE;
} else if (connPackage.contains("sqlserver")) {
return SQL_SERVER;
} else {
for (Map.Entry<String, String> entry : map.entrySet()) {
if (connPackage.contains(entry.getKey())) {
return entry.getValue();
}
}
return MYSQL_AND_ORACLE;
}
}
public static void registerQueryMetaDataSQL(String keyWord, String sql) {
map.put(keyWord, sql);
}
}
| update DefaultMetaDataChecker
| ddal-ddr/src/main/java/org/hellojavaer/ddal/ddr/datasource/security/metadata/DefaultMetaDataChecker.java | update DefaultMetaDataChecker |
|
Java | apache-2.0 | 8557717360429caa99418475f76a8a35ca5069df | 0 | SAP/cloud-odata-java,SAP/cloud-odata-java | package com.sap.core.odata.processor.jpa.access.api;
import java.util.List;
import com.sap.core.odata.api.edm.provider.Schema;
import com.sap.core.odata.processor.jpa.exception.ODataJPAModelException;
public interface JPAEdmBuilder {
public List<Schema> getSchemas( ) throws ODataJPAModelException;
/*public List<EntityType> getEntityTypes( ) throws ODataJPAModelException;
public EntityType getEntityType(FullQualifiedName fqName) throws ODataJPAModelException;
public EntitySet getEntitySet(FullQualifiedName fqName) throws ODataJPAModelException;*/
}
| com.sap.core.odata.processor/src/main/java/com/sap/core/odata/processor/jpa/access/api/JPAEdmBuilder.java | package com.sap.core.odata.processor.jpa.access.api;
import java.util.List;
import com.sap.core.odata.api.edm.FullQualifiedName;
import com.sap.core.odata.api.edm.provider.ComplexType;
import com.sap.core.odata.api.edm.provider.EntitySet;
import com.sap.core.odata.api.edm.provider.EntityType;
import com.sap.core.odata.api.edm.provider.Schema;
import com.sap.core.odata.processor.jpa.exception.ODataJPAModelException;
public interface JPAEdmBuilder {
public List<Schema> getSchemas( ) throws ODataJPAModelException;
public List<EntityType> getEntityTypes( ) throws ODataJPAModelException;
public EntityType getEntityType(FullQualifiedName fqName) throws ODataJPAModelException;
public EntitySet getEntitySet(FullQualifiedName fqName) throws ODataJPAModelException;
}
| JPA Edm Builder changes
Change-Id: Ifd7ef4cacc32c49485c671bc746b07e99612dbb0
Signed-off-by: Chandan V A <[email protected]>
| com.sap.core.odata.processor/src/main/java/com/sap/core/odata/processor/jpa/access/api/JPAEdmBuilder.java | JPA Edm Builder changes |
|
Java | apache-2.0 | 308c68dc936dd1bb8501861869ae4610b71d8fa6 | 0 | reactor/reactor-netty,reactor/reactor-netty | /*
* Copyright (c) 2011-2018 Pivotal Software Inc, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package reactor.ipc.netty.resources;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.Future;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.NonBlocking;
import reactor.ipc.netty.FutureMono;
/**
* An adapted global eventLoop handler.
*
* @since 0.6
*/
final class DefaultLoopResources extends AtomicLong implements LoopResources {
final String prefix;
final boolean daemon;
final int selectCount;
final int workerCount;
final EventLoopGroup serverLoops;
final EventLoopGroup clientLoops;
final EventLoopGroup serverSelectLoops;
final AtomicReference<EventLoopGroup> cacheNativeClientLoops;
final AtomicReference<EventLoopGroup> cacheNativeServerLoops;
final AtomicReference<EventLoopGroup> cacheNativeSelectLoops;
final AtomicBoolean running;
static ThreadFactory threadFactory(DefaultLoopResources parent, String prefix) {
return new EventLoopFactory(parent.daemon,
parent.prefix + "-" + prefix,
parent);
}
DefaultLoopResources(String prefix, int workerCount, boolean daemon) {
this(prefix, -1, workerCount, daemon);
}
DefaultLoopResources(String prefix,
int selectCount,
int workerCount,
boolean daemon) {
this.running = new AtomicBoolean(true);
this.daemon = daemon;
this.workerCount = workerCount;
this.prefix = prefix;
this.serverLoops = new NioEventLoopGroup(workerCount,
threadFactory(this, "nio"));
this.clientLoops = LoopResources.colocate(serverLoops);
this.cacheNativeClientLoops = new AtomicReference<>();
this.cacheNativeServerLoops = new AtomicReference<>();
if (selectCount == -1) {
this.selectCount = workerCount;
this.serverSelectLoops = this.serverLoops;
this.cacheNativeSelectLoops = this.cacheNativeServerLoops;
}
else {
this.selectCount = selectCount;
this.serverSelectLoops =
new NioEventLoopGroup(selectCount, threadFactory(this, "select-nio"));
this.cacheNativeSelectLoops = new AtomicReference<>();
}
}
@Override
public boolean isDisposed() {
return !running.get();
}
@SuppressWarnings("unchecked")
@Override
public Mono<Void> disposeLater() {
return Mono.defer(() -> {
EventLoopGroup cacheNativeClientGroup = cacheNativeClientLoops.get();
EventLoopGroup cacheNativeSelectGroup = cacheNativeSelectLoops.get();
EventLoopGroup cacheNativeServerGroup = cacheNativeServerLoops.get();
if(running.compareAndSet(true, false)) {
clientLoops.shutdownGracefully();
serverSelectLoops.shutdownGracefully();
serverLoops.shutdownGracefully();
if(cacheNativeClientGroup != null){
cacheNativeClientGroup.shutdownGracefully();
}
if(cacheNativeSelectGroup != null){
cacheNativeSelectGroup.shutdownGracefully();
}
if(cacheNativeServerGroup != null){
cacheNativeServerGroup.shutdownGracefully();
}
}
Mono<?> clMono = FutureMono.from((Future) clientLoops.terminationFuture());
Mono<?> sslMono = FutureMono.from((Future)serverSelectLoops.terminationFuture());
Mono<?> slMono = FutureMono.from((Future)serverLoops.terminationFuture());
Mono<?> cnclMono = Mono.empty();
if(cacheNativeClientGroup != null){
cnclMono = FutureMono.from((Future) cacheNativeClientGroup.terminationFuture());
}
Mono<?> cnslMono = Mono.empty();
if(cacheNativeSelectGroup != null){
cnslMono = FutureMono.from((Future) cacheNativeSelectGroup.terminationFuture());
}
Mono<?> cnsrvlMono = Mono.empty();
if(cacheNativeServerGroup != null){
cnsrvlMono = FutureMono.from((Future) cacheNativeServerGroup.terminationFuture());
}
return Mono.when(clMono, sslMono, slMono, cnclMono, cnslMono, cnsrvlMono);
});
}
@Override
public EventLoopGroup onServerSelect(boolean useNative) {
if (useNative && preferNative()) {
return cacheNativeSelectLoops();
}
return serverSelectLoops;
}
@Override
public EventLoopGroup onServer(boolean useNative) {
if (useNative && preferNative()) {
return cacheNativeServerLoops();
}
return serverLoops;
}
@Override
public EventLoopGroup onClient(boolean useNative) {
if (useNative && preferNative()) {
return cacheNativeClientLoops();
}
return clientLoops;
}
EventLoopGroup cacheNativeSelectLoops() {
if (cacheNativeSelectLoops == cacheNativeServerLoops) {
return cacheNativeServerLoops();
}
EventLoopGroup eventLoopGroup = cacheNativeSelectLoops.get();
if (null == eventLoopGroup) {
DefaultLoop defaultLoop = DefaultLoopNativeDetector.getInstance();
EventLoopGroup newEventLoopGroup = defaultLoop.newEventLoopGroup(
selectCount,
threadFactory(this, "select-" + defaultLoop.getName()));
if (!cacheNativeSelectLoops.compareAndSet(null, newEventLoopGroup)) {
newEventLoopGroup.shutdownGracefully();
}
eventLoopGroup = cacheNativeSelectLoops();
}
return eventLoopGroup;
}
EventLoopGroup cacheNativeServerLoops() {
EventLoopGroup eventLoopGroup = cacheNativeServerLoops.get();
if (null == eventLoopGroup) {
DefaultLoop defaultLoop = DefaultLoopNativeDetector.getInstance();
EventLoopGroup newEventLoopGroup = defaultLoop.newEventLoopGroup(
workerCount,
threadFactory(this, "server-" + defaultLoop.getName()));
if (!cacheNativeServerLoops.compareAndSet(null, newEventLoopGroup)) {
newEventLoopGroup.shutdownGracefully();
}
eventLoopGroup = cacheNativeServerLoops();
}
return eventLoopGroup;
}
EventLoopGroup cacheNativeClientLoops() {
EventLoopGroup eventLoopGroup = cacheNativeClientLoops.get();
if (null == eventLoopGroup) {
DefaultLoop defaultLoop = DefaultLoopNativeDetector.getInstance();
EventLoopGroup newEventLoopGroup = defaultLoop.newEventLoopGroup(
workerCount,
threadFactory(this, "client-" + defaultLoop.getName()));
newEventLoopGroup = LoopResources.colocate(newEventLoopGroup);
if (!cacheNativeClientLoops.compareAndSet(null, newEventLoopGroup)) {
newEventLoopGroup.shutdownGracefully();
}
eventLoopGroup = cacheNativeClientLoops();
}
return eventLoopGroup;
}
final static class EventLoopFactory implements ThreadFactory {
final boolean daemon;
final AtomicLong counter;
final String prefix;
EventLoopFactory(boolean daemon,
String prefix,
AtomicLong counter) {
this.daemon = daemon;
this.counter = counter;
this.prefix = prefix;
}
@Override
public Thread newThread(Runnable r) {
Thread t = new EventLoop(r);
t.setDaemon(daemon);
t.setName(prefix + "-" + counter.incrementAndGet());
return t;
}
}
final static class EventLoop extends Thread implements NonBlocking {
EventLoop(Runnable target) {
super(target);
}
}
}
| src/main/java/reactor/ipc/netty/resources/DefaultLoopResources.java | /*
* Copyright (c) 2011-2018 Pivotal Software Inc, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package reactor.ipc.netty.resources;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.Future;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.NonBlocking;
import reactor.ipc.netty.FutureMono;
/**
* An adapted global eventLoop handler.
*
* @since 0.6
*/
final class DefaultLoopResources extends AtomicLong implements LoopResources {
final String prefix;
final boolean daemon;
final int selectCount;
final int workerCount;
final EventLoopGroup serverLoops;
final EventLoopGroup clientLoops;
final EventLoopGroup serverSelectLoops;
final AtomicReference<EventLoopGroup> cacheNativeClientLoops;
final AtomicReference<EventLoopGroup> cacheNativeServerLoops;
final AtomicReference<EventLoopGroup> cacheNativeSelectLoops;
final AtomicBoolean running;
static ThreadFactory threadFactory(DefaultLoopResources parent, String prefix) {
return new EventLoopFactory(parent.daemon,
parent.prefix + "-" + prefix,
parent);
}
DefaultLoopResources(String prefix, int workerCount, boolean daemon) {
this(prefix, -1, workerCount, daemon);
}
DefaultLoopResources(String prefix,
int selectCount,
int workerCount,
boolean daemon) {
this.running = new AtomicBoolean(true);
this.daemon = daemon;
this.workerCount = workerCount;
this.prefix = prefix;
this.serverLoops = new NioEventLoopGroup(workerCount,
threadFactory(this, "nio"));
this.clientLoops = LoopResources.colocate(serverLoops);
this.cacheNativeClientLoops = new AtomicReference<>();
this.cacheNativeServerLoops = new AtomicReference<>();
if (selectCount == -1) {
this.selectCount = workerCount;
this.serverSelectLoops = this.serverLoops;
this.cacheNativeSelectLoops = this.cacheNativeServerLoops;
}
else {
this.selectCount = selectCount;
this.serverSelectLoops =
new NioEventLoopGroup(selectCount, threadFactory(this, "select-nio"));
this.cacheNativeSelectLoops = new AtomicReference<>();
}
}
@Override
public boolean isDisposed() {
return !running.get();
}
@Override
public Mono<Void> disposeLater() {
return Mono.defer(() -> {
EventLoopGroup cacheNativeClientGroup = cacheNativeClientLoops.get();
EventLoopGroup cacheNativeSelectGroup = cacheNativeSelectLoops.get();
EventLoopGroup cacheNativeServerGroup = cacheNativeServerLoops.get();
if(running.compareAndSet(true, false)) {
clientLoops.shutdownGracefully();
serverSelectLoops.shutdownGracefully();
serverLoops.shutdownGracefully();
if(cacheNativeClientGroup != null){
cacheNativeClientGroup.shutdownGracefully();
}
if(cacheNativeSelectGroup != null){
cacheNativeSelectGroup.shutdownGracefully();
}
if(cacheNativeServerGroup != null){
cacheNativeServerGroup.shutdownGracefully();
}
}
Mono<?> clMono = FutureMono.from((Future) clientLoops.terminationFuture());
Mono<?> sslMono = FutureMono.from((Future)serverSelectLoops.terminationFuture());
Mono<?> slMono = FutureMono.from((Future)serverLoops.terminationFuture());
Mono<?> cnclMono = Mono.empty();
if(cacheNativeClientGroup != null){
cnclMono = FutureMono.from((Future) cacheNativeClientGroup.terminationFuture());
}
Mono<?> cnslMono = Mono.empty();
if(cacheNativeSelectGroup != null){
cnslMono = FutureMono.from((Future) cacheNativeSelectGroup.terminationFuture());
}
Mono<?> cnsrvlMono = Mono.empty();
if(cacheNativeServerGroup != null){
cnsrvlMono = FutureMono.from((Future) cacheNativeServerGroup.terminationFuture());
}
return Mono.when(clMono, sslMono, slMono, cnclMono, cnslMono, cnsrvlMono);
});
}
@Override
public EventLoopGroup onServerSelect(boolean useNative) {
if (useNative && preferNative()) {
return cacheNativeSelectLoops();
}
return serverSelectLoops;
}
@Override
public EventLoopGroup onServer(boolean useNative) {
if (useNative && preferNative()) {
return cacheNativeServerLoops();
}
return serverLoops;
}
@Override
public EventLoopGroup onClient(boolean useNative) {
if (useNative && preferNative()) {
return cacheNativeClientLoops();
}
return clientLoops;
}
EventLoopGroup cacheNativeSelectLoops() {
if (cacheNativeSelectLoops == cacheNativeServerLoops) {
return cacheNativeServerLoops();
}
EventLoopGroup eventLoopGroup = cacheNativeSelectLoops.get();
if (null == eventLoopGroup) {
DefaultLoop defaultLoop = DefaultLoopNativeDetector.getInstance();
EventLoopGroup newEventLoopGroup = defaultLoop.newEventLoopGroup(
selectCount,
threadFactory(this, "select-" + defaultLoop.getName()));
if (!cacheNativeSelectLoops.compareAndSet(null, newEventLoopGroup)) {
newEventLoopGroup.shutdownGracefully();
}
eventLoopGroup = cacheNativeSelectLoops();
}
return eventLoopGroup;
}
EventLoopGroup cacheNativeServerLoops() {
EventLoopGroup eventLoopGroup = cacheNativeServerLoops.get();
if (null == eventLoopGroup) {
DefaultLoop defaultLoop = DefaultLoopNativeDetector.getInstance();
EventLoopGroup newEventLoopGroup = defaultLoop.newEventLoopGroup(
workerCount,
threadFactory(this, "server-" + defaultLoop.getName()));
if (!cacheNativeServerLoops.compareAndSet(null, newEventLoopGroup)) {
newEventLoopGroup.shutdownGracefully();
}
eventLoopGroup = cacheNativeServerLoops();
}
return eventLoopGroup;
}
EventLoopGroup cacheNativeClientLoops() {
EventLoopGroup eventLoopGroup = cacheNativeClientLoops.get();
if (null == eventLoopGroup) {
DefaultLoop defaultLoop = DefaultLoopNativeDetector.getInstance();
EventLoopGroup newEventLoopGroup = defaultLoop.newEventLoopGroup(
workerCount,
threadFactory(this, "client-" + defaultLoop.getName()));
newEventLoopGroup = LoopResources.colocate(newEventLoopGroup);
if (!cacheNativeClientLoops.compareAndSet(null, newEventLoopGroup)) {
newEventLoopGroup.shutdownGracefully();
}
eventLoopGroup = cacheNativeClientLoops();
}
return eventLoopGroup;
}
final static class EventLoopFactory implements ThreadFactory {
final boolean daemon;
final AtomicLong counter;
final String prefix;
EventLoopFactory(boolean daemon,
String prefix,
AtomicLong counter) {
this.daemon = daemon;
this.counter = counter;
this.prefix = prefix;
}
@Override
public Thread newThread(Runnable r) {
Thread t = new EventLoop(r);
t.setDaemon(daemon);
t.setName(prefix + "-" + counter.incrementAndGet());
return t;
}
}
final static class EventLoop extends Thread implements NonBlocking {
EventLoop(Runnable target) {
super(target);
}
}
}
| Suppress unchecked warnings in disposeLater method
| src/main/java/reactor/ipc/netty/resources/DefaultLoopResources.java | Suppress unchecked warnings in disposeLater method |
|
Java | apache-2.0 | 905ad4e28a0a0969e410d86c2bf2ee61455f1f6c | 0 | nknize/elasticsearch,gingerwizard/elasticsearch,gingerwizard/elasticsearch,GlenRSmith/elasticsearch,coding0011/elasticsearch,coding0011/elasticsearch,robin13/elasticsearch,scorpionvicky/elasticsearch,coding0011/elasticsearch,scorpionvicky/elasticsearch,gingerwizard/elasticsearch,nknize/elasticsearch,gingerwizard/elasticsearch,scorpionvicky/elasticsearch,gingerwizard/elasticsearch,scorpionvicky/elasticsearch,uschindler/elasticsearch,GlenRSmith/elasticsearch,uschindler/elasticsearch,HonzaKral/elasticsearch,robin13/elasticsearch,robin13/elasticsearch,uschindler/elasticsearch,nknize/elasticsearch,HonzaKral/elasticsearch,scorpionvicky/elasticsearch,HonzaKral/elasticsearch,nknize/elasticsearch,robin13/elasticsearch,uschindler/elasticsearch,HonzaKral/elasticsearch,robin13/elasticsearch,GlenRSmith/elasticsearch,coding0011/elasticsearch,GlenRSmith/elasticsearch,gingerwizard/elasticsearch,GlenRSmith/elasticsearch,gingerwizard/elasticsearch,coding0011/elasticsearch,nknize/elasticsearch,uschindler/elasticsearch | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.core.indexlifecycle;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.indices.rollover.RolloverRequest;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.ToXContentObject;
import org.elasticsearch.common.xcontent.XContentBuilder;
import java.io.IOException;
import java.util.Locale;
import java.util.Objects;
/**
* Waits for at least one rollover condition to be satisfied, using the Rollover API's dry_run option.
*/
public class WaitForRolloverReadyStep extends AsyncWaitStep {
private static final Logger logger = LogManager.getLogger(WaitForRolloverReadyStep.class);
public static final String NAME = "check-rollover-ready";
private final ByteSizeValue maxSize;
private final TimeValue maxAge;
private final Long maxDocs;
public WaitForRolloverReadyStep(StepKey key, StepKey nextStepKey, Client client, ByteSizeValue maxSize, TimeValue maxAge,
Long maxDocs) {
super(key, nextStepKey, client);
this.maxSize = maxSize;
this.maxAge = maxAge;
this.maxDocs = maxDocs;
}
@Override
public void evaluateCondition(IndexMetaData indexMetaData, Listener listener) {
String rolloverAlias = RolloverAction.LIFECYCLE_ROLLOVER_ALIAS_SETTING.get(indexMetaData.getSettings());
if (Strings.isNullOrEmpty(rolloverAlias)) {
listener.onFailure(new IllegalArgumentException(String.format(Locale.ROOT,
"setting [%s] for index [%s] is empty or not defined", RolloverAction.LIFECYCLE_ROLLOVER_ALIAS,
indexMetaData.getIndex().getName())));
return;
}
// The order of the following checks is important in ways which may not be obvious.
// First, figure out if 1) The configured alias points to this index, and if so,
// whether this index is the write alias for this index
boolean aliasPointsToThisIndex = indexMetaData.getAliases().containsKey(rolloverAlias);
Boolean isWriteIndex = null;
if (aliasPointsToThisIndex) {
// The writeIndex() call returns a tri-state boolean:
// true -> this index is the write index for this alias
// false -> this index is not the write index for this alias
// null -> this alias is a "classic-style" alias and does not have a write index configured, but only points to one index
// and is thus the write index by default
isWriteIndex = indexMetaData.getAliases().get(rolloverAlias).writeIndex();
}
boolean indexingComplete = LifecycleSettings.LIFECYCLE_INDEXING_COMPLETE_SETTING.get(indexMetaData.getSettings());
if (indexingComplete) {
logger.trace(indexMetaData.getIndex() + " has lifecycle complete set, skipping " + WaitForRolloverReadyStep.NAME);
// If this index is still the write index for this alias, skipping rollover and continuing with the policy almost certainly
// isn't what we want, as something likely still expects to be writing to this index.
// If the alias doesn't point to this index, that's okay as that will be the result if this index is using a
// "classic-style" alias and has already rolled over, and we want to continue with the policy.
if (aliasPointsToThisIndex && Boolean.TRUE.equals(isWriteIndex)) {
listener.onFailure(new IllegalStateException(String.format(Locale.ROOT,
"index [%s] has [%s] set to [true], but is still the write index for alias [%s]",
indexMetaData.getIndex().getName(), LifecycleSettings.LIFECYCLE_INDEXING_COMPLETE, rolloverAlias)));
return;
}
listener.onResponse(true, new WaitForRolloverReadyStep.EmptyInfo());
return;
}
// If indexing_complete is *not* set, and the alias does not point to this index, we can't roll over this index, so error out.
if (aliasPointsToThisIndex == false) {
listener.onFailure(new IllegalArgumentException(String.format(Locale.ROOT,
"%s [%s] does not point to index [%s]", RolloverAction.LIFECYCLE_ROLLOVER_ALIAS, rolloverAlias,
indexMetaData.getIndex().getName())));
return;
}
// Similarly, if isWriteIndex is false (see note above on false vs. null), we can't roll over this index, so error out.
if (Boolean.FALSE.equals(isWriteIndex)) {
listener.onFailure(new IllegalArgumentException(String.format(Locale.ROOT,
"index [%s] is not the write index for alias [%s]", indexMetaData.getIndex().getName(), rolloverAlias)));
}
RolloverRequest rolloverRequest = new RolloverRequest(rolloverAlias, null);
rolloverRequest.dryRun(true);
if (maxAge != null) {
rolloverRequest.addMaxIndexAgeCondition(maxAge);
}
if (maxSize != null) {
rolloverRequest.addMaxIndexSizeCondition(maxSize);
}
if (maxDocs != null) {
rolloverRequest.addMaxIndexDocsCondition(maxDocs);
}
getClient().admin().indices().rolloverIndex(rolloverRequest,
ActionListener.wrap(response -> listener.onResponse(response.getConditionStatus().values().stream().anyMatch(i -> i),
new WaitForRolloverReadyStep.EmptyInfo()), listener::onFailure));
}
ByteSizeValue getMaxSize() {
return maxSize;
}
TimeValue getMaxAge() {
return maxAge;
}
Long getMaxDocs() {
return maxDocs;
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), maxSize, maxAge, maxDocs);
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
WaitForRolloverReadyStep other = (WaitForRolloverReadyStep) obj;
return super.equals(obj) &&
Objects.equals(maxSize, other.maxSize) &&
Objects.equals(maxAge, other.maxAge) &&
Objects.equals(maxDocs, other.maxDocs);
}
// We currently have no information to provide for this AsyncWaitStep, so this is an empty object
private class EmptyInfo implements ToXContentObject {
private EmptyInfo() {
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
return builder;
}
}
}
| x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/indexlifecycle/WaitForRolloverReadyStep.java | /*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.core.indexlifecycle;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.indices.rollover.RolloverRequest;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.ToXContentObject;
import org.elasticsearch.common.xcontent.XContentBuilder;
import java.io.IOException;
import java.util.Locale;
import java.util.Objects;
/**
* Waits for at least one rollover condition to be satisfied, using the Rollover API's dry_run option.
*/
public class WaitForRolloverReadyStep extends AsyncWaitStep {
private static final Logger logger = LogManager.getLogger(WaitForRolloverReadyStep.class);
public static final String NAME = "check-rollover-ready";
private final ByteSizeValue maxSize;
private final TimeValue maxAge;
private final Long maxDocs;
public WaitForRolloverReadyStep(StepKey key, StepKey nextStepKey, Client client, ByteSizeValue maxSize, TimeValue maxAge,
Long maxDocs) {
super(key, nextStepKey, client);
this.maxSize = maxSize;
this.maxAge = maxAge;
this.maxDocs = maxDocs;
}
@Override
public void evaluateCondition(IndexMetaData indexMetaData, Listener listener) {
String rolloverAlias = RolloverAction.LIFECYCLE_ROLLOVER_ALIAS_SETTING.get(indexMetaData.getSettings());
if (Strings.isNullOrEmpty(rolloverAlias)) {
listener.onFailure(new IllegalArgumentException(String.format(Locale.ROOT,
"setting [%s] for index [%s] is empty or not defined", RolloverAction.LIFECYCLE_ROLLOVER_ALIAS,
indexMetaData.getIndex().getName())));
return;
}
// The order of the following checks is important in ways which may not be obvious.
// First, figure out if 1) The configured alias points to this index, and if so,
// whether this index is the write alias for this index
boolean aliasPointsToThisIndex = indexMetaData.getAliases().containsKey(rolloverAlias);
Boolean isWriteIndex = null;
if (aliasPointsToThisIndex) {
// The writeIndex() call returns a tri-state boolean:
// true -> this index is the write index for this alias
// false -> this index is not the write index for this alias
// null -> this alias is a "classic-style" alias and does not have a write index configured, but only points to one index
// and is thus the write index by default
isWriteIndex = indexMetaData.getAliases().get(rolloverAlias).writeIndex();
}
boolean indexingComplete = LifecycleSettings.LIFECYCLE_INDEXING_COMPLETE_SETTING.get(indexMetaData.getSettings());
if (indexingComplete) {
logger.trace(indexMetaData.getIndex() + " has lifecycle complete set, skipping " + WaitForRolloverReadyStep.NAME);
// If this index is still the write index for this alias, skipping rollover and continuing with the policy almost certainly
// isn't what we want, as something likely still expects to be writing to this index.
// If the alias doesn't point to this index, that's okay as that will be the result if this index is using a
// "classic-style" alias and has already rolled over, and we want to continue with the policy.
if (aliasPointsToThisIndex && Boolean.TRUE.equals(isWriteIndex)) {
listener.onFailure(new IllegalStateException(String.format(Locale.ROOT,
"index [%s] has [%s] set to [true], but is still the write index for alias [%s]",
indexMetaData.getIndex().getName(), LifecycleSettings.LIFECYCLE_INDEXING_COMPLETE, rolloverAlias)));
return;
}
listener.onResponse(true, new WaitForRolloverReadyStep.EmptyInfo());
return;
}
// If indexing_complete is *not* set, and the alias does not point to this index, we can't roll over this index, so error out.
if (aliasPointsToThisIndex == false) {
listener.onFailure(new IllegalArgumentException(String.format(Locale.ROOT,
"%s [%s] does not point to index [%s]", RolloverAction.LIFECYCLE_ROLLOVER_ALIAS, rolloverAlias,
indexMetaData.getIndex().getName())));
return;
}
// Similarly, if isWriteIndex is false (see note above on false vs. null), we can't roll over this index, so error out.
if (Boolean.FALSE.equals(isWriteIndex)) {
listener.onFailure(new IllegalArgumentException(String.format(Locale.ROOT,
"index [%s] is not the write index for alias [%s]", rolloverAlias, indexMetaData.getIndex().getName())));
}
RolloverRequest rolloverRequest = new RolloverRequest(rolloverAlias, null);
rolloverRequest.dryRun(true);
if (maxAge != null) {
rolloverRequest.addMaxIndexAgeCondition(maxAge);
}
if (maxSize != null) {
rolloverRequest.addMaxIndexSizeCondition(maxSize);
}
if (maxDocs != null) {
rolloverRequest.addMaxIndexDocsCondition(maxDocs);
}
getClient().admin().indices().rolloverIndex(rolloverRequest,
ActionListener.wrap(response -> listener.onResponse(response.getConditionStatus().values().stream().anyMatch(i -> i),
new WaitForRolloverReadyStep.EmptyInfo()), listener::onFailure));
}
ByteSizeValue getMaxSize() {
return maxSize;
}
TimeValue getMaxAge() {
return maxAge;
}
Long getMaxDocs() {
return maxDocs;
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), maxSize, maxAge, maxDocs);
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
WaitForRolloverReadyStep other = (WaitForRolloverReadyStep) obj;
return super.equals(obj) &&
Objects.equals(maxSize, other.maxSize) &&
Objects.equals(maxAge, other.maxAge) &&
Objects.equals(maxDocs, other.maxDocs);
}
// We currently have no information to provide for this AsyncWaitStep, so this is an empty object
private class EmptyInfo implements ToXContentObject {
private EmptyInfo() {
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
return builder;
}
}
}
| Fix swapped variables in error message (#44300)
The alias name and index were in the incorrect order in this error
message. This commit corrects the order. | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/indexlifecycle/WaitForRolloverReadyStep.java | Fix swapped variables in error message (#44300) |
|
Java | apache-2.0 | 3a46e2bbe7a8cc0f7352b0841b407a66d023e32b | 0 | Pushpalanka/carbon-identity,Pushpalanka/carbon-identity,Pushpalanka/carbon-identity | /*
* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.identity.application.mgt;
import org.apache.axiom.om.OMElement;
import org.apache.axis2.AxisFault;
import org.apache.axis2.description.AxisService;
import org.apache.axis2.description.Parameter;
import org.apache.axis2.engine.AxisConfiguration;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.rahas.impl.SAMLTokenIssuerConfig;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.context.RegistryType;
import org.wso2.carbon.core.RegistryResources;
import org.wso2.carbon.directory.server.manager.DirectoryServerManager;
import org.wso2.carbon.identity.application.common.IdentityApplicationManagementException;
import org.wso2.carbon.identity.application.common.model.ApplicationBasicInfo;
import org.wso2.carbon.identity.application.common.model.ApplicationPermission;
import org.wso2.carbon.identity.application.common.model.AuthenticationStep;
import org.wso2.carbon.identity.application.common.model.IdentityProvider;
import org.wso2.carbon.identity.application.common.model.InboundAuthenticationRequestConfig;
import org.wso2.carbon.identity.application.common.model.LocalAuthenticatorConfig;
import org.wso2.carbon.identity.application.common.model.PermissionsAndRoleConfig;
import org.wso2.carbon.identity.application.common.model.RequestPathAuthenticatorConfig;
import org.wso2.carbon.identity.application.common.model.ServiceProvider;
import org.wso2.carbon.identity.application.common.util.IdentityApplicationConstants;
import org.wso2.carbon.identity.application.mgt.cache.IdentityServiceProviderCache;
import org.wso2.carbon.identity.application.mgt.cache.IdentityServiceProviderCacheEntry;
import org.wso2.carbon.identity.application.mgt.cache.IdentityServiceProviderCacheKey;
import org.wso2.carbon.identity.application.mgt.dao.ApplicationDAO;
import org.wso2.carbon.identity.application.mgt.dao.IdentityProviderDAO;
import org.wso2.carbon.identity.application.mgt.dao.OAuthApplicationDAO;
import org.wso2.carbon.identity.application.mgt.dao.SAMLApplicationDAO;
import org.wso2.carbon.identity.application.mgt.dao.impl.FileBasedApplicationDAO;
import org.wso2.carbon.identity.application.mgt.internal.ApplicationManagementServiceComponent;
import org.wso2.carbon.identity.application.mgt.internal.ApplicationManagementServiceComponentHolder;
import org.wso2.carbon.identity.application.mgt.internal.ApplicationMgtListenerServiceComponent;
import org.wso2.carbon.identity.application.mgt.listener.AbstractApplicationMgtListener;
import org.wso2.carbon.identity.application.mgt.listener.ApplicationMgtListener;
import org.wso2.carbon.registry.api.RegistryException;
import org.wso2.carbon.registry.core.Registry;
import org.wso2.carbon.registry.core.RegistryConstants;
import org.wso2.carbon.registry.core.Resource;
import org.wso2.carbon.security.SecurityConfigException;
import org.wso2.carbon.security.config.SecurityServiceAdmin;
import org.wso2.carbon.user.api.ClaimMapping;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.utils.ServerConstants;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
* Application management service implementation. Which can use as an osgi
* service and reuse this in admin service
*/
public class ApplicationManagementServiceImpl extends ApplicationManagementService {
private static Log log = LogFactory.getLog(ApplicationManagementServiceImpl.class);
private static volatile ApplicationManagementServiceImpl appMgtService;
/**
* Private constructor which not allow to create object from outside
*/
private ApplicationManagementServiceImpl() {
}
/**
* Get ApplicationManagementServiceImpl instance
*
* @return ApplicationManagementServiceImpl
*/
public static ApplicationManagementServiceImpl getInstance() {
if (appMgtService == null) {
synchronized (ApplicationManagementServiceImpl.class) {
if (appMgtService == null) {
appMgtService = new ApplicationManagementServiceImpl();
}
}
}
return appMgtService;
}
@Override
public void createApplication(ServiceProvider serviceProvider, String tenantDomain, String userName)
throws IdentityApplicationManagementException {
// invoking the listeners
Collection<ApplicationMgtListener> listeners = ApplicationMgtListenerServiceComponent.getApplicationMgtListeners();
for (ApplicationMgtListener listener : listeners) {
if (!listener.doPreCreateApplication(serviceProvider,tenantDomain, userName )) {
return;
}
}
startTenantFlow(tenantDomain, userName);
boolean roleCreated = false;
boolean permissionStored = false;
try {
// first we need to create a role with the application name.
// only the users in this role will be able to edit/update the
// application.
ApplicationMgtUtil.createAppRole(serviceProvider.getApplicationName());
roleCreated = true;
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
ApplicationMgtUtil.storePermission(serviceProvider.getApplicationName(),
serviceProvider.getPermissionAndRoleConfig());
permissionStored = true;
appDAO.createApplication(serviceProvider, tenantDomain);
} catch (Exception e) {
try {
if (roleCreated) {
ApplicationMgtUtil.deleteAppRole(serviceProvider.getApplicationName());
}
if (permissionStored) {
ApplicationMgtUtil.deletePermissions(serviceProvider.getApplicationName());
}
} catch (Exception ignored) {
if (log.isDebugEnabled()) {
log.debug("Ignored the exception occurred while trying to delete the role : ", e);
}
}
String error = "Error occurred while creating the application : " + serviceProvider.getApplicationName();
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
} finally {
endTenantFlow();
}
for (ApplicationMgtListener listener : listeners) {
if (!listener.doPostCreateApplication(serviceProvider, tenantDomain, userName)) {
return;
}
}
}
@Override
public ServiceProvider getApplicationExcludingFileBasedSPs(String applicationName, String tenantDomain)
throws IdentityApplicationManagementException {
try {
startTenantFlow(tenantDomain);
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
ServiceProvider serviceProvider = appDAO.getApplication(applicationName, tenantDomain);
if (serviceProvider != null) {
loadApplicationPermissions(applicationName, serviceProvider);
}
return serviceProvider;
} catch (Exception e) {
String error = "Error occurred while retrieving the application, " + applicationName;
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
} finally {
endTenantFlow();
}
}
@Override
public ApplicationBasicInfo[] getAllApplicationBasicInfo(String tenantDomain, String userName)
throws IdentityApplicationManagementException {
try {
startTenantFlow(tenantDomain, userName);
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
return appDAO.getAllApplicationBasicInfo();
} catch (Exception e) {
String error = "Error occurred while retrieving the all applications";
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
} finally {
endTenantFlow();
}
}
@Override
public void updateApplication(ServiceProvider serviceProvider, String tenantDomain, String userName)
throws IdentityApplicationManagementException {
// invoking the listeners
Collection<ApplicationMgtListener> listeners = ApplicationMgtListenerServiceComponent.getApplicationMgtListeners();
for (ApplicationMgtListener listener : listeners) {
if (!listener.doPreUpdateApplication(serviceProvider, tenantDomain, userName)) {
return;
}
}
try {
startTenantFlow(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
IdentityServiceProviderCacheKey cacheKey = new IdentityServiceProviderCacheKey(
tenantDomain, serviceProvider.getApplicationName());
IdentityServiceProviderCache.getInstance().clearCacheEntry(cacheKey);
} finally {
endTenantFlow();
startTenantFlow(tenantDomain, userName);
}
// check whether use is authorized to update the application.
if (!ApplicationConstants.LOCAL_SP.equals(serviceProvider.getApplicationName()) &&
!ApplicationMgtUtil.isUserAuthorized(serviceProvider.getApplicationName(),
serviceProvider.getApplicationID())) {
log.warn("Illegal Access! User " +
CarbonContext.getThreadLocalCarbonContext().getUsername() +
" does not have access to the application " +
serviceProvider.getApplicationName());
throw new IdentityApplicationManagementException("User not authorized");
}
try {
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
String storedAppName = appDAO.getApplicationName(serviceProvider.getApplicationID());
appDAO.updateApplication(serviceProvider);
ApplicationPermission[] permissions = serviceProvider.getPermissionAndRoleConfig().getPermissions();
String applicationNode = ApplicationMgtUtil.getApplicationPermissionPath() + RegistryConstants
.PATH_SEPARATOR + storedAppName;
org.wso2.carbon.registry.api.Registry tenantGovReg = CarbonContext.getThreadLocalCarbonContext()
.getRegistry(RegistryType.USER_GOVERNANCE);
boolean exist = tenantGovReg.resourceExists(applicationNode);
if (exist && !StringUtils.equals(storedAppName, serviceProvider.getApplicationName())) {
ApplicationMgtUtil.renameAppPermissionPathNode(storedAppName, serviceProvider.getApplicationName());
}
if (ArrayUtils.isNotEmpty(permissions)) {
ApplicationMgtUtil.updatePermissions(serviceProvider.getApplicationName(), permissions);
}
} catch (Exception e) {
String error = "Error occurred while updating the application";
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
} finally {
endTenantFlow();
}
for (ApplicationMgtListener listener : listeners) {
if (!listener.doPostUpdateApplication(serviceProvider, tenantDomain, userName)) {
return;
}
}
}
private void startTenantFlow(String tenantDomain)
throws IdentityApplicationManagementException {
int tenantId;
try {
tenantId = ApplicationManagementServiceComponentHolder.getInstance().getRealmService()
.getTenantManager().getTenantId(tenantDomain);
} catch (UserStoreException e) {
throw new IdentityApplicationManagementException("Error when setting tenant domain. ", e);
}
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain);
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId);
}
private void startTenantFlow(String tenantDomain, String userName)
throws IdentityApplicationManagementException {
int tenantId;
try {
tenantId = ApplicationManagementServiceComponentHolder.getInstance().getRealmService()
.getTenantManager().getTenantId(tenantDomain);
} catch (UserStoreException e) {
throw new IdentityApplicationManagementException("Error when setting tenant domain. ", e);
}
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain);
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId);
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(userName);
}
private void endTenantFlow() {
PrivilegedCarbonContext.endTenantFlow();
}
@Override
public void deleteApplication(String applicationName, String tenantDomain, String userName)
throws IdentityApplicationManagementException {
// invoking the listeners
Collection<ApplicationMgtListener> listeners = ApplicationMgtListenerServiceComponent.getApplicationMgtListeners();
for (ApplicationMgtListener listener : listeners) {
if (!listener.doPreDeleteApplication(applicationName, tenantDomain, userName)) {
return;
}
}
startTenantFlow(tenantDomain, userName);
if (!ApplicationMgtUtil.isUserAuthorized(applicationName)) {
log.warn("Illegal Access! User " + CarbonContext.getThreadLocalCarbonContext().getUsername() +
" does not have access to the application " + applicationName);
throw new IdentityApplicationManagementException("User not authorized");
}
try {
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
ServiceProvider serviceProvider = appDAO.getApplication(applicationName, tenantDomain);
appDAO.deleteApplication(applicationName);
ApplicationMgtUtil.deleteAppRole(applicationName);
ApplicationMgtUtil.deletePermissions(applicationName);
if (serviceProvider != null &&
serviceProvider.getInboundAuthenticationConfig() != null &&
serviceProvider.getInboundAuthenticationConfig().getInboundAuthenticationRequestConfigs() != null) {
InboundAuthenticationRequestConfig[] configs = serviceProvider.getInboundAuthenticationConfig()
.getInboundAuthenticationRequestConfigs();
for (InboundAuthenticationRequestConfig config : configs) {
if (IdentityApplicationConstants.Authenticator.SAML2SSO.NAME.
equalsIgnoreCase(config.getInboundAuthType()) && config.getInboundAuthKey() != null) {
SAMLApplicationDAO samlDAO = ApplicationMgtSystemConfig.getInstance().getSAMLClientDAO();
samlDAO.removeServiceProviderConfiguration(config.getInboundAuthKey());
} else if (IdentityApplicationConstants.OAuth2.NAME.equalsIgnoreCase(config.getInboundAuthType()) &&
config.getInboundAuthKey() != null) {
OAuthApplicationDAO oathDAO = ApplicationMgtSystemConfig.getInstance().getOAuthOIDCClientDAO();
oathDAO.removeOAuthApplication(config.getInboundAuthKey());
} else if ("kerberos".equalsIgnoreCase(config.getInboundAuthType()) && config.getInboundAuthKey()
!= null) {
DirectoryServerManager directoryServerManager = new DirectoryServerManager();
directoryServerManager.removeServer(config.getInboundAuthKey());
} else if(IdentityApplicationConstants.Authenticator.WSTrust.NAME.equalsIgnoreCase(
config.getInboundAuthType()) && config.getInboundAuthKey() != null) {
try {
AxisService stsService = getAxisConfig().getService(ServerConstants.STS_NAME);
Parameter origParam =
stsService.getParameter(SAMLTokenIssuerConfig.SAML_ISSUER_CONFIG.getLocalPart());
if (origParam != null) {
OMElement samlConfigElem = origParam.getParameterElement()
.getFirstChildWithName(SAMLTokenIssuerConfig.SAML_ISSUER_CONFIG);
SAMLTokenIssuerConfig samlConfig = new SAMLTokenIssuerConfig(samlConfigElem);
samlConfig.getTrustedServices().remove(config.getInboundAuthKey());
setSTSParameter(samlConfig);
removeTrustedService(ServerConstants.STS_NAME, ServerConstants.STS_NAME,
config.getInboundAuthKey());
} else {
throw new IdentityApplicationManagementException(
"missing parameter : " + SAMLTokenIssuerConfig.SAML_ISSUER_CONFIG.getLocalPart());
}
} catch (Exception e) {
String error = "Error while removing a trusted service";
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
}
}
}
}
} catch (Exception e) {
String error = "Error occurred while deleting the application";
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
} finally {
endTenantFlow();
}
for (ApplicationMgtListener listener : listeners) {
if (!listener.doPostDeleteApplication(applicationName, tenantDomain, userName)) {
return;
}
}
}
@Override
public IdentityProvider getIdentityProvider(String federatedIdPName, String tenantDomain)
throws IdentityApplicationManagementException {
try {
startTenantFlow(tenantDomain);
IdentityProviderDAO idpdao = ApplicationMgtSystemConfig.getInstance().getIdentityProviderDAO();
return idpdao.getIdentityProvider(federatedIdPName);
} catch (Exception e) {
String error = "Error occurred while retrieving Identity Provider";
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
} finally {
endTenantFlow();
}
}
@Override
public IdentityProvider[] getAllIdentityProviders(String tenantDomain)
throws IdentityApplicationManagementException {
try {
startTenantFlow(tenantDomain);
IdentityProviderDAO idpdao = ApplicationMgtSystemConfig.getInstance().getIdentityProviderDAO();
List<IdentityProvider> fedIdpList = idpdao.getAllIdentityProviders();
if (fedIdpList != null) {
return fedIdpList.toArray(new IdentityProvider[fedIdpList.size()]);
}
return new IdentityProvider[0];
} catch (Exception e) {
String error = "Error occurred while retrieving all Identity Providers";
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
} finally {
endTenantFlow();
}
}
@Override
public LocalAuthenticatorConfig[] getAllLocalAuthenticators(String tenantDomain)
throws IdentityApplicationManagementException {
try {
startTenantFlow(tenantDomain);
IdentityProviderDAO idpdao = ApplicationMgtSystemConfig.getInstance().getIdentityProviderDAO();
List<LocalAuthenticatorConfig> localAuthenticators = idpdao.getAllLocalAuthenticators();
if (localAuthenticators != null) {
return localAuthenticators.toArray(new LocalAuthenticatorConfig[localAuthenticators.size()]);
}
return new LocalAuthenticatorConfig[0];
} catch (Exception e) {
String error = "Error occurred while retrieving all Local Authenticators";
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
} finally {
endTenantFlow();
}
}
@Override
public RequestPathAuthenticatorConfig[] getAllRequestPathAuthenticators(String tenantDomain)
throws IdentityApplicationManagementException {
try {
startTenantFlow(tenantDomain);
IdentityProviderDAO idpdao = ApplicationMgtSystemConfig.getInstance().getIdentityProviderDAO();
List<RequestPathAuthenticatorConfig> reqPathAuthenticators = idpdao.getAllRequestPathAuthenticators();
if (reqPathAuthenticators != null) {
return reqPathAuthenticators.toArray(new RequestPathAuthenticatorConfig[reqPathAuthenticators.size()]);
}
return new RequestPathAuthenticatorConfig[0];
} catch (Exception e) {
String error = "Error occurred while retrieving all Request Path Authenticators";
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
} finally {
endTenantFlow();
}
}
@Override
public String[] getAllLocalClaimUris(String tenantDomain) throws IdentityApplicationManagementException {
try {
startTenantFlow(tenantDomain);
String claimDialect = ApplicationMgtSystemConfig.getInstance().getClaimDialect();
ClaimMapping[] claimMappings = CarbonContext.getThreadLocalCarbonContext().getUserRealm().getClaimManager()
.getAllClaimMappings(claimDialect);
List<String> claimUris = new ArrayList<>();
for (ClaimMapping claimMap : claimMappings) {
claimUris.add(claimMap.getClaim().getClaimUri());
}
String[] allLocalClaimUris = (claimUris.toArray(new String[claimUris.size()]));
if (ArrayUtils.isNotEmpty(allLocalClaimUris)) {
Arrays.sort(allLocalClaimUris);
}
return allLocalClaimUris;
} catch (Exception e) {
String error = "Error while reading system claims";
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
} finally {
endTenantFlow();
}
}
@Override
public String getServiceProviderNameByClientIdExcludingFileBasedSPs(String clientId, String type, String
tenantDomain)
throws IdentityApplicationManagementException {
try {
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
return appDAO.getServiceProviderNameByClientId(clientId, type, tenantDomain);
} catch (Exception e) {
String error = "Error occurred while retrieving the service provider for client id : " + clientId;
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
}
}
/**
* [sp-claim-uri,local-idp-claim-uri]
*
* @param serviceProviderName
* @param tenantDomain
* @return
* @throws IdentityApplicationManagementException
*/
@Override
public Map<String, String> getServiceProviderToLocalIdPClaimMapping(String serviceProviderName,
String tenantDomain)
throws IdentityApplicationManagementException {
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
Map<String, String> claimMap = appDAO.getServiceProviderToLocalIdPClaimMapping(
serviceProviderName, tenantDomain);
if (claimMap == null
|| claimMap.isEmpty()
&& ApplicationManagementServiceComponent.getFileBasedSPs().containsKey(
serviceProviderName)) {
return new FileBasedApplicationDAO().getServiceProviderToLocalIdPClaimMapping(
serviceProviderName, tenantDomain);
}
return claimMap;
}
/**
* [local-idp-claim-uri,sp-claim-uri]
*
* @param serviceProviderName
* @param tenantDomain
* @return
* @throws IdentityApplicationManagementException
*/
@Override
public Map<String, String> getLocalIdPToServiceProviderClaimMapping(String serviceProviderName,
String tenantDomain)
throws IdentityApplicationManagementException {
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
Map<String, String> claimMap = appDAO.getLocalIdPToServiceProviderClaimMapping(
serviceProviderName, tenantDomain);
if (claimMap == null
|| claimMap.isEmpty()
&& ApplicationManagementServiceComponent.getFileBasedSPs().containsKey(
serviceProviderName)) {
return new FileBasedApplicationDAO().getLocalIdPToServiceProviderClaimMapping(
serviceProviderName, tenantDomain);
}
return claimMap;
}
/**
* Returns back the requested set of claims by the provided service provider in local idp claim
* dialect.
*
* @param serviceProviderName
* @param tenantDomain
* @return
* @throws IdentityApplicationManagementException
*/
@Override
public List<String> getAllRequestedClaimsByServiceProvider(String serviceProviderName,
String tenantDomain)
throws IdentityApplicationManagementException {
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
List<String> reqClaims = appDAO.getAllRequestedClaimsByServiceProvider(serviceProviderName,
tenantDomain);
if (reqClaims == null
|| reqClaims.isEmpty()
&& ApplicationManagementServiceComponent.getFileBasedSPs().containsKey(
serviceProviderName)) {
return new FileBasedApplicationDAO().getAllRequestedClaimsByServiceProvider(
serviceProviderName, tenantDomain);
}
return reqClaims;
}
/**
* @param clientId
* @param clientType
* @param tenantDomain
* @return
* @throws IdentityApplicationManagementException
*/
@Override
public String getServiceProviderNameByClientId(String clientId, String clientType,
String tenantDomain) throws IdentityApplicationManagementException {
String name;
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
name = appDAO.getServiceProviderNameByClientId(clientId, clientType, tenantDomain);
if (name == null) {
name = new FileBasedApplicationDAO().getServiceProviderNameByClientId(clientId,
clientType, tenantDomain);
}
if (name == null) {
ServiceProvider defaultSP = ApplicationManagementServiceComponent.getFileBasedSPs()
.get(IdentityApplicationConstants.DEFAULT_SP_CONFIG);
name = defaultSP.getApplicationName();
}
return name;
}
/**
* @param serviceProviderName
* @param tenantDomain
* @return
* @throws IdentityApplicationManagementException
*/
@Override
public ServiceProvider getServiceProvider(String serviceProviderName, String tenantDomain)
throws IdentityApplicationManagementException {
startTenantFlow(tenantDomain);
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
ServiceProvider serviceProvider = appDAO.getApplication(serviceProviderName, tenantDomain);
if (serviceProvider != null) {
loadApplicationPermissions(serviceProviderName, serviceProvider);
}
if (serviceProvider == null
&& ApplicationManagementServiceComponent.getFileBasedSPs().containsKey(
serviceProviderName)) {
serviceProvider = ApplicationManagementServiceComponent.getFileBasedSPs().get(
serviceProviderName);
}
endTenantFlow();
return serviceProvider;
}
/**
* @param clientId
* @param clientType
* @param tenantDomain
* @return
* @throws IdentityApplicationManagementException
*/
@Override
public ServiceProvider getServiceProviderByClientId(String clientId, String clientType, String tenantDomain)
throws IdentityApplicationManagementException {
// client id can contain the @ to identify the tenant domain.
if (clientId != null && clientId.contains("@")) {
clientId = clientId.split("@")[0];
}
String serviceProviderName;
ServiceProvider serviceProvider = null;
serviceProviderName = getServiceProviderNameByClientId(clientId, clientType, tenantDomain);
try {
startTenantFlow(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
IdentityServiceProviderCacheKey cacheKey = new IdentityServiceProviderCacheKey(
tenantDomain, serviceProviderName);
IdentityServiceProviderCacheEntry entry = ((IdentityServiceProviderCacheEntry) IdentityServiceProviderCache
.getInstance().getValueFromCache(cacheKey));
if (entry != null) {
return entry.getServiceProvider();
}
} finally {
endTenantFlow();
startTenantFlow(tenantDomain);
}
if (serviceProviderName != null) {
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
serviceProvider = appDAO.getApplication(serviceProviderName, tenantDomain);
if (serviceProvider != null) {
// if "Authentication Type" is "Default" we must get the steps from the default SP
AuthenticationStep[] authenticationSteps = serviceProvider
.getLocalAndOutBoundAuthenticationConfig().getAuthenticationSteps();
loadApplicationPermissions(serviceProviderName, serviceProvider);
if (authenticationSteps == null || authenticationSteps.length == 0) {
ServiceProvider defaultSP = ApplicationManagementServiceComponent
.getFileBasedSPs().get(IdentityApplicationConstants.DEFAULT_SP_CONFIG);
authenticationSteps = defaultSP.getLocalAndOutBoundAuthenticationConfig()
.getAuthenticationSteps();
serviceProvider.getLocalAndOutBoundAuthenticationConfig()
.setAuthenticationSteps(authenticationSteps);
}
}
}
if (serviceProvider == null
&& serviceProviderName != null
&& ApplicationManagementServiceComponent.getFileBasedSPs().containsKey(
serviceProviderName)) {
serviceProvider = ApplicationManagementServiceComponent.getFileBasedSPs().get(
serviceProviderName);
}
endTenantFlow();
try {
startTenantFlow(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
IdentityServiceProviderCacheKey cacheKey = new IdentityServiceProviderCacheKey(
tenantDomain, serviceProviderName);
IdentityServiceProviderCacheEntry entry = new IdentityServiceProviderCacheEntry();
entry.setServiceProvider(serviceProvider);
IdentityServiceProviderCache.getInstance().addToCache(cacheKey, entry);
} finally {
endTenantFlow();
}
return serviceProvider;
}
private void loadApplicationPermissions(String serviceProviderName, ServiceProvider serviceProvider)
throws IdentityApplicationManagementException {
List<ApplicationPermission> permissionList = ApplicationMgtUtil.loadPermissions(serviceProviderName);
if (permissionList != null) {
PermissionsAndRoleConfig permissionAndRoleConfig;
if (serviceProvider.getPermissionAndRoleConfig() == null) {
permissionAndRoleConfig = new PermissionsAndRoleConfig();
} else {
permissionAndRoleConfig = serviceProvider.getPermissionAndRoleConfig();
}
permissionAndRoleConfig.setPermissions(permissionList.toArray(
new ApplicationPermission[permissionList.size()]));
serviceProvider.setPermissionAndRoleConfig(permissionAndRoleConfig);
}
}
/**
* Set STS parameters
*
* @param samlConfig SAML config
* @throws org.apache.axis2.AxisFault
* @throws org.wso2.carbon.registry.api.RegistryException
*/
private void setSTSParameter(SAMLTokenIssuerConfig samlConfig) throws AxisFault,
RegistryException {
new SecurityServiceAdmin(getAxisConfig(), getConfigSystemRegistry()).
setServiceParameterElement(ServerConstants.STS_NAME, samlConfig.getParameter());
}
/**
* Remove trusted service
*
* @param groupName Group name
* @param serviceName Service name
* @param trustedService Trusted service name
* @throws org.wso2.carbon.security.SecurityConfigException
*/
private void removeTrustedService(String groupName, String serviceName, String trustedService)
throws SecurityConfigException {
Registry registry;
String resourcePath;
Resource resource;
try {
resourcePath = RegistryResources.SERVICE_GROUPS + groupName +
RegistryResources.SERVICES + serviceName + "/trustedServices";
registry = getConfigSystemRegistry();
if (registry != null) {
if (registry.resourceExists(resourcePath)) {
resource = registry.get(resourcePath);
if (resource.getProperty(trustedService) != null) {
resource.removeProperty(trustedService);
}
registry.put(resourcePath, resource);
}
}
} catch (Exception e) {
String error = "Error occurred while removing trusted service for STS";
log.error(error, e);
throw new SecurityConfigException(error, e);
}
}
/**
* Get axis config
*
* @return axis configuration
*/
private AxisConfiguration getAxisConfig() {
return ApplicationManagementServiceComponentHolder.getInstance().getConfigContextService()
.getServerConfigContext().getAxisConfiguration();
}
/**
* Get config system registry
*
* @return config system registry
* @throws org.wso2.carbon.registry.api.RegistryException
*/
private Registry getConfigSystemRegistry() throws RegistryException {
return (Registry) ApplicationManagementServiceComponentHolder.getInstance().getRegistryService()
.getConfigSystemRegistry();
}
}
| components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/ApplicationManagementServiceImpl.java | /*
* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.identity.application.mgt;
import org.apache.axiom.om.OMElement;
import org.apache.axis2.AxisFault;
import org.apache.axis2.description.AxisService;
import org.apache.axis2.description.Parameter;
import org.apache.axis2.engine.AxisConfiguration;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.rahas.impl.SAMLTokenIssuerConfig;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.context.RegistryType;
import org.wso2.carbon.core.RegistryResources;
import org.wso2.carbon.directory.server.manager.DirectoryServerManager;
import org.wso2.carbon.identity.application.common.IdentityApplicationManagementException;
import org.wso2.carbon.identity.application.common.model.ApplicationBasicInfo;
import org.wso2.carbon.identity.application.common.model.ApplicationPermission;
import org.wso2.carbon.identity.application.common.model.AuthenticationStep;
import org.wso2.carbon.identity.application.common.model.IdentityProvider;
import org.wso2.carbon.identity.application.common.model.InboundAuthenticationRequestConfig;
import org.wso2.carbon.identity.application.common.model.LocalAuthenticatorConfig;
import org.wso2.carbon.identity.application.common.model.PermissionsAndRoleConfig;
import org.wso2.carbon.identity.application.common.model.RequestPathAuthenticatorConfig;
import org.wso2.carbon.identity.application.common.model.ServiceProvider;
import org.wso2.carbon.identity.application.common.util.IdentityApplicationConstants;
import org.wso2.carbon.identity.application.mgt.cache.IdentityServiceProviderCache;
import org.wso2.carbon.identity.application.mgt.cache.IdentityServiceProviderCacheEntry;
import org.wso2.carbon.identity.application.mgt.cache.IdentityServiceProviderCacheKey;
import org.wso2.carbon.identity.application.mgt.dao.ApplicationDAO;
import org.wso2.carbon.identity.application.mgt.dao.IdentityProviderDAO;
import org.wso2.carbon.identity.application.mgt.dao.OAuthApplicationDAO;
import org.wso2.carbon.identity.application.mgt.dao.SAMLApplicationDAO;
import org.wso2.carbon.identity.application.mgt.dao.impl.FileBasedApplicationDAO;
import org.wso2.carbon.identity.application.mgt.internal.ApplicationManagementServiceComponent;
import org.wso2.carbon.identity.application.mgt.internal.ApplicationManagementServiceComponentHolder;
import org.wso2.carbon.identity.application.mgt.internal.ApplicationMgtListenerServiceComponent;
import org.wso2.carbon.identity.application.mgt.listener.AbstractApplicationMgtListener;
import org.wso2.carbon.identity.application.mgt.listener.ApplicationMgtListener;
import org.wso2.carbon.registry.api.RegistryException;
import org.wso2.carbon.registry.core.Registry;
import org.wso2.carbon.registry.core.RegistryConstants;
import org.wso2.carbon.registry.core.Resource;
import org.wso2.carbon.security.SecurityConfigException;
import org.wso2.carbon.security.config.SecurityServiceAdmin;
import org.wso2.carbon.user.api.ClaimMapping;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.utils.ServerConstants;
import org.wso2.carbon.utils.multitenancy.MultitenantConstants;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
* Application management service implementation. Which can use as an osgi
* service and reuse this in admin service
*/
public class ApplicationManagementServiceImpl extends ApplicationManagementService {
private static Log log = LogFactory.getLog(ApplicationManagementServiceImpl.class);
private static volatile ApplicationManagementServiceImpl appMgtService;
/**
* Private constructor which not allow to create object from outside
*/
private ApplicationManagementServiceImpl() {
}
/**
* Get ApplicationManagementServiceImpl instance
*
* @return ApplicationManagementServiceImpl
*/
public static ApplicationManagementServiceImpl getInstance() {
if (appMgtService == null) {
synchronized (ApplicationManagementServiceImpl.class) {
if (appMgtService == null) {
appMgtService = new ApplicationManagementServiceImpl();
}
}
}
return appMgtService;
}
@Override
public void createApplication(ServiceProvider serviceProvider, String tenantDomain, String userName)
throws IdentityApplicationManagementException {
// invoking the listeners
Collection<ApplicationMgtListener> listeners = ApplicationMgtListenerServiceComponent.getApplicationMgtListeners();
for (ApplicationMgtListener listener : listeners) {
if (!listener.doPreCreateApplication(serviceProvider,tenantDomain, userName )) {
return;
}
}
startTenantFlow(tenantDomain, userName);
try {
// first we need to create a role with the application name.
// only the users in this role will be able to edit/update the
// application.
ApplicationMgtUtil.createAppRole(serviceProvider.getApplicationName());
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
ApplicationMgtUtil.storePermission(serviceProvider.getApplicationName(),
serviceProvider.getPermissionAndRoleConfig());
appDAO.createApplication(serviceProvider, tenantDomain);
} catch (Exception e) {
try {
ApplicationMgtUtil.deleteAppRole(serviceProvider.getApplicationName());
ApplicationMgtUtil.deletePermissions(serviceProvider.getApplicationName());
} catch (Exception ignored) {
if (log.isDebugEnabled()) {
log.debug("Ignored the exception occurred while trying to delete the role : ", e);
}
}
String error = "Error occurred while creating the application : " + serviceProvider.getApplicationName();
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
} finally {
endTenantFlow();
}
for (ApplicationMgtListener listener : listeners) {
if (!listener.doPostCreateApplication(serviceProvider, tenantDomain, userName)) {
return;
}
}
}
@Override
public ServiceProvider getApplicationExcludingFileBasedSPs(String applicationName, String tenantDomain)
throws IdentityApplicationManagementException {
try {
startTenantFlow(tenantDomain);
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
ServiceProvider serviceProvider = appDAO.getApplication(applicationName, tenantDomain);
if (serviceProvider != null) {
loadApplicationPermissions(applicationName, serviceProvider);
}
return serviceProvider;
} catch (Exception e) {
String error = "Error occurred while retrieving the application, " + applicationName;
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
} finally {
endTenantFlow();
}
}
@Override
public ApplicationBasicInfo[] getAllApplicationBasicInfo(String tenantDomain, String userName)
throws IdentityApplicationManagementException {
try {
startTenantFlow(tenantDomain, userName);
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
return appDAO.getAllApplicationBasicInfo();
} catch (Exception e) {
String error = "Error occurred while retrieving the all applications";
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
} finally {
endTenantFlow();
}
}
@Override
public void updateApplication(ServiceProvider serviceProvider, String tenantDomain, String userName)
throws IdentityApplicationManagementException {
// invoking the listeners
Collection<ApplicationMgtListener> listeners = ApplicationMgtListenerServiceComponent.getApplicationMgtListeners();
for (ApplicationMgtListener listener : listeners) {
if (!listener.doPreUpdateApplication(serviceProvider, tenantDomain, userName)) {
return;
}
}
try {
startTenantFlow(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
IdentityServiceProviderCacheKey cacheKey = new IdentityServiceProviderCacheKey(
tenantDomain, serviceProvider.getApplicationName());
IdentityServiceProviderCache.getInstance().clearCacheEntry(cacheKey);
} finally {
endTenantFlow();
startTenantFlow(tenantDomain, userName);
}
// check whether use is authorized to update the application.
if (!ApplicationConstants.LOCAL_SP.equals(serviceProvider.getApplicationName()) &&
!ApplicationMgtUtil.isUserAuthorized(serviceProvider.getApplicationName(),
serviceProvider.getApplicationID())) {
log.warn("Illegal Access! User " +
CarbonContext.getThreadLocalCarbonContext().getUsername() +
" does not have access to the application " +
serviceProvider.getApplicationName());
throw new IdentityApplicationManagementException("User not authorized");
}
try {
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
String storedAppName = appDAO.getApplicationName(serviceProvider.getApplicationID());
appDAO.updateApplication(serviceProvider);
ApplicationPermission[] permissions = serviceProvider.getPermissionAndRoleConfig().getPermissions();
String applicationNode = ApplicationMgtUtil.getApplicationPermissionPath() + RegistryConstants
.PATH_SEPARATOR + storedAppName;
org.wso2.carbon.registry.api.Registry tenantGovReg = CarbonContext.getThreadLocalCarbonContext()
.getRegistry(RegistryType.USER_GOVERNANCE);
boolean exist = tenantGovReg.resourceExists(applicationNode);
if (exist && !StringUtils.equals(storedAppName, serviceProvider.getApplicationName())) {
ApplicationMgtUtil.renameAppPermissionPathNode(storedAppName, serviceProvider.getApplicationName());
}
if (ArrayUtils.isNotEmpty(permissions)) {
ApplicationMgtUtil.updatePermissions(serviceProvider.getApplicationName(), permissions);
}
} catch (Exception e) {
String error = "Error occurred while updating the application";
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
} finally {
endTenantFlow();
}
for (ApplicationMgtListener listener : listeners) {
if (!listener.doPostUpdateApplication(serviceProvider, tenantDomain, userName)) {
return;
}
}
}
private void startTenantFlow(String tenantDomain)
throws IdentityApplicationManagementException {
int tenantId;
try {
tenantId = ApplicationManagementServiceComponentHolder.getInstance().getRealmService()
.getTenantManager().getTenantId(tenantDomain);
} catch (UserStoreException e) {
throw new IdentityApplicationManagementException("Error when setting tenant domain. ", e);
}
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain);
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId);
}
private void startTenantFlow(String tenantDomain, String userName)
throws IdentityApplicationManagementException {
int tenantId;
try {
tenantId = ApplicationManagementServiceComponentHolder.getInstance().getRealmService()
.getTenantManager().getTenantId(tenantDomain);
} catch (UserStoreException e) {
throw new IdentityApplicationManagementException("Error when setting tenant domain. ", e);
}
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain);
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tenantId);
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(userName);
}
private void endTenantFlow() {
PrivilegedCarbonContext.endTenantFlow();
}
@Override
public void deleteApplication(String applicationName, String tenantDomain, String userName)
throws IdentityApplicationManagementException {
// invoking the listeners
Collection<ApplicationMgtListener> listeners = ApplicationMgtListenerServiceComponent.getApplicationMgtListeners();
for (ApplicationMgtListener listener : listeners) {
if (!listener.doPreDeleteApplication(applicationName, tenantDomain, userName)) {
return;
}
}
startTenantFlow(tenantDomain, userName);
if (!ApplicationMgtUtil.isUserAuthorized(applicationName)) {
log.warn("Illegal Access! User " + CarbonContext.getThreadLocalCarbonContext().getUsername() +
" does not have access to the application " + applicationName);
throw new IdentityApplicationManagementException("User not authorized");
}
try {
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
ServiceProvider serviceProvider = appDAO.getApplication(applicationName, tenantDomain);
appDAO.deleteApplication(applicationName);
ApplicationMgtUtil.deleteAppRole(applicationName);
ApplicationMgtUtil.deletePermissions(applicationName);
if (serviceProvider != null &&
serviceProvider.getInboundAuthenticationConfig() != null &&
serviceProvider.getInboundAuthenticationConfig().getInboundAuthenticationRequestConfigs() != null) {
InboundAuthenticationRequestConfig[] configs = serviceProvider.getInboundAuthenticationConfig()
.getInboundAuthenticationRequestConfigs();
for (InboundAuthenticationRequestConfig config : configs) {
if (IdentityApplicationConstants.Authenticator.SAML2SSO.NAME.
equalsIgnoreCase(config.getInboundAuthType()) && config.getInboundAuthKey() != null) {
SAMLApplicationDAO samlDAO = ApplicationMgtSystemConfig.getInstance().getSAMLClientDAO();
samlDAO.removeServiceProviderConfiguration(config.getInboundAuthKey());
} else if (IdentityApplicationConstants.OAuth2.NAME.equalsIgnoreCase(config.getInboundAuthType()) &&
config.getInboundAuthKey() != null) {
OAuthApplicationDAO oathDAO = ApplicationMgtSystemConfig.getInstance().getOAuthOIDCClientDAO();
oathDAO.removeOAuthApplication(config.getInboundAuthKey());
} else if ("kerberos".equalsIgnoreCase(config.getInboundAuthType()) && config.getInboundAuthKey()
!= null) {
DirectoryServerManager directoryServerManager = new DirectoryServerManager();
directoryServerManager.removeServer(config.getInboundAuthKey());
} else if(IdentityApplicationConstants.Authenticator.WSTrust.NAME.equalsIgnoreCase(
config.getInboundAuthType()) && config.getInboundAuthKey() != null) {
try {
AxisService stsService = getAxisConfig().getService(ServerConstants.STS_NAME);
Parameter origParam =
stsService.getParameter(SAMLTokenIssuerConfig.SAML_ISSUER_CONFIG.getLocalPart());
if (origParam != null) {
OMElement samlConfigElem = origParam.getParameterElement()
.getFirstChildWithName(SAMLTokenIssuerConfig.SAML_ISSUER_CONFIG);
SAMLTokenIssuerConfig samlConfig = new SAMLTokenIssuerConfig(samlConfigElem);
samlConfig.getTrustedServices().remove(config.getInboundAuthKey());
setSTSParameter(samlConfig);
removeTrustedService(ServerConstants.STS_NAME, ServerConstants.STS_NAME,
config.getInboundAuthKey());
} else {
throw new IdentityApplicationManagementException(
"missing parameter : " + SAMLTokenIssuerConfig.SAML_ISSUER_CONFIG.getLocalPart());
}
} catch (Exception e) {
String error = "Error while removing a trusted service";
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
}
}
}
}
} catch (Exception e) {
String error = "Error occurred while deleting the application";
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
} finally {
endTenantFlow();
}
for (ApplicationMgtListener listener : listeners) {
if (!listener.doPostDeleteApplication(applicationName, tenantDomain, userName)) {
return;
}
}
}
@Override
public IdentityProvider getIdentityProvider(String federatedIdPName, String tenantDomain)
throws IdentityApplicationManagementException {
try {
startTenantFlow(tenantDomain);
IdentityProviderDAO idpdao = ApplicationMgtSystemConfig.getInstance().getIdentityProviderDAO();
return idpdao.getIdentityProvider(federatedIdPName);
} catch (Exception e) {
String error = "Error occurred while retrieving Identity Provider";
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
} finally {
endTenantFlow();
}
}
@Override
public IdentityProvider[] getAllIdentityProviders(String tenantDomain)
throws IdentityApplicationManagementException {
try {
startTenantFlow(tenantDomain);
IdentityProviderDAO idpdao = ApplicationMgtSystemConfig.getInstance().getIdentityProviderDAO();
List<IdentityProvider> fedIdpList = idpdao.getAllIdentityProviders();
if (fedIdpList != null) {
return fedIdpList.toArray(new IdentityProvider[fedIdpList.size()]);
}
return new IdentityProvider[0];
} catch (Exception e) {
String error = "Error occurred while retrieving all Identity Providers";
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
} finally {
endTenantFlow();
}
}
@Override
public LocalAuthenticatorConfig[] getAllLocalAuthenticators(String tenantDomain)
throws IdentityApplicationManagementException {
try {
startTenantFlow(tenantDomain);
IdentityProviderDAO idpdao = ApplicationMgtSystemConfig.getInstance().getIdentityProviderDAO();
List<LocalAuthenticatorConfig> localAuthenticators = idpdao.getAllLocalAuthenticators();
if (localAuthenticators != null) {
return localAuthenticators.toArray(new LocalAuthenticatorConfig[localAuthenticators.size()]);
}
return new LocalAuthenticatorConfig[0];
} catch (Exception e) {
String error = "Error occurred while retrieving all Local Authenticators";
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
} finally {
endTenantFlow();
}
}
@Override
public RequestPathAuthenticatorConfig[] getAllRequestPathAuthenticators(String tenantDomain)
throws IdentityApplicationManagementException {
try {
startTenantFlow(tenantDomain);
IdentityProviderDAO idpdao = ApplicationMgtSystemConfig.getInstance().getIdentityProviderDAO();
List<RequestPathAuthenticatorConfig> reqPathAuthenticators = idpdao.getAllRequestPathAuthenticators();
if (reqPathAuthenticators != null) {
return reqPathAuthenticators.toArray(new RequestPathAuthenticatorConfig[reqPathAuthenticators.size()]);
}
return new RequestPathAuthenticatorConfig[0];
} catch (Exception e) {
String error = "Error occurred while retrieving all Request Path Authenticators";
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
} finally {
endTenantFlow();
}
}
@Override
public String[] getAllLocalClaimUris(String tenantDomain) throws IdentityApplicationManagementException {
try {
startTenantFlow(tenantDomain);
String claimDialect = ApplicationMgtSystemConfig.getInstance().getClaimDialect();
ClaimMapping[] claimMappings = CarbonContext.getThreadLocalCarbonContext().getUserRealm().getClaimManager()
.getAllClaimMappings(claimDialect);
List<String> claimUris = new ArrayList<>();
for (ClaimMapping claimMap : claimMappings) {
claimUris.add(claimMap.getClaim().getClaimUri());
}
String[] allLocalClaimUris = (claimUris.toArray(new String[claimUris.size()]));
if (ArrayUtils.isNotEmpty(allLocalClaimUris)) {
Arrays.sort(allLocalClaimUris);
}
return allLocalClaimUris;
} catch (Exception e) {
String error = "Error while reading system claims";
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
} finally {
endTenantFlow();
}
}
@Override
public String getServiceProviderNameByClientIdExcludingFileBasedSPs(String clientId, String type, String
tenantDomain)
throws IdentityApplicationManagementException {
try {
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
return appDAO.getServiceProviderNameByClientId(clientId, type, tenantDomain);
} catch (Exception e) {
String error = "Error occurred while retrieving the service provider for client id : " + clientId;
log.error(error, e);
throw new IdentityApplicationManagementException(error, e);
}
}
/**
* [sp-claim-uri,local-idp-claim-uri]
*
* @param serviceProviderName
* @param tenantDomain
* @return
* @throws IdentityApplicationManagementException
*/
@Override
public Map<String, String> getServiceProviderToLocalIdPClaimMapping(String serviceProviderName,
String tenantDomain)
throws IdentityApplicationManagementException {
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
Map<String, String> claimMap = appDAO.getServiceProviderToLocalIdPClaimMapping(
serviceProviderName, tenantDomain);
if (claimMap == null
|| claimMap.isEmpty()
&& ApplicationManagementServiceComponent.getFileBasedSPs().containsKey(
serviceProviderName)) {
return new FileBasedApplicationDAO().getServiceProviderToLocalIdPClaimMapping(
serviceProviderName, tenantDomain);
}
return claimMap;
}
/**
* [local-idp-claim-uri,sp-claim-uri]
*
* @param serviceProviderName
* @param tenantDomain
* @return
* @throws IdentityApplicationManagementException
*/
@Override
public Map<String, String> getLocalIdPToServiceProviderClaimMapping(String serviceProviderName,
String tenantDomain)
throws IdentityApplicationManagementException {
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
Map<String, String> claimMap = appDAO.getLocalIdPToServiceProviderClaimMapping(
serviceProviderName, tenantDomain);
if (claimMap == null
|| claimMap.isEmpty()
&& ApplicationManagementServiceComponent.getFileBasedSPs().containsKey(
serviceProviderName)) {
return new FileBasedApplicationDAO().getLocalIdPToServiceProviderClaimMapping(
serviceProviderName, tenantDomain);
}
return claimMap;
}
/**
* Returns back the requested set of claims by the provided service provider in local idp claim
* dialect.
*
* @param serviceProviderName
* @param tenantDomain
* @return
* @throws IdentityApplicationManagementException
*/
@Override
public List<String> getAllRequestedClaimsByServiceProvider(String serviceProviderName,
String tenantDomain)
throws IdentityApplicationManagementException {
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
List<String> reqClaims = appDAO.getAllRequestedClaimsByServiceProvider(serviceProviderName,
tenantDomain);
if (reqClaims == null
|| reqClaims.isEmpty()
&& ApplicationManagementServiceComponent.getFileBasedSPs().containsKey(
serviceProviderName)) {
return new FileBasedApplicationDAO().getAllRequestedClaimsByServiceProvider(
serviceProviderName, tenantDomain);
}
return reqClaims;
}
/**
* @param clientId
* @param clientType
* @param tenantDomain
* @return
* @throws IdentityApplicationManagementException
*/
@Override
public String getServiceProviderNameByClientId(String clientId, String clientType,
String tenantDomain) throws IdentityApplicationManagementException {
String name;
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
name = appDAO.getServiceProviderNameByClientId(clientId, clientType, tenantDomain);
if (name == null) {
name = new FileBasedApplicationDAO().getServiceProviderNameByClientId(clientId,
clientType, tenantDomain);
}
if (name == null) {
ServiceProvider defaultSP = ApplicationManagementServiceComponent.getFileBasedSPs()
.get(IdentityApplicationConstants.DEFAULT_SP_CONFIG);
name = defaultSP.getApplicationName();
}
return name;
}
/**
* @param serviceProviderName
* @param tenantDomain
* @return
* @throws IdentityApplicationManagementException
*/
@Override
public ServiceProvider getServiceProvider(String serviceProviderName, String tenantDomain)
throws IdentityApplicationManagementException {
startTenantFlow(tenantDomain);
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
ServiceProvider serviceProvider = appDAO.getApplication(serviceProviderName, tenantDomain);
if (serviceProvider != null) {
loadApplicationPermissions(serviceProviderName, serviceProvider);
}
if (serviceProvider == null
&& ApplicationManagementServiceComponent.getFileBasedSPs().containsKey(
serviceProviderName)) {
serviceProvider = ApplicationManagementServiceComponent.getFileBasedSPs().get(
serviceProviderName);
}
endTenantFlow();
return serviceProvider;
}
/**
* @param clientId
* @param clientType
* @param tenantDomain
* @return
* @throws IdentityApplicationManagementException
*/
@Override
public ServiceProvider getServiceProviderByClientId(String clientId, String clientType, String tenantDomain)
throws IdentityApplicationManagementException {
// client id can contain the @ to identify the tenant domain.
if (clientId != null && clientId.contains("@")) {
clientId = clientId.split("@")[0];
}
String serviceProviderName;
ServiceProvider serviceProvider = null;
serviceProviderName = getServiceProviderNameByClientId(clientId, clientType, tenantDomain);
try {
startTenantFlow(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
IdentityServiceProviderCacheKey cacheKey = new IdentityServiceProviderCacheKey(
tenantDomain, serviceProviderName);
IdentityServiceProviderCacheEntry entry = ((IdentityServiceProviderCacheEntry) IdentityServiceProviderCache
.getInstance().getValueFromCache(cacheKey));
if (entry != null) {
return entry.getServiceProvider();
}
} finally {
endTenantFlow();
startTenantFlow(tenantDomain);
}
if (serviceProviderName != null) {
ApplicationDAO appDAO = ApplicationMgtSystemConfig.getInstance().getApplicationDAO();
serviceProvider = appDAO.getApplication(serviceProviderName, tenantDomain);
if (serviceProvider != null) {
// if "Authentication Type" is "Default" we must get the steps from the default SP
AuthenticationStep[] authenticationSteps = serviceProvider
.getLocalAndOutBoundAuthenticationConfig().getAuthenticationSteps();
loadApplicationPermissions(serviceProviderName, serviceProvider);
if (authenticationSteps == null || authenticationSteps.length == 0) {
ServiceProvider defaultSP = ApplicationManagementServiceComponent
.getFileBasedSPs().get(IdentityApplicationConstants.DEFAULT_SP_CONFIG);
authenticationSteps = defaultSP.getLocalAndOutBoundAuthenticationConfig()
.getAuthenticationSteps();
serviceProvider.getLocalAndOutBoundAuthenticationConfig()
.setAuthenticationSteps(authenticationSteps);
}
}
}
if (serviceProvider == null
&& serviceProviderName != null
&& ApplicationManagementServiceComponent.getFileBasedSPs().containsKey(
serviceProviderName)) {
serviceProvider = ApplicationManagementServiceComponent.getFileBasedSPs().get(
serviceProviderName);
}
endTenantFlow();
try {
startTenantFlow(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
IdentityServiceProviderCacheKey cacheKey = new IdentityServiceProviderCacheKey(
tenantDomain, serviceProviderName);
IdentityServiceProviderCacheEntry entry = new IdentityServiceProviderCacheEntry();
entry.setServiceProvider(serviceProvider);
IdentityServiceProviderCache.getInstance().addToCache(cacheKey, entry);
} finally {
endTenantFlow();
}
return serviceProvider;
}
private void loadApplicationPermissions(String serviceProviderName, ServiceProvider serviceProvider)
throws IdentityApplicationManagementException {
List<ApplicationPermission> permissionList = ApplicationMgtUtil.loadPermissions(serviceProviderName);
if (permissionList != null) {
PermissionsAndRoleConfig permissionAndRoleConfig;
if (serviceProvider.getPermissionAndRoleConfig() == null) {
permissionAndRoleConfig = new PermissionsAndRoleConfig();
} else {
permissionAndRoleConfig = serviceProvider.getPermissionAndRoleConfig();
}
permissionAndRoleConfig.setPermissions(permissionList.toArray(
new ApplicationPermission[permissionList.size()]));
serviceProvider.setPermissionAndRoleConfig(permissionAndRoleConfig);
}
}
/**
* Set STS parameters
*
* @param samlConfig SAML config
* @throws org.apache.axis2.AxisFault
* @throws org.wso2.carbon.registry.api.RegistryException
*/
private void setSTSParameter(SAMLTokenIssuerConfig samlConfig) throws AxisFault,
RegistryException {
new SecurityServiceAdmin(getAxisConfig(), getConfigSystemRegistry()).
setServiceParameterElement(ServerConstants.STS_NAME, samlConfig.getParameter());
}
/**
* Remove trusted service
*
* @param groupName Group name
* @param serviceName Service name
* @param trustedService Trusted service name
* @throws org.wso2.carbon.security.SecurityConfigException
*/
private void removeTrustedService(String groupName, String serviceName, String trustedService)
throws SecurityConfigException {
Registry registry;
String resourcePath;
Resource resource;
try {
resourcePath = RegistryResources.SERVICE_GROUPS + groupName +
RegistryResources.SERVICES + serviceName + "/trustedServices";
registry = getConfigSystemRegistry();
if (registry != null) {
if (registry.resourceExists(resourcePath)) {
resource = registry.get(resourcePath);
if (resource.getProperty(trustedService) != null) {
resource.removeProperty(trustedService);
}
registry.put(resourcePath, resource);
}
}
} catch (Exception e) {
String error = "Error occurred while removing trusted service for STS";
log.error(error, e);
throw new SecurityConfigException(error, e);
}
}
/**
* Get axis config
*
* @return axis configuration
*/
private AxisConfiguration getAxisConfig() {
return ApplicationManagementServiceComponentHolder.getInstance().getConfigContextService()
.getServerConfigContext().getAxisConfiguration();
}
/**
* Get config system registry
*
* @return config system registry
* @throws org.wso2.carbon.registry.api.RegistryException
*/
private Registry getConfigSystemRegistry() throws RegistryException {
return (Registry) ApplicationManagementServiceComponentHolder.getInstance().getRegistryService()
.getConfigSystemRegistry();
}
}
| fixing IDENTITY-3721
| components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/ApplicationManagementServiceImpl.java | fixing IDENTITY-3721 |
|
Java | apache-2.0 | d4def3a24a05e5f47fd3c69924d73683e05a38a5 | 0 | apache/httpcore,apache/httpcore,apache/httpcomponents-core | /*
* ====================================================================
* 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.
* ====================================================================
*
* 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.hc.core5.net;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import org.apache.hc.core5.util.TextUtils;
/**
* Builder for {@link URI} instances.
*
* @since 5.0
*/
public class URIBuilder {
/**
* Creates a new builder for the host {@link InetAddress#getLocalHost()}.
*
* @return a new builder.
* @throws UnknownHostException if the local host name could not be resolved into an address.
*/
public static URIBuilder localhost() throws UnknownHostException {
return new URIBuilder().setHost(InetAddress.getLocalHost());
}
/**
* Creates a new builder for the host {@link InetAddress#getLoopbackAddress()}.
*/
public static URIBuilder loopbackAddress() {
return new URIBuilder().setHost(InetAddress.getLoopbackAddress());
}
private String scheme;
private String encodedSchemeSpecificPart;
private String encodedAuthority;
private String userInfo;
private String encodedUserInfo;
private String host;
private int port;
private String encodedPath;
private List<String> pathSegments;
private String encodedQuery;
private List<NameValuePair> queryParams;
private String query;
private Charset charset;
private String fragment;
private String encodedFragment;
/**
* Constructs an empty instance.
*/
public URIBuilder() {
super();
this.port = -1;
}
/**
* Construct an instance from the string which must be a valid URI.
*
* @param string a valid URI in string form
* @throws URISyntaxException if the input is not a valid URI
*/
public URIBuilder(final String string) throws URISyntaxException {
this(new URI(string), null);
}
/**
* Construct an instance from the provided URI.
* @param uri
*/
public URIBuilder(final URI uri) {
this(uri, null);
}
/**
* Construct an instance from the string which must be a valid URI.
*
* @param string a valid URI in string form
* @throws URISyntaxException if the input is not a valid URI
*/
public URIBuilder(final String string, final Charset charset) throws URISyntaxException {
this(new URI(string), charset);
}
/**
* Construct an instance from the provided URI.
* @param uri
*/
public URIBuilder(final URI uri, final Charset charset) {
super();
setCharset(charset);
digestURI(uri);
}
public URIBuilder setCharset(final Charset charset) {
this.charset = charset;
return this;
}
public Charset getCharset() {
return charset;
}
private List <NameValuePair> parseQuery(final String query, final Charset charset) {
if (query != null && !query.isEmpty()) {
return URLEncodedUtils.parse(query, charset);
}
return null;
}
private List <String> parsePath(final String path, final Charset charset) {
if (path != null && !path.isEmpty()) {
return URLEncodedUtils.parsePathSegments(path, charset);
}
return null;
}
/**
* Builds a {@link URI} instance.
*/
public URI build() throws URISyntaxException {
return new URI(buildString());
}
private String buildString() {
final StringBuilder sb = new StringBuilder();
if (this.scheme != null) {
sb.append(this.scheme).append(':');
}
if (this.encodedSchemeSpecificPart != null) {
sb.append(this.encodedSchemeSpecificPart);
} else {
if (this.encodedAuthority != null) {
sb.append("//").append(this.encodedAuthority);
} else if (this.host != null) {
sb.append("//");
if (this.encodedUserInfo != null) {
sb.append(this.encodedUserInfo).append("@");
} else if (this.userInfo != null) {
encodeUserInfo(sb, this.userInfo);
sb.append("@");
}
if (InetAddressUtils.isIPv6Address(this.host)) {
sb.append("[").append(this.host).append("]");
} else {
sb.append(this.host);
}
if (this.port >= 0) {
sb.append(":").append(this.port);
}
}
if (this.encodedPath != null) {
sb.append(normalizePath(this.encodedPath, sb.length() == 0));
} else if (this.pathSegments != null) {
encodePath(sb, this.pathSegments);
}
if (this.encodedQuery != null) {
sb.append("?").append(this.encodedQuery);
} else if (this.queryParams != null && !this.queryParams.isEmpty()) {
sb.append("?");
encodeUrlForm(sb, this.queryParams);
} else if (this.query != null) {
sb.append("?");
encodeUric(sb, this.query);
}
}
if (this.encodedFragment != null) {
sb.append("#").append(this.encodedFragment);
} else if (this.fragment != null) {
sb.append("#");
encodeUric(sb, this.fragment);
}
return sb.toString();
}
private static String normalizePath(final String path, final boolean relative) {
String s = path;
if (TextUtils.isBlank(s)) {
return "";
}
if (!relative && !s.startsWith("/")) {
s = "/" + s;
}
return s;
}
private void digestURI(final URI uri) {
this.scheme = uri.getScheme();
this.encodedSchemeSpecificPart = uri.getRawSchemeSpecificPart();
this.encodedAuthority = uri.getRawAuthority();
this.host = uri.getHost();
this.port = uri.getPort();
this.encodedUserInfo = uri.getRawUserInfo();
this.userInfo = uri.getUserInfo();
this.encodedPath = uri.getRawPath();
this.pathSegments = parsePath(uri.getRawPath(), this.charset != null ? this.charset : StandardCharsets.UTF_8);
this.encodedQuery = uri.getRawQuery();
this.queryParams = parseQuery(uri.getRawQuery(), this.charset != null ? this.charset : StandardCharsets.UTF_8);
this.encodedFragment = uri.getRawFragment();
this.fragment = uri.getFragment();
}
private void encodeUserInfo(final StringBuilder buf, final String userInfo) {
URLEncodedUtils.encUserInfo(buf, userInfo, this.charset != null ? this.charset : StandardCharsets.UTF_8);
}
private void encodePath(final StringBuilder buf, final List<String> pathSegments) {
URLEncodedUtils.formatSegments(buf, pathSegments, this.charset != null ? this.charset : StandardCharsets.UTF_8);
}
private void encodeUrlForm(final StringBuilder buf, final List<NameValuePair> params) {
URLEncodedUtils.formatParameters(buf, params, this.charset != null ? this.charset : StandardCharsets.UTF_8);
}
private void encodeUric(final StringBuilder buf, final String fragment) {
URLEncodedUtils.encUric(buf, fragment, this.charset != null ? this.charset : StandardCharsets.UTF_8);
}
/**
* Sets URI scheme.
*
* @return this.
*/
public URIBuilder setScheme(final String scheme) {
this.scheme = !TextUtils.isBlank(scheme) ? scheme : null;
return this;
}
/**
* Sets URI user info. The value is expected to be unescaped and may contain non ASCII
* characters.
*
* @return this.
*/
public URIBuilder setUserInfo(final String userInfo) {
this.userInfo = !TextUtils.isBlank(userInfo) ? userInfo : null;
this.encodedSchemeSpecificPart = null;
this.encodedAuthority = null;
this.encodedUserInfo = null;
return this;
}
/**
* Sets URI user info as a combination of username and password. These values are expected to
* be unescaped and may contain non ASCII characters.
*
* @return this.
*/
public URIBuilder setUserInfo(final String username, final String password) {
return setUserInfo(username + ':' + password);
}
/**
* Sets URI host.
*
* @return this.
*/
public URIBuilder setHost(final InetAddress host) {
this.host = host != null ? host.getHostAddress() : null;
this.encodedSchemeSpecificPart = null;
this.encodedAuthority = null;
return this;
}
/**
* Sets URI host.
*
* @return this.
*/
public URIBuilder setHost(final String host) {
this.host = !TextUtils.isBlank(host) ? host : null;
this.encodedSchemeSpecificPart = null;
this.encodedAuthority = null;
return this;
}
/**
* Sets the scheme, host name, and port.
*
* @param httpHost the scheme, host name, and port.
* @return this.
*/
public URIBuilder setHttpHost(final HttpHost httpHost ) {
setScheme(httpHost.getSchemeName());
setHost(httpHost.getHostName());
setPort(httpHost.getPort());
return this;
}
/**
* Sets URI port.
*
* @return this.
*/
public URIBuilder setPort(final int port) {
this.port = port < 0 ? -1 : port;
this.encodedSchemeSpecificPart = null;
this.encodedAuthority = null;
return this;
}
/**
* Sets URI path. The value is expected to be unescaped and may contain non ASCII characters.
*
* @return this.
*/
public URIBuilder setPath(final String path) {
return setPathSegments(path != null ? URLEncodedUtils.splitPathSegments(path) : null);
}
/**
* Sets URI path. The value is expected to be unescaped and may contain non ASCII characters.
*
* @return this.
*/
public URIBuilder setPathSegments(final String... pathSegments) {
this.pathSegments = pathSegments.length > 0 ? Arrays.asList(pathSegments) : null;
this.encodedSchemeSpecificPart = null;
this.encodedPath = null;
return this;
}
/**
* Sets URI path. The value is expected to be unescaped and may contain non ASCII characters.
*
* @return this.
*/
public URIBuilder setPathSegments(final List<String> pathSegments) {
this.pathSegments = pathSegments != null && pathSegments.size() > 0 ? new ArrayList<>(pathSegments) : null;
this.encodedSchemeSpecificPart = null;
this.encodedPath = null;
return this;
}
/**
* Removes URI query.
*
* @return this.
*/
public URIBuilder removeQuery() {
this.queryParams = null;
this.query = null;
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
return this;
}
/**
* Sets URI query parameters. The parameter name / values are expected to be unescaped
* and may contain non ASCII characters.
* <p>
* Please note query parameters and custom query component are mutually exclusive. This method
* will remove custom query if present.
* </p>
*
* @return this.
*/
public URIBuilder setParameters(final List <NameValuePair> nvps) {
if (this.queryParams == null) {
this.queryParams = new ArrayList<>();
} else {
this.queryParams.clear();
}
this.queryParams.addAll(nvps);
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
this.query = null;
return this;
}
/**
* Adds URI query parameters. The parameter name / values are expected to be unescaped
* and may contain non ASCII characters.
* <p>
* Please note query parameters and custom query component are mutually exclusive. This method
* will remove custom query if present.
* </p>
*
* @return this.
*/
public URIBuilder addParameters(final List <NameValuePair> nvps) {
if (this.queryParams == null) {
this.queryParams = new ArrayList<>();
}
this.queryParams.addAll(nvps);
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
this.query = null;
return this;
}
/**
* Sets URI query parameters. The parameter name / values are expected to be unescaped
* and may contain non ASCII characters.
* <p>
* Please note query parameters and custom query component are mutually exclusive. This method
* will remove custom query if present.
* </p>
*
* @return this.
*/
public URIBuilder setParameters(final NameValuePair... nvps) {
if (this.queryParams == null) {
this.queryParams = new ArrayList<>();
} else {
this.queryParams.clear();
}
for (final NameValuePair nvp: nvps) {
this.queryParams.add(nvp);
}
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
this.query = null;
return this;
}
/**
* Adds parameter to URI query. The parameter name and value are expected to be unescaped
* and may contain non ASCII characters.
* <p>
* Please note query parameters and custom query component are mutually exclusive. This method
* will remove custom query if present.
* </p>
*
* @return this.
*/
public URIBuilder addParameter(final String param, final String value) {
if (this.queryParams == null) {
this.queryParams = new ArrayList<>();
}
this.queryParams.add(new BasicNameValuePair(param, value));
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
this.query = null;
return this;
}
/**
* Sets parameter of URI query overriding existing value if set. The parameter name and value
* are expected to be unescaped and may contain non ASCII characters.
* <p>
* Please note query parameters and custom query component are mutually exclusive. This method
* will remove custom query if present.
* </p>
*
* @return this.
*/
public URIBuilder setParameter(final String param, final String value) {
if (this.queryParams == null) {
this.queryParams = new ArrayList<>();
}
if (!this.queryParams.isEmpty()) {
for (final Iterator<NameValuePair> it = this.queryParams.iterator(); it.hasNext(); ) {
final NameValuePair nvp = it.next();
if (nvp.getName().equals(param)) {
it.remove();
}
}
}
this.queryParams.add(new BasicNameValuePair(param, value));
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
this.query = null;
return this;
}
/**
* Clears URI query parameters.
*
* @return this.
*/
public URIBuilder clearParameters() {
this.queryParams = null;
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
return this;
}
/**
* Sets custom URI query. The value is expected to be unescaped and may contain non ASCII
* characters.
* <p>
* Please note query parameters and custom query component are mutually exclusive. This method
* will remove query parameters if present.
* </p>
*
* @return this.
*/
public URIBuilder setCustomQuery(final String query) {
this.query = !TextUtils.isBlank(query) ? query : null;
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
this.queryParams = null;
return this;
}
/**
* Sets URI fragment. The value is expected to be unescaped and may contain non ASCII
* characters.
*
* @return this.
*/
public URIBuilder setFragment(final String fragment) {
this.fragment = !TextUtils.isBlank(fragment) ? fragment : null;
this.encodedFragment = null;
return this;
}
public boolean isAbsolute() {
return this.scheme != null;
}
public boolean isOpaque() {
return this.pathSegments == null && this.encodedPath == null;
}
public String getScheme() {
return this.scheme;
}
public String getUserInfo() {
return this.userInfo;
}
public String getHost() {
return this.host;
}
public int getPort() {
return this.port;
}
public boolean isPathEmpty() {
return (this.pathSegments == null || this.pathSegments.isEmpty()) &&
(this.encodedPath == null || this.encodedPath.isEmpty());
}
public List<String> getPathSegments() {
return this.pathSegments != null ? new ArrayList<>(this.pathSegments) : Collections.<String>emptyList();
}
public String getPath() {
if (this.pathSegments == null) {
return null;
}
final StringBuilder result = new StringBuilder();
for (final String segment : this.pathSegments) {
result.append('/').append(segment);
}
return result.toString();
}
public boolean isQueryEmpty() {
return (this.queryParams == null || this.queryParams.isEmpty()) && this.encodedQuery == null;
}
public List<NameValuePair> getQueryParams() {
return this.queryParams != null ? new ArrayList<>(this.queryParams) : Collections.<NameValuePair>emptyList();
}
public String getFragment() {
return this.fragment;
}
@Override
public String toString() {
return buildString();
}
}
| httpcore5/src/main/java/org/apache/hc/core5/net/URIBuilder.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.
* ====================================================================
*
* 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.hc.core5.net;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import org.apache.hc.core5.util.TextUtils;
/**
* Builder for {@link URI} instances.
*
* @since 5.0
*/
public class URIBuilder {
/**
* Creates a new builder for the host {@link InetAddress#getLocalHost()}.
*
* @return a new builder.
* @throws UnknownHostException if the local host name could not be resolved into an address.
*/
public static URIBuilder localhost() throws UnknownHostException {
return new URIBuilder().setHost(InetAddress.getLocalHost());
}
/**
* Creates a new builder for the host {@link InetAddress#getLoopbackAddress()}.
*/
public static URIBuilder loopbackAddress() {
return new URIBuilder().setHost(InetAddress.getLoopbackAddress());
}
private String scheme;
private String encodedSchemeSpecificPart;
private String encodedAuthority;
private String userInfo;
private String encodedUserInfo;
private String host;
private int port;
private String encodedPath;
private List<String> pathSegments;
private String encodedQuery;
private List<NameValuePair> queryParams;
private String query;
private Charset charset;
private String fragment;
private String encodedFragment;
/**
* Constructs an empty instance.
*/
public URIBuilder() {
super();
this.port = -1;
}
/**
* Construct an instance from the string which must be a valid URI.
*
* @param string a valid URI in string form
* @throws URISyntaxException if the input is not a valid URI
*/
public URIBuilder(final String string) throws URISyntaxException {
super();
digestURI(new URI(string));
}
/**
* Construct an instance from the provided URI.
* @param uri
*/
public URIBuilder(final URI uri) {
super();
digestURI(uri);
}
public URIBuilder setCharset(final Charset charset) {
this.charset = charset;
return this;
}
public Charset getCharset() {
return charset;
}
private List <NameValuePair> parseQuery(final String query, final Charset charset) {
if (query != null && !query.isEmpty()) {
return URLEncodedUtils.parse(query, charset);
}
return null;
}
private List <String> parsePath(final String path, final Charset charset) {
if (path != null && !path.isEmpty()) {
return URLEncodedUtils.parsePathSegments(path, charset);
}
return null;
}
/**
* Builds a {@link URI} instance.
*/
public URI build() throws URISyntaxException {
return new URI(buildString());
}
private String buildString() {
final StringBuilder sb = new StringBuilder();
if (this.scheme != null) {
sb.append(this.scheme).append(':');
}
if (this.encodedSchemeSpecificPart != null) {
sb.append(this.encodedSchemeSpecificPart);
} else {
if (this.encodedAuthority != null) {
sb.append("//").append(this.encodedAuthority);
} else if (this.host != null) {
sb.append("//");
if (this.encodedUserInfo != null) {
sb.append(this.encodedUserInfo).append("@");
} else if (this.userInfo != null) {
encodeUserInfo(sb, this.userInfo);
sb.append("@");
}
if (InetAddressUtils.isIPv6Address(this.host)) {
sb.append("[").append(this.host).append("]");
} else {
sb.append(this.host);
}
if (this.port >= 0) {
sb.append(":").append(this.port);
}
}
if (this.encodedPath != null) {
sb.append(normalizePath(this.encodedPath, sb.length() == 0));
} else if (this.pathSegments != null) {
encodePath(sb, this.pathSegments);
}
if (this.encodedQuery != null) {
sb.append("?").append(this.encodedQuery);
} else if (this.queryParams != null && !this.queryParams.isEmpty()) {
sb.append("?");
encodeUrlForm(sb, this.queryParams);
} else if (this.query != null) {
sb.append("?");
encodeUric(sb, this.query);
}
}
if (this.encodedFragment != null) {
sb.append("#").append(this.encodedFragment);
} else if (this.fragment != null) {
sb.append("#");
encodeUric(sb, this.fragment);
}
return sb.toString();
}
private static String normalizePath(final String path, final boolean relative) {
String s = path;
if (TextUtils.isBlank(s)) {
return "";
}
if (!relative && !s.startsWith("/")) {
s = "/" + s;
}
return s;
}
private void digestURI(final URI uri) {
this.scheme = uri.getScheme();
this.encodedSchemeSpecificPart = uri.getRawSchemeSpecificPart();
this.encodedAuthority = uri.getRawAuthority();
this.host = uri.getHost();
this.port = uri.getPort();
this.encodedUserInfo = uri.getRawUserInfo();
this.userInfo = uri.getUserInfo();
this.encodedPath = uri.getRawPath();
this.pathSegments = parsePath(uri.getRawPath(), this.charset != null ? this.charset : StandardCharsets.UTF_8);
this.encodedQuery = uri.getRawQuery();
this.queryParams = parseQuery(uri.getRawQuery(), this.charset != null ? this.charset : StandardCharsets.UTF_8);
this.encodedFragment = uri.getRawFragment();
this.fragment = uri.getFragment();
}
private void encodeUserInfo(final StringBuilder buf, final String userInfo) {
URLEncodedUtils.encUserInfo(buf, userInfo, this.charset != null ? this.charset : StandardCharsets.UTF_8);
}
private void encodePath(final StringBuilder buf, final List<String> pathSegments) {
URLEncodedUtils.formatSegments(buf, pathSegments, this.charset != null ? this.charset : StandardCharsets.UTF_8);
}
private void encodeUrlForm(final StringBuilder buf, final List<NameValuePair> params) {
URLEncodedUtils.formatParameters(buf, params, this.charset != null ? this.charset : StandardCharsets.UTF_8);
}
private void encodeUric(final StringBuilder buf, final String fragment) {
URLEncodedUtils.encUric(buf, fragment, this.charset != null ? this.charset : StandardCharsets.UTF_8);
}
/**
* Sets URI scheme.
*
* @return this.
*/
public URIBuilder setScheme(final String scheme) {
this.scheme = !TextUtils.isBlank(scheme) ? scheme : null;
return this;
}
/**
* Sets URI user info. The value is expected to be unescaped and may contain non ASCII
* characters.
*
* @return this.
*/
public URIBuilder setUserInfo(final String userInfo) {
this.userInfo = !TextUtils.isBlank(userInfo) ? userInfo : null;
this.encodedSchemeSpecificPart = null;
this.encodedAuthority = null;
this.encodedUserInfo = null;
return this;
}
/**
* Sets URI user info as a combination of username and password. These values are expected to
* be unescaped and may contain non ASCII characters.
*
* @return this.
*/
public URIBuilder setUserInfo(final String username, final String password) {
return setUserInfo(username + ':' + password);
}
/**
* Sets URI host.
*
* @return this.
*/
public URIBuilder setHost(final InetAddress host) {
this.host = host != null ? host.getHostAddress() : null;
this.encodedSchemeSpecificPart = null;
this.encodedAuthority = null;
return this;
}
/**
* Sets URI host.
*
* @return this.
*/
public URIBuilder setHost(final String host) {
this.host = !TextUtils.isBlank(host) ? host : null;
this.encodedSchemeSpecificPart = null;
this.encodedAuthority = null;
return this;
}
/**
* Sets the scheme, host name, and port.
*
* @param httpHost the scheme, host name, and port.
* @return this.
*/
public URIBuilder setHttpHost(final HttpHost httpHost ) {
setScheme(httpHost.getSchemeName());
setHost(httpHost.getHostName());
setPort(httpHost.getPort());
return this;
}
/**
* Sets URI port.
*
* @return this.
*/
public URIBuilder setPort(final int port) {
this.port = port < 0 ? -1 : port;
this.encodedSchemeSpecificPart = null;
this.encodedAuthority = null;
return this;
}
/**
* Sets URI path. The value is expected to be unescaped and may contain non ASCII characters.
*
* @return this.
*/
public URIBuilder setPath(final String path) {
return setPathSegments(path != null ? URLEncodedUtils.splitPathSegments(path) : null);
}
/**
* Sets URI path. The value is expected to be unescaped and may contain non ASCII characters.
*
* @return this.
*/
public URIBuilder setPathSegments(final String... pathSegments) {
this.pathSegments = pathSegments.length > 0 ? Arrays.asList(pathSegments) : null;
this.encodedSchemeSpecificPart = null;
this.encodedPath = null;
return this;
}
/**
* Sets URI path. The value is expected to be unescaped and may contain non ASCII characters.
*
* @return this.
*/
public URIBuilder setPathSegments(final List<String> pathSegments) {
this.pathSegments = pathSegments != null && pathSegments.size() > 0 ? new ArrayList<>(pathSegments) : null;
this.encodedSchemeSpecificPart = null;
this.encodedPath = null;
return this;
}
/**
* Removes URI query.
*
* @return this.
*/
public URIBuilder removeQuery() {
this.queryParams = null;
this.query = null;
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
return this;
}
/**
* Sets URI query parameters. The parameter name / values are expected to be unescaped
* and may contain non ASCII characters.
* <p>
* Please note query parameters and custom query component are mutually exclusive. This method
* will remove custom query if present.
* </p>
*
* @return this.
*/
public URIBuilder setParameters(final List <NameValuePair> nvps) {
if (this.queryParams == null) {
this.queryParams = new ArrayList<>();
} else {
this.queryParams.clear();
}
this.queryParams.addAll(nvps);
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
this.query = null;
return this;
}
/**
* Adds URI query parameters. The parameter name / values are expected to be unescaped
* and may contain non ASCII characters.
* <p>
* Please note query parameters and custom query component are mutually exclusive. This method
* will remove custom query if present.
* </p>
*
* @return this.
*/
public URIBuilder addParameters(final List <NameValuePair> nvps) {
if (this.queryParams == null) {
this.queryParams = new ArrayList<>();
}
this.queryParams.addAll(nvps);
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
this.query = null;
return this;
}
/**
* Sets URI query parameters. The parameter name / values are expected to be unescaped
* and may contain non ASCII characters.
* <p>
* Please note query parameters and custom query component are mutually exclusive. This method
* will remove custom query if present.
* </p>
*
* @return this.
*/
public URIBuilder setParameters(final NameValuePair... nvps) {
if (this.queryParams == null) {
this.queryParams = new ArrayList<>();
} else {
this.queryParams.clear();
}
for (final NameValuePair nvp: nvps) {
this.queryParams.add(nvp);
}
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
this.query = null;
return this;
}
/**
* Adds parameter to URI query. The parameter name and value are expected to be unescaped
* and may contain non ASCII characters.
* <p>
* Please note query parameters and custom query component are mutually exclusive. This method
* will remove custom query if present.
* </p>
*
* @return this.
*/
public URIBuilder addParameter(final String param, final String value) {
if (this.queryParams == null) {
this.queryParams = new ArrayList<>();
}
this.queryParams.add(new BasicNameValuePair(param, value));
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
this.query = null;
return this;
}
/**
* Sets parameter of URI query overriding existing value if set. The parameter name and value
* are expected to be unescaped and may contain non ASCII characters.
* <p>
* Please note query parameters and custom query component are mutually exclusive. This method
* will remove custom query if present.
* </p>
*
* @return this.
*/
public URIBuilder setParameter(final String param, final String value) {
if (this.queryParams == null) {
this.queryParams = new ArrayList<>();
}
if (!this.queryParams.isEmpty()) {
for (final Iterator<NameValuePair> it = this.queryParams.iterator(); it.hasNext(); ) {
final NameValuePair nvp = it.next();
if (nvp.getName().equals(param)) {
it.remove();
}
}
}
this.queryParams.add(new BasicNameValuePair(param, value));
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
this.query = null;
return this;
}
/**
* Clears URI query parameters.
*
* @return this.
*/
public URIBuilder clearParameters() {
this.queryParams = null;
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
return this;
}
/**
* Sets custom URI query. The value is expected to be unescaped and may contain non ASCII
* characters.
* <p>
* Please note query parameters and custom query component are mutually exclusive. This method
* will remove query parameters if present.
* </p>
*
* @return this.
*/
public URIBuilder setCustomQuery(final String query) {
this.query = !TextUtils.isBlank(query) ? query : null;
this.encodedQuery = null;
this.encodedSchemeSpecificPart = null;
this.queryParams = null;
return this;
}
/**
* Sets URI fragment. The value is expected to be unescaped and may contain non ASCII
* characters.
*
* @return this.
*/
public URIBuilder setFragment(final String fragment) {
this.fragment = !TextUtils.isBlank(fragment) ? fragment : null;
this.encodedFragment = null;
return this;
}
public boolean isAbsolute() {
return this.scheme != null;
}
public boolean isOpaque() {
return this.pathSegments == null && this.encodedPath == null;
}
public String getScheme() {
return this.scheme;
}
public String getUserInfo() {
return this.userInfo;
}
public String getHost() {
return this.host;
}
public int getPort() {
return this.port;
}
public boolean isPathEmpty() {
return (this.pathSegments == null || this.pathSegments.isEmpty()) &&
(this.encodedPath == null || this.encodedPath.isEmpty());
}
public List<String> getPathSegments() {
return this.pathSegments != null ? new ArrayList<>(this.pathSegments) : Collections.<String>emptyList();
}
public String getPath() {
if (this.pathSegments == null) {
return null;
}
final StringBuilder result = new StringBuilder();
for (final String segment : this.pathSegments) {
result.append('/').append(segment);
}
return result.toString();
}
public boolean isQueryEmpty() {
return (this.queryParams == null || this.queryParams.isEmpty()) && this.encodedQuery == null;
}
public List<NameValuePair> getQueryParams() {
return this.queryParams != null ? new ArrayList<>(this.queryParams) : Collections.<NameValuePair>emptyList();
}
public String getFragment() {
return this.fragment;
}
@Override
public String toString() {
return buildString();
}
}
| HTTPCLIENT-2029: URIBuilder to support parsing of non-UTF8 URIs
| httpcore5/src/main/java/org/apache/hc/core5/net/URIBuilder.java | HTTPCLIENT-2029: URIBuilder to support parsing of non-UTF8 URIs |
|
Java | apache-2.0 | 80b7a6468a8199ac244f5652828bfbaf5631a36e | 0 | pearson-enabling-technologies/elasticsearch-approx-plugin | package com.pearson.entech.elasticsearch.search.facet.approx.datehistogram;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Lists.newArrayListWithExpectedSize;
import static com.google.common.collect.Maps.newHashMap;
import static org.junit.Assert.assertEquals;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.elasticsearch.action.ListenableActionFuture;
import org.elasticsearch.action.admin.cluster.node.hotthreads.NodeHotThreads;
import org.elasticsearch.action.admin.cluster.node.hotthreads.NodesHotThreadsRequestBuilder;
import org.elasticsearch.action.admin.cluster.node.hotthreads.NodesHotThreadsResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.FilterBuilder;
import org.elasticsearch.index.query.FilterBuilders;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.facet.Facet;
import org.elasticsearch.search.facet.Facets;
import org.junit.AfterClass;
import org.junit.Ignore;
import org.junit.Test;
public class MediumDataSetPerformanceTest extends MediumDataSetTest {
private static final Map<String, Long> __executionStartTimes = newHashMap();
private static final Map<String, Long> __executionEndTimes = newHashMap();
ExecutorService _singleThread = Executors.newSingleThreadExecutor();
private final boolean _hotThreads = true;
// TODO add instrumentation for heap usage
private void clearMemory() throws Exception {
client().admin().indices().prepareClearCache(_index).execute().actionGet();
System.gc();
Thread.sleep(2000);
}
@AfterClass
public static void tearDownClass() {
System.out.println("Completed tests:");
for(final String name : __executionEndTimes.keySet()) {
final long duration = __executionEndTimes.get(name) - __executionStartTimes.get(name);
System.out.println(name + " completed in " + duration + " ms");
}
}
// TODO count facet in value_field mode as well
@Test
public void test100CountFacets() throws Exception {
final List<RandomDateFacetQuery> randomFacets = nRandomDateFacets(100);
testSomeRandomFacets(randomFacets, "test100CountFacets");
}
@Test
public void test100ApproxDistinctFacets() throws Exception {
final List<RandomDistinctDateFacetQuery> randomFacets = nRandomDistinctFacets(100, 0, 0.01);
testSomeRandomFacets(randomFacets, "test100ApproxDistinctFacets");
}
@Test
public void test100MixedDistinctFacets() throws Exception {
final List<RandomDistinctDateFacetQuery> randomFacets = nRandomDistinctFacets(100, 5000, 0.01);
testSomeRandomFacets(randomFacets, "test100MixedDistinctFacets");
}
@Test
public void test100ExactDistinctFacets() throws Exception {
final List<RandomDistinctDateFacetQuery> randomFacets = nRandomDistinctFacets(100, Integer.MAX_VALUE, 0);
testSomeRandomFacets(randomFacets, "test100ExactDistinctFacets");
}
// TODO sliced facet in value_field mode as well
@Test
public void test100SlicedFacets() throws Exception {
final List<RandomSlicedDateFacetQuery> randomFacets = nRandomSlicedFacets(100);
testSomeRandomFacets(randomFacets, "test100SlicedFacets");
}
@Test
@Ignore
public void testBringUpServerForManualQuerying() throws Exception {
Thread.sleep(1000000);
}
private String randomField() {
return randomPick(_fieldNames);
}
private <T extends RandomDateFacetQuery> void testSomeRandomFacets(final List<T> randomFacets, final String testName) throws Exception {
final List<SearchResponse> responses = executeSerially(randomFacets, testName);
assertEquals(randomFacets.size(), responses.size());
for(int i = 0; i < randomFacets.size(); i++) {
randomFacets.get(i).checkResults(responses.get(i));
}
}
private <T> List<T> executeSerially(final List<? extends Callable<T>> tasks, final String testName) throws Exception {
clearMemory();
final ListenableActionFuture<NodesHotThreadsResponse> threads = _hotThreads ?
new NodesHotThreadsRequestBuilder(client().admin().cluster())
.setInterval(TimeValue.timeValueSeconds(2))
.setType("cpu").setThreads(4).execute()
: null;
logExecutionStart(testName);
final List<Future<T>> futures = _singleThread.invokeAll(tasks);
logExecutionEnd(testName);
if(_hotThreads) {
final NodeHotThreads[] nodes = threads.actionGet().getNodes();
System.out.println("Hot threads for " + testName);
dumpHotThreads(nodes);
}
final List<T> results = newArrayList();
for(final Future<T> future : futures) {
results.add(future.get());
}
return results;
}
private void dumpHotThreads(final NodeHotThreads[] nodes) {
for(final NodeHotThreads node : nodes) {
System.out.println(node.getHotThreads());
}
}
private List<RandomDateFacetQuery> nRandomDateFacets(final int n) {
final List<RandomDateFacetQuery> requests = newArrayListWithExpectedSize(n);
for(int i = 0; i < n; i++) {
requests.add(new RandomDateFacetQuery("RandomDateFacet" + i));
}
return requests;
}
private List<RandomDistinctDateFacetQuery> nRandomDistinctFacets(final int n, final int exactThreshold, final double tolerance) {
final String distinctField = randomField();
final List<RandomDistinctDateFacetQuery> requests = newArrayListWithExpectedSize(n);
for(int i = 0; i < n; i++) {
requests.add(new RandomDistinctDateFacetQuery("RandomDistinctDateFacet" + i, distinctField, exactThreshold, tolerance));
}
return requests;
}
private List<RandomSlicedDateFacetQuery> nRandomSlicedFacets(final int n) {
final String sliceField = randomField();
final List<RandomSlicedDateFacetQuery> requests = newArrayListWithExpectedSize(n);
for(int i = 0; i < n; i++) {
requests.add(new RandomSlicedDateFacetQuery("RandomSlicedDateFacet" + i, sliceField));
}
return requests;
}
protected void logExecutionStart(final String testName) {
__executionStartTimes.put(testName, System.currentTimeMillis());
}
protected void logExecutionEnd(final String testName) {
__executionEndTimes.put(testName, System.currentTimeMillis());
}
public class RandomSlicedDateFacetQuery extends RandomDateFacetQuery {
private final String _sliceField;
private RandomSlicedDateFacetQuery(final String facetName, final String sliceField) {
super(facetName);
_sliceField = sliceField;
}
@Override
protected DateFacetBuilder makeFacet(final String name) {
return super.makeFacet(name).sliceField(_sliceField);
}
@Override
public String queryType() {
return "sliced_date_facet";
}
@Override
protected String facetField() {
return _sliceField;
}
@Override
public CountingQueryResultChecker buildChecker() {
return new SlicedQueryResultChecker(_index, _dtField, _sliceField, client(), this);
}
}
public class RandomDistinctDateFacetQuery extends RandomDateFacetQuery {
private final String _distinctField;
private final int _exactThreshold;
private final double _tolerance;
private RandomDistinctDateFacetQuery(final String facetName, final String distinctField, final int exactThreshold, final double tolerance) {
super(facetName);
_distinctField = distinctField;
_exactThreshold = exactThreshold;
_tolerance = tolerance;
}
@Override
protected DateFacetBuilder makeFacet(final String name) {
return super.makeFacet(name).distinctField(_distinctField).exactThreshold(_exactThreshold);
}
@Override
public String queryType() {
return "distinct_date_facet";
}
@Override
protected String facetField() {
return _distinctField;
}
@Override
public CountingQueryResultChecker buildChecker() {
return new DistinctQueryResultChecker(_index, _dtField, client(), _tolerance);
}
@Override
protected void checkHeaders(final Facet facet) {
super.checkHeaders(facet);
final DistinctQueryResultChecker checker = (DistinctQueryResultChecker) getChecker();
final HasDistinct castFacet = (HasDistinct) facet;
checker.checkTotalDistinctCount(castFacet.getDistinctCount());
}
}
public class RandomDateFacetQuery implements Callable<SearchResponse> {
private final String _facetName;
private CountingQueryResultChecker _checker;
private SearchResponse _response;
private RandomDateFacetQuery(final String facetName) {
_facetName = facetName;
}
protected CountingQueryResultChecker buildChecker() {
return new CountingQueryResultChecker(_index, _dtField, client());
}
public CountingQueryResultChecker getChecker() {
if(_checker == null)
_checker = buildChecker();
return _checker;
}
protected DateFacetBuilder makeFacet(final String name) {
return new DateFacetBuilder(name)
.interval(randomPick(_intervals))
.keyField(_dtField);
}
protected FilterBuilder makeFilter() {
return FilterBuilders.matchAllFilter();
}
protected String queryType() {
return "counting_date_facet";
}
protected String facetName() {
return _facetName;
}
protected String facetField() {
return _dtField;
}
public SearchResponse getSearchResponse() {
return _response;
}
@Override
public SearchResponse call() throws Exception {
return client()
.prepareSearch(_index)
.setQuery(
QueryBuilders.filteredQuery(
QueryBuilders.matchAllQuery(),
makeFilter()))
.setSearchType(SearchType.COUNT)
.addFacet(makeFacet(_facetName))
.execute().actionGet();
}
// Validation stuff
public void checkResults(final SearchResponse myResponse) {
_response = myResponse;
final Facets facets = myResponse.getFacets();
assertEquals("Found " + facets.facets().size() + " facets instead of 1", 1, facets.facets().size());
final Facet facet = facets.facet(_facetName);
assertEquals(queryType(), facet.getType());
checkEntries(facet);
checkHeaders(facet);
}
protected void checkEntries(final Facet facet) {
@SuppressWarnings("unchecked")
final DateFacet<TimePeriod<NullEntry>> castFacet = (DateFacet<TimePeriod<NullEntry>>) facet;
for(int i = 0; i < castFacet.getEntries().size(); i++) {
getChecker().specifier(facetField(), castFacet, i).validate();
}
}
protected void checkHeaders(final Facet facet) {
@SuppressWarnings("unchecked")
final DateFacet<TimePeriod<NullEntry>> castFacet = (DateFacet<TimePeriod<NullEntry>>) facet;
long totalCount = 0;
for(int i = 0; i < castFacet.getEntries().size(); i++) {
totalCount += castFacet.getEntries().get(i).getTotalCount();
}
getChecker().checkTotalCount(totalCount);
}
}
}
| src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/datehistogram/MediumDataSetPerformanceTest.java | package com.pearson.entech.elasticsearch.search.facet.approx.datehistogram;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.collect.Lists.newArrayListWithExpectedSize;
import static com.google.common.collect.Maps.newHashMap;
import static org.junit.Assert.assertEquals;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.elasticsearch.action.ListenableActionFuture;
import org.elasticsearch.action.admin.cluster.node.hotthreads.NodeHotThreads;
import org.elasticsearch.action.admin.cluster.node.hotthreads.NodesHotThreadsRequestBuilder;
import org.elasticsearch.action.admin.cluster.node.hotthreads.NodesHotThreadsResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.FilterBuilder;
import org.elasticsearch.index.query.FilterBuilders;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.facet.Facet;
import org.elasticsearch.search.facet.Facets;
import org.junit.AfterClass;
import org.junit.Ignore;
import org.junit.Test;
public class MediumDataSetPerformanceTest extends MediumDataSetTest {
private static final Map<String, Long> __executionStartTimes = newHashMap();
private static final Map<String, Long> __executionEndTimes = newHashMap();
ExecutorService _singleThread = Executors.newSingleThreadExecutor();
private final boolean _hotThreads = true;
// TODO add instrumentation for heap usage
private void clearMemory() throws Exception {
client().admin().indices().prepareClearCache(_index).execute().actionGet();
System.gc();
Thread.sleep(2000);
}
@AfterClass
public static void tearDownClass() {
System.out.println("Completed tests:");
for(final String name : __executionEndTimes.keySet()) {
final long duration = __executionEndTimes.get(name) - __executionStartTimes.get(name);
System.out.println(name + " completed in " + duration + " ms");
}
}
// TODO count facet in value_field mode as well
@Test
public void test100CountFacets() throws Exception {
final List<RandomDateFacetQuery> randomFacets = nRandomDateFacets(100);
testSomeRandomFacets(randomFacets, "test100CountFacets");
}
@Test
public void test100ApproxDistinctFacets() throws Exception {
final List<RandomDistinctDateFacetQuery> randomFacets = nRandomDistinctFacets(100, 0, 0.01);
testSomeRandomFacets(randomFacets, "test100ApproxDistinctFacets");
}
@Test
public void test100MixedDistinctFacets() throws Exception {
final List<RandomDistinctDateFacetQuery> randomFacets = nRandomDistinctFacets(100, 5000, 0.01);
testSomeRandomFacets(randomFacets, "test100MixedDistinctFacets");
}
@Test
public void test100ExactDistinctFacets() throws Exception {
final List<RandomDistinctDateFacetQuery> randomFacets = nRandomDistinctFacets(100, Integer.MAX_VALUE, 0);
testSomeRandomFacets(randomFacets, "test100ExactDistinctFacets");
}
// TODO sliced facet in value_field mode as well
@Test
public void test100SlicedFacets() throws Exception {
final List<RandomSlicedDateFacetQuery> randomFacets = nRandomSlicedFacets(100);
testSomeRandomFacets(randomFacets, "test100SlicedFacets");
}
@Test
@Ignore
public void testBringUpServerForManualQuerying() throws Exception {
Thread.sleep(1000000);
}
private String randomField() {
return randomPick(_fieldNames);
}
private <T extends RandomDateFacetQuery> void testSomeRandomFacets(final List<T> randomFacets, final String testName) throws Exception {
final List<SearchResponse> responses = executeSerially(randomFacets, testName);
assertEquals(randomFacets.size(), responses.size());
for(int i = 0; i < randomFacets.size(); i++) {
randomFacets.get(i).checkResults(responses.get(i));
}
}
private <T> List<T> executeSerially(final List<? extends Callable<T>> tasks, final String testName) throws Exception {
clearMemory();
final ListenableActionFuture<NodesHotThreadsResponse> threads = _hotThreads ?
new NodesHotThreadsRequestBuilder(client().admin().cluster())
.setInterval(TimeValue.timeValueSeconds(2))
.setThreads(5).execute()
: null;
logExecutionStart(testName);
final List<Future<T>> futures = _singleThread.invokeAll(tasks);
logExecutionEnd(testName);
if(_hotThreads) {
final NodeHotThreads[] nodes = threads.actionGet().getNodes();
System.out.println("Hot threads for " + testName);
dumpHotThreads(nodes);
}
final List<T> results = newArrayList();
for(final Future<T> future : futures) {
results.add(future.get());
}
return results;
}
private void dumpHotThreads(final NodeHotThreads[] nodes) {
for(final NodeHotThreads node : nodes) {
System.out.println(node.getHotThreads());
}
}
private List<RandomDateFacetQuery> nRandomDateFacets(final int n) {
final List<RandomDateFacetQuery> requests = newArrayListWithExpectedSize(n);
for(int i = 0; i < n; i++) {
requests.add(new RandomDateFacetQuery("RandomDateFacet" + i));
}
return requests;
}
private List<RandomDistinctDateFacetQuery> nRandomDistinctFacets(final int n, final int exactThreshold, final double tolerance) {
final String distinctField = randomField();
final List<RandomDistinctDateFacetQuery> requests = newArrayListWithExpectedSize(n);
for(int i = 0; i < n; i++) {
requests.add(new RandomDistinctDateFacetQuery("RandomDistinctDateFacet" + i, distinctField, exactThreshold, tolerance));
}
return requests;
}
private List<RandomSlicedDateFacetQuery> nRandomSlicedFacets(final int n) {
final String sliceField = randomField();
final List<RandomSlicedDateFacetQuery> requests = newArrayListWithExpectedSize(n);
for(int i = 0; i < n; i++) {
requests.add(new RandomSlicedDateFacetQuery("RandomSlicedDateFacet" + i, sliceField));
}
return requests;
}
protected void logExecutionStart(final String testName) {
__executionStartTimes.put(testName, System.currentTimeMillis());
}
protected void logExecutionEnd(final String testName) {
__executionEndTimes.put(testName, System.currentTimeMillis());
}
public class RandomSlicedDateFacetQuery extends RandomDateFacetQuery {
private final String _sliceField;
private RandomSlicedDateFacetQuery(final String facetName, final String sliceField) {
super(facetName);
_sliceField = sliceField;
}
@Override
protected DateFacetBuilder makeFacet(final String name) {
return super.makeFacet(name).sliceField(_sliceField);
}
@Override
public String queryType() {
return "sliced_date_facet";
}
@Override
protected String facetField() {
return _sliceField;
}
@Override
public CountingQueryResultChecker buildChecker() {
return new SlicedQueryResultChecker(_index, _dtField, _sliceField, client(), this);
}
}
public class RandomDistinctDateFacetQuery extends RandomDateFacetQuery {
private final String _distinctField;
private final int _exactThreshold;
private final double _tolerance;
private RandomDistinctDateFacetQuery(final String facetName, final String distinctField, final int exactThreshold, final double tolerance) {
super(facetName);
_distinctField = distinctField;
_exactThreshold = exactThreshold;
_tolerance = tolerance;
}
@Override
protected DateFacetBuilder makeFacet(final String name) {
return super.makeFacet(name).distinctField(_distinctField).exactThreshold(_exactThreshold);
}
@Override
public String queryType() {
return "distinct_date_facet";
}
@Override
protected String facetField() {
return _distinctField;
}
@Override
public CountingQueryResultChecker buildChecker() {
return new DistinctQueryResultChecker(_index, _dtField, client(), _tolerance);
}
@Override
protected void checkHeaders(final Facet facet) {
super.checkHeaders(facet);
final DistinctQueryResultChecker checker = (DistinctQueryResultChecker) getChecker();
final HasDistinct castFacet = (HasDistinct) facet;
checker.checkTotalDistinctCount(castFacet.getDistinctCount());
}
}
public class RandomDateFacetQuery implements Callable<SearchResponse> {
private final String _facetName;
private CountingQueryResultChecker _checker;
private SearchResponse _response;
private RandomDateFacetQuery(final String facetName) {
_facetName = facetName;
}
protected CountingQueryResultChecker buildChecker() {
return new CountingQueryResultChecker(_index, _dtField, client());
}
public CountingQueryResultChecker getChecker() {
if(_checker == null)
_checker = buildChecker();
return _checker;
}
protected DateFacetBuilder makeFacet(final String name) {
return new DateFacetBuilder(name)
.interval(randomPick(_intervals))
.keyField(_dtField);
}
protected FilterBuilder makeFilter() {
return FilterBuilders.matchAllFilter();
}
protected String queryType() {
return "counting_date_facet";
}
protected String facetName() {
return _facetName;
}
protected String facetField() {
return _dtField;
}
public SearchResponse getSearchResponse() {
return _response;
}
@Override
public SearchResponse call() throws Exception {
return client()
.prepareSearch(_index)
.setQuery(
QueryBuilders.filteredQuery(
QueryBuilders.matchAllQuery(),
makeFilter()))
.setSearchType(SearchType.COUNT)
.addFacet(makeFacet(_facetName))
.execute().actionGet();
}
// Validation stuff
public void checkResults(final SearchResponse myResponse) {
_response = myResponse;
final Facets facets = myResponse.getFacets();
assertEquals("Found " + facets.facets().size() + " facets instead of 1", 1, facets.facets().size());
final Facet facet = facets.facet(_facetName);
assertEquals(queryType(), facet.getType());
checkEntries(facet);
checkHeaders(facet);
}
protected void checkEntries(final Facet facet) {
@SuppressWarnings("unchecked")
final DateFacet<TimePeriod<NullEntry>> castFacet = (DateFacet<TimePeriod<NullEntry>>) facet;
for(int i = 0; i < castFacet.getEntries().size(); i++) {
getChecker().specifier(facetField(), castFacet, i).validate();
}
}
protected void checkHeaders(final Facet facet) {
@SuppressWarnings("unchecked")
final DateFacet<TimePeriod<NullEntry>> castFacet = (DateFacet<TimePeriod<NullEntry>>) facet;
long totalCount = 0;
for(int i = 0; i < castFacet.getEntries().size(); i++) {
totalCount += castFacet.getEntries().get(i).getTotalCount();
}
getChecker().checkTotalCount(totalCount);
}
}
}
| Snapshot before releasing to lo1 | src/test/java/com/pearson/entech/elasticsearch/search/facet/approx/datehistogram/MediumDataSetPerformanceTest.java | Snapshot before releasing to lo1 |
|
Java | apache-2.0 | 3d3a8fe7dafdb84366fd2e6ec12f4e71db17d8c5 | 0 | apache/derby,trejkaz/derby,apache/derby,trejkaz/derby,trejkaz/derby,apache/derby,apache/derby | /*
Derby - Class org.apache.derbyTesting.functionTests.tests.jdbcapi.DatabaseMetaDataTest
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.jdbcapi;
import java.io.IOException;
//import java.lang.reflect.Constructor;
//import java.lang.reflect.Method;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Arrays;
//import java.util.HashMap;
//import java.util.Iterator;
import java.util.List;
import java.util.Locale;
//import java.util.Map;
import java.util.Random;
import java.util.StringTokenizer;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.derbyTesting.junit.BaseJDBCTestCase;
//import org.apache.derbyTesting.junit.CleanDatabaseTestSetup;
import org.apache.derbyTesting.junit.DatabasePropertyTestSetup;
import org.apache.derbyTesting.junit.JDBC;
import org.apache.derbyTesting.junit.TestConfiguration;
//import org.apache.derby.shared.common.reference.JDBC40Translation;
/**
* Test the DatabaseMetaData api.
* <P>
* For the methods that return a ResultSet to determine the
* attributes of SQL objects (e.g. getTables) two methods
* are provided. A non-modify and a modify one.
*
* <BR>
* The non-modify method tests that the getXXX method call works.
* This can be used by other tests where issues have been seen
* with database meta data, such as upgrade and read-only databases.
* The non-modify means that the test method does not change the database
* in order to test the return of the getXXX method is correct.
* <BR>
* The modify versions test
* Work in progress.
* TODO: Methods left to test from JDBC 3
*
* getColumnPrivileges
* getCrossReference
* getExportedKeys
* getImportedKeys
* getIndexInfo
* getPrimaryKeys
* getProcedureColumns
* getProcedures
* getTablePrivileges
* <P>
* This test is also called from the upgrade tests to test that
* metadata continues to work at various points in the upgrade.
*/
public class DatabaseMetaDataTest extends BaseJDBCTestCase {
/*
** Escaped function testing
*/
private static final String[][] NUMERIC_FUNCTIONS =
{
// Section C.1 JDBC 3.0 spec.
{ "ABS", "-25.67" },
{ "ACOS", "0.0707" },
{ "ASIN", "0.997" },
{ "ATAN", "14.10" },
{ "ATAN2", "0.56", "1.2" },
{ "CEILING", "3.45" },
{ "COS", "1.2" },
{ "COT", "3.4" },
{ "DEGREES", "2.1" },
{ "EXP", "2.3" },
{ "FLOOR", "3.22" },
{ "LOG", "34.1" },
{ "LOG10", "18.7" },
{ "MOD", "124", "7" },
{ "PI" },
{ "POWER", "2", "3" },
{ "RADIANS", "54" },
{ "RAND", "17" },
{ "ROUND", "345.345", "1" },
{ "SIGN", "-34" },
{ "SIN", "0.32" },
{ "SQRT", "6.22" },
{ "TAN", "0.57", },
{ "TRUNCATE", "345.395", "1" }
};
private static final String[][] TIMEDATE_FUNCTIONS =
{
// Section C.3 JDBC 3.0 spec.
{ "CURDATE" },
{ "CURTIME" },
{ "DAYNAME", "{d '1995-12-19'h}" },
{ "DAYOFMONTH", "{d '1995-12-19'}" },
{ "DAYOFWEEK", "{d '1995-12-19'}" },
{ "DAYOFYEAR", "{d '1995-12-19'}" },
{ "HOUR", "{t '16:13:03'}" },
{ "MINUTE", "{t '16:13:03'}" },
{ "MONTH", "{d '1995-12-19'}" },
{ "MONTHNAME", "{d '1995-12-19'}" },
{ "NOW" },
{ "QUARTER", "{d '1995-12-19'}" },
{ "SECOND", "{t '16:13:03'}" },
{ "TIMESTAMPADD", "SQL_TSI_DAY", "7", "{ts '1995-12-19 12:15:54'}" },
{ "TIMESTAMPDIFF", "SQL_TSI_DAY", "{ts '1995-12-19 12:15:54'}", "{ts '1997-11-02 00:15:23'}" },
{ "WEEK", "{d '1995-12-19'}" },
{ "YEAR", "{d '1995-12-19'}" },
};
private static final String[][] SYSTEM_FUNCTIONS =
{
// Section C.4 JDBC 3.0 spec.
{ "DATABASE" },
{ "IFNULL", "'this'", "'that'" },
{ "USER"},
};
private static final String[][] STRING_FUNCTIONS =
{
// Section C.2 JDBC 3.0 spec.
{ "ASCII" , "'Yellow'" },
{ "CHAR", "65" },
{ "CONCAT", "'hello'", "'there'" },
{ "DIFFERENCE", "'Pires'", "'Piers'" },
{ "INSERT", "'Bill Clinton'", "4", "'William'" },
{ "LCASE", "'Fernando Alonso'" },
{ "LEFT", "'Bonjour'", "3" },
{ "LENGTH", "'four '" } ,
{ "LOCATE", "'jour'", "'Bonjour'" },
{ "LTRIM", "' left trim '"},
{ "REPEAT", "'echo'", "3" },
{ "REPLACE", "'to be or not to be'", "'be'", "'England'" },
{ "RTRIM", "' right trim '"},
{ "SOUNDEX", "'Derby'" },
{ "SPACE", "12"},
{ "SUBSTRING", "'Ruby the Rubicon Jeep'", "10", "7", },
{ "UCASE", "'Fernando Alonso'" }
};
/**
* Did the test modifiy the database.
*/
private boolean modifiedDatabase;
public DatabaseMetaDataTest(String name) {
super(name);
}
protected void tearDown() throws Exception
{
if (modifiedDatabase)
{
Connection conn = getConnection();
conn.setAutoCommit(false);
DatabaseMetaData dmd = getDMD();
for (int i = 0; i < IDS.length; i++)
JDBC.dropSchema(dmd, getStoredIdentifier(IDS[i]));
commit();
}
super.tearDown();
}
/**
* Default suite for running this test.
*/
public static Test suite() {
TestSuite suite = new TestSuite("DatabaseMetaDataTest");
suite.addTest(
TestConfiguration.defaultSuite(DatabaseMetaDataTest.class));
// Test for DERBY-2584 needs a fresh database to ensure that the
// meta-data queries haven't already been compiled. No need to run the
// test in client/server mode since it only tests the compilation of
// meta-data queries.
suite.addTest(
TestConfiguration.singleUseDatabaseDecorator(
// until DERBY-177 is fixed, set lock timeout to prevent the
// test from waiting one minute
DatabasePropertyTestSetup.setLockTimeouts(
new DatabaseMetaDataTest("initialCompilationTest"), 2, 4)));
return suite;
}
/**
* Return the identifiers used to create schemas,
* tables etc. in the order the database stores them.
*/
private String[] getSortedIdentifiers()
{
String[] dbIDS = new String[IDS.length];
// Remove any quotes from user schemas and upper case
// those without quotes.
for (int i = 0; i < IDS.length; i++)
{
dbIDS[i] = getStoredIdentifier(IDS[i]);
}
Arrays.sort(dbIDS);
return dbIDS;
}
private final DatabaseMetaData getDMD() throws SQLException
{
return getConnection().getMetaData();
}
/**
* Tests that a meta-data query is compiled and stored correctly even when
* there's a lock on the system tables (DERBY-2584). This test must run on
* a fresh database (that is, <code>getIndexInfo</code> must not have been
* prepared and stored in <code>SYS.SYSSTATEMENTS</code>).
*/
public void initialCompilationTest() throws SQLException {
Connection c = getConnection();
c.setAutoCommit(false);
c.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
Statement s = createStatement();
// First get shared row locks on the SYSSTATEMENTS table.
JDBC.assertDrainResults(
s.executeQuery("SELECT * FROM SYS.SYSSTATEMENTS"));
s.close();
// Execute getIndexInfo() for the first time. Because of the shared
// locks on SYSSTATEMENTS, the query is compiled in the main
// transaction.
getDMD().getIndexInfo(null, null, "T", false, false).close();
// Re-use the previously compiled query from disk. Fails with
// ArrayIndexOutOfBoundsException before DERBY-2584.
getDMD().getIndexInfo(null, null, "T", false, false).close();
}
/**
* Test the methods that indicate if a feature
* is supported or not. Methods start with
* 'support'. See secton 7.3 in JDBC 3.0 specification.
*
* @throws SQLException
*
*/
public void testDetermineFeatureSupport() throws SQLException
{
DatabaseMetaData dmd = getDMD();
assertTrue(dmd.supportsAlterTableWithAddColumn());
assertTrue(dmd.supportsAlterTableWithDropColumn());
/* DERBY-2243 Derby does support ANSI 92 standards
* and this behaviour is now consistant across drivers
*/
assertTrue(dmd.supportsANSI92EntryLevelSQL());
assertFalse(dmd.supportsANSI92FullSQL());
assertFalse(dmd.supportsANSI92IntermediateSQL());
assertTrue(dmd.supportsBatchUpdates());
assertFalse(dmd.supportsCatalogsInDataManipulation());
assertFalse(dmd.supportsCatalogsInIndexDefinitions());
assertFalse(dmd.supportsCatalogsInPrivilegeDefinitions());
assertFalse(dmd.supportsCatalogsInProcedureCalls());
assertFalse(dmd.supportsCatalogsInTableDefinitions());
assertTrue(dmd.supportsColumnAliasing());
// Bug DERBY-462 should return false.
assertTrue(dmd.supportsConvert());
// Simple check since convert is not supported.
// A comprehensive test should be added when convert
// is supported, though most likely in a test class
// specific to convert.
assertFalse(dmd.supportsConvert(Types.INTEGER, Types.SMALLINT));
assertFalse(dmd.supportsCoreSQLGrammar());
assertTrue(dmd.supportsCorrelatedSubqueries());
assertTrue(dmd.supportsDataDefinitionAndDataManipulationTransactions());
assertFalse(dmd.supportsDataManipulationTransactionsOnly());
assertTrue(dmd.supportsDifferentTableCorrelationNames());
/* DERBY-2244 Derby does support Order By clause
* thus the changing the assert condition to TRUE
*/
assertTrue(dmd.supportsExpressionsInOrderBy());
assertFalse(dmd.supportsExtendedSQLGrammar());
assertFalse(dmd.supportsFullOuterJoins());
assertFalse(dmd.supportsGetGeneratedKeys());
assertTrue(dmd.supportsGroupBy());
assertTrue(dmd.supportsGroupByBeyondSelect());
assertTrue(dmd.supportsGroupByUnrelated());
assertFalse(dmd.supportsIntegrityEnhancementFacility());
assertTrue(dmd.supportsLikeEscapeClause());
assertTrue(dmd.supportsLimitedOuterJoins());
assertTrue(dmd.supportsMinimumSQLGrammar());
assertFalse(dmd.supportsMixedCaseIdentifiers());
assertTrue(dmd.supportsMixedCaseQuotedIdentifiers());
assertTrue(dmd.supportsMultipleOpenResults());
assertTrue(dmd.supportsMultipleResultSets());
assertTrue(dmd.supportsMultipleTransactions());
assertFalse(dmd.supportsNamedParameters());
assertTrue(dmd.supportsNonNullableColumns());
// Open cursors are not supported across global
// (XA) transactions so the driver returns false.
assertFalse(dmd.supportsOpenCursorsAcrossCommit());
assertFalse(dmd.supportsOpenCursorsAcrossRollback());
assertTrue(dmd.supportsOpenStatementsAcrossCommit());
assertFalse(dmd.supportsOpenStatementsAcrossRollback());
assertFalse(dmd.supportsOrderByUnrelated());
assertTrue(dmd.supportsOuterJoins());
assertTrue(dmd.supportsPositionedDelete());
assertTrue(dmd.supportsPositionedUpdate());
assertTrue(dmd.supportsResultSetConcurrency(
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY));
assertTrue(dmd.supportsResultSetConcurrency(
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE));
assertTrue(dmd.supportsResultSetConcurrency(
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY));
assertTrue(dmd.supportsResultSetConcurrency(
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE));
assertFalse(dmd.supportsResultSetConcurrency(
ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY));
assertFalse(dmd.supportsResultSetConcurrency(
ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE));
assertTrue(dmd.supportsResultSetHoldability(
ResultSet.CLOSE_CURSORS_AT_COMMIT));
assertTrue(dmd.supportsResultSetHoldability(
ResultSet.HOLD_CURSORS_OVER_COMMIT));
assertTrue(dmd.supportsResultSetType(
ResultSet.TYPE_FORWARD_ONLY));
assertTrue(dmd.supportsResultSetType(
ResultSet.TYPE_SCROLL_INSENSITIVE));
assertFalse(dmd.supportsResultSetType(
ResultSet.TYPE_SCROLL_SENSITIVE));
assertTrue(dmd.supportsSavepoints());
assertTrue(dmd.supportsSchemasInDataManipulation());
assertTrue(dmd.supportsSchemasInIndexDefinitions());
assertTrue(dmd.supportsSchemasInPrivilegeDefinitions());
assertTrue(dmd.supportsSchemasInProcedureCalls());
assertTrue(dmd.supportsSchemasInTableDefinitions());
assertTrue(dmd.supportsSelectForUpdate());
assertFalse(dmd.supportsStatementPooling());
assertTrue(dmd.supportsStoredProcedures());
assertTrue(dmd.supportsSubqueriesInComparisons());
assertTrue(dmd.supportsSubqueriesInExists());
assertTrue(dmd.supportsSubqueriesInIns());
assertTrue(dmd.supportsSubqueriesInQuantifieds());
assertTrue(dmd.supportsTableCorrelationNames());
assertTrue(dmd.supportsTransactionIsolationLevel(
Connection.TRANSACTION_READ_COMMITTED));
assertTrue(dmd.supportsTransactionIsolationLevel(
Connection.TRANSACTION_READ_UNCOMMITTED));
assertTrue(dmd.supportsTransactionIsolationLevel(
Connection.TRANSACTION_REPEATABLE_READ));
assertTrue(dmd.supportsTransactionIsolationLevel(
Connection.TRANSACTION_SERIALIZABLE));
assertTrue(dmd.supportsTransactions());
assertTrue(dmd.supportsUnion());
assertTrue(dmd.supportsUnionAll());
}
/**
* Test group of methods provides the limits imposed by a given data source
* Methods start with
* 'getMax'. See section 7.4 in JDBC 3.0 specification.
*
* Note a return of zero from one of these functions means
* no limit or limit not known.
*
* @throws SQLException
*
*/
public void testDataSourceLimits() throws SQLException
{
DatabaseMetaData dmd = getDMD();
assertEquals(0, dmd.getMaxBinaryLiteralLength());
// Catalogs not supported.
assertEquals(0, dmd.getMaxCatalogNameLength());
assertEquals(0, dmd.getMaxCharLiteralLength());
assertEquals(128, dmd.getMaxColumnNameLength());
assertEquals(0, dmd.getMaxColumnsInGroupBy());
assertEquals(0, dmd.getMaxColumnsInIndex());
assertEquals(0, dmd.getMaxColumnsInOrderBy());
assertEquals(0, dmd.getMaxColumnsInSelect());
assertEquals(0, dmd.getMaxColumnsInTable());
assertEquals(0, dmd.getMaxConnections());
assertEquals(128, dmd.getMaxCursorNameLength());
assertEquals(0, dmd.getMaxIndexLength());
assertEquals(128, dmd.getMaxProcedureNameLength());
assertEquals(0, dmd.getMaxRowSize());
assertEquals(128, dmd.getMaxSchemaNameLength());
assertEquals(0, dmd.getMaxStatementLength());
assertEquals(0, dmd.getMaxStatements());
assertEquals(128, dmd.getMaxTableNameLength());
assertEquals(0, dmd.getMaxTablesInSelect());
assertEquals(30, dmd.getMaxUserNameLength());
}
public void testMiscellaneous() throws SQLException
{
DatabaseMetaData dmd = getDMD();
assertTrue(dmd.allProceduresAreCallable());
assertTrue(dmd.allTablesAreSelectable());
assertFalse(dmd.dataDefinitionCausesTransactionCommit());
assertFalse(dmd.dataDefinitionIgnoredInTransactions());
assertFalse(dmd.deletesAreDetected(ResultSet.TYPE_FORWARD_ONLY));
assertTrue(dmd.deletesAreDetected(ResultSet.TYPE_SCROLL_INSENSITIVE));
assertFalse(dmd.deletesAreDetected(ResultSet.TYPE_SCROLL_SENSITIVE));
assertTrue(dmd.doesMaxRowSizeIncludeBlobs());
// Catalogs not supported, so empty string returned for separator.
assertEquals("", dmd.getCatalogSeparator());
assertEquals("CATALOG", dmd.getCatalogTerm());
assertEquals(Connection.TRANSACTION_READ_COMMITTED,
dmd.getDefaultTransactionIsolation());
assertEquals("", dmd.getExtraNameCharacters());
assertEquals("\"", dmd.getIdentifierQuoteString());
assertEquals("PROCEDURE", dmd.getProcedureTerm());
assertEquals(ResultSet.HOLD_CURSORS_OVER_COMMIT,
dmd.getResultSetHoldability());
assertEquals("SCHEMA", dmd.getSchemaTerm());
assertEquals("", dmd.getSearchStringEscape());
assertEquals(DatabaseMetaData.sqlStateSQL99,
dmd.getSQLStateType());
assertFalse(dmd.isCatalogAtStart());
assertTrue(dmd.locatorsUpdateCopy());
assertTrue(dmd.usesLocalFilePerTable());
assertTrue(dmd.usesLocalFiles());
}
/**
* Methods that describe the version of the
* driver and database.
*/
public void testVersionInfo() throws SQLException
{
DatabaseMetaData dmd = getDMD();
int databaseMajor = dmd.getDatabaseMajorVersion();
int databaseMinor = dmd.getDatabaseMinorVersion();
int driverMajor = dmd.getDriverMajorVersion();
int driverMinor = dmd.getDriverMinorVersion();
String databaseVersion = dmd.getDatabaseProductVersion();
String driverVersion = dmd.getDriverVersion();
if (usingEmbedded())
{
// Database *is* the driver.
assertEquals("Embedded Major version ",
databaseMajor, driverMajor);
assertEquals("Embedded Minor version ",
databaseMinor, driverMinor);
assertEquals("Embedded version",
databaseVersion, driverVersion);
}
assertEquals("Apache Derby", dmd.getDatabaseProductName());
String driverName = dmd.getDriverName();
if (usingEmbedded())
{
assertEquals("Apache Derby Embedded JDBC Driver",
driverName);
}
else if (usingDerbyNetClient())
{
assertEquals("Apache Derby Network Client JDBC Driver",
driverName);
}
int jdbcMajor = dmd.getJDBCMajorVersion();
int jdbcMinor = dmd.getJDBCMinorVersion();
int expectedJDBCMajor = -1;
if (JDBC.vmSupportsJDBC4())
{
expectedJDBCMajor = 4;
}
else if (JDBC.vmSupportsJDBC3())
{
expectedJDBCMajor = 3;
}
else if (JDBC.vmSupportsJSR169())
{
// Not sure what is the correct output for JSR 169
expectedJDBCMajor = -1;
}
if (expectedJDBCMajor != -1)
{
assertEquals("JDBC Major version",
expectedJDBCMajor, jdbcMajor);
assertEquals("JDBC Minor version", 0, jdbcMinor);
}
}
/**
* getURL() method. Note that this method
* is the only JDBC 3 DatabaseMetaData method
* that is dropped in JSR169.
*/
public void testGetURL() throws SQLException
{
DatabaseMetaData dmd = getDMD();
String url;
try {
url = dmd.getURL();
} catch (NoSuchMethodError e) {
// JSR 169 - method must not be there!
assertTrue("getURL not supported", JDBC.vmSupportsJSR169());
assertFalse("getURL not supported", JDBC.vmSupportsJDBC2());
return;
}
assertFalse("getURL is supported!", JDBC.vmSupportsJSR169());
assertTrue("getURL is supported!", JDBC.vmSupportsJDBC2());
assertEquals("getURL match",
getTestConfiguration().getJDBCUrl(),
url);
}
/**
* Derby stores unquoted identifiers as upper
* case and quoted ones as mixed case.
* They are always compared case sensitive.
*/
public void testIdentifierStorage() throws SQLException
{
DatabaseMetaData dmd = getDMD();
assertFalse(dmd.storesLowerCaseIdentifiers());
assertFalse(dmd.storesLowerCaseQuotedIdentifiers());
assertFalse(dmd.storesMixedCaseIdentifiers());
assertTrue(dmd.storesMixedCaseQuotedIdentifiers());
assertTrue(dmd.storesUpperCaseIdentifiers());
assertFalse(dmd.storesUpperCaseQuotedIdentifiers());
}
/**
* methods that return information about handling NULL.
*/
public void testNullInfo() throws SQLException
{
DatabaseMetaData dmd = getDMD();
assertTrue(dmd.nullPlusNonNullIsNull());
assertFalse(dmd.nullsAreSortedAtEnd());
assertFalse(dmd.nullsAreSortedAtStart());
assertTrue(dmd.nullsAreSortedHigh());
assertFalse(dmd.nullsAreSortedLow());
}
/**
* Method getSQLKeywords, returns list of SQL keywords
* that are not defined by SQL92.
*/
public void testSQLKeywords() throws SQLException
{
String keywords = getDMD().getSQLKeywords();
assertNotNull(keywords);
//TODO: more testing but not sure what!
}
/**
* Methods that return information specific to
* the current connection.
*/
public void testConnectionSpecific() throws SQLException
{
DatabaseMetaData dmd = getDMD();
assertSame(getConnection(), dmd.getConnection());
assertEquals(getTestConfiguration().getUserName(),
dmd.getUserName());
assertEquals(getConnection().isReadOnly(), dmd.isReadOnly());
}
/**
* This is not a test of Derby but JDBC constants for meta data
* that this test depends on.
* The constants for nullability are the same but let's check to make sure.
*
*/
public void testConstants()
{
assertEquals(DatabaseMetaData.columnNoNulls, ResultSetMetaData.columnNoNulls);
assertEquals(DatabaseMetaData.columnNullable, ResultSetMetaData.columnNullable);
assertEquals(DatabaseMetaData.columnNullableUnknown, ResultSetMetaData.columnNullableUnknown);
}
/*
** DatabaseMetaData calls that return ResultSets.
*/
/**
* Test methods that describe attributes of SQL Objects
* that are not supported by derby. In each case the
* metadata should return an empty ResultSet of the
* correct shape, and with correct names, datatypes and
* nullability for the columns in the ResultSet.
*
*/
public void testUnimplementedSQLObjectAttributes() throws SQLException
{
DatabaseMetaData dmd = getDMD();
ResultSet rs;
rs = dmd.getAttributes(null,null,null,null);
String [] columnNames = {
"TYPE_CAT", "TYPE_SCHEM", "TYPE_NAME", "ATTR_NAME", "DATA_TYPE",
"ATTR_TYPE_NAME", "ATTR_SIZE", "DECIMAL_DIGITS", "NUM_PREC_RADIX",
"NULLABLE", "REMARKS", "ATTR_DEF", "SQL_DATA_TYPE",
"SQL_DATETIME_SUB", "CHAR_OCTET_LENGTH", "ORDINAL_POSITION",
"IS_NULLABLE", "SCOPE_CATALOG", "SCOPE_SCHEMA", "SCOPE_TABLE",
"SOURCE_DATA_TYPE"
};
int [] columnTypes = {
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.INTEGER, Types.VARCHAR, Types.INTEGER, Types.INTEGER, Types.INTEGER,
Types.INTEGER, Types.VARCHAR, Types.VARCHAR, Types.INTEGER,
Types.INTEGER, Types.INTEGER, Types.INTEGER,
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.SMALLINT
};
// DERBY-3171; we get a different value back for nullability for
// a number of the columns with networkserver/client vs. embedded
boolean nullval = true;
if (usingDerbyNetClient())
nullval = false;
boolean [] nullability = {
true, true, true, true, nullval, true, nullval,
nullval, nullval, nullval, true, true, nullval, nullval,
nullval, nullval, true, true, true, true, true
};
assertMetaDataResultSet(rs, columnNames, columnTypes, nullability);
JDBC.assertEmpty(rs);
rs = dmd.getCatalogs();
checkCatalogsShape(rs);
JDBC.assertEmpty(rs);
rs = dmd.getSuperTables(null,null,null);
columnNames = new String[] {
"TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", "SUPERTABLE_NAME"};
columnTypes = new int[] {
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR};
nullability = new boolean[] {
true, true, true, true};
assertMetaDataResultSet(rs, columnNames, columnTypes, nullability);
JDBC.assertEmpty(rs);
rs = dmd.getSuperTypes(null,null,null);
columnNames = new String[] {
"TYPE_CAT", "TYPE_SCHEM", "TYPE_NAME", "SUPERTYPE_CAT",
"SUPERTYPE_SCHEM", "SUPERTYPE_NAME"};
columnTypes = new int[] {
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR};
nullability = new boolean[] {
true, true, true, true, true, true};
assertMetaDataResultSet(rs, columnNames, columnTypes, nullability);
JDBC.assertEmpty(rs);
rs = dmd.getUDTs(null,null,null,null);
columnNames = new String[] {
"TYPE_CAT", "TYPE_SCHEM", "TYPE_NAME", "CLASS_NAME",
"DATA_TYPE", "REMARKS", "BASE_TYPE"};
columnTypes = new int[] {
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR};
nullability = new boolean[] {
true, true, true, true};
assertMetaDataResultSet(rs, null, null, null);
JDBC.assertEmpty(rs);
rs = dmd.getVersionColumns(null,null, "No_such_table");
checkVersionColumnsShape(rs);
JDBC.assertEmpty(rs);
}
/**
* Six combinations of valid identifiers with mixed
* case, to see how the various pattern matching
* and returned values handle them.
* This test only creates objects in these schemas.
*/
private static final String[] IDS =
{
"one_dmd_test",
"TWO_dmd_test",
"ThReE_dmd_test",
"\"four_dmd_test\"",
"\"FIVE_dmd_test\"",
"\"sIx_dmd_test\""
};
/**
* All the builtin schemas.
*/
private static final String[] BUILTIN_SCHEMAS = {
"APP", "NULLID", "SQLJ", "SYS", "SYSCAT", "SYSCS_DIAG",
"SYSCS_UTIL", "SYSFUN", "SYSIBM", "SYSPROC", "SYSSTAT"};
public static String getStoredIdentifier(String sqlIdentifier)
{
if (sqlIdentifier.charAt(0) == '"')
return sqlIdentifier.substring(1, sqlIdentifier.length() - 1);
else
return sqlIdentifier.toUpperCase(Locale.ENGLISH);
}
/**
* Test getSchemas() without modifying the database.
*
* @throws SQLException
*/
public void testGetSchemasReadOnly() throws SQLException {
DatabaseMetaData dmd = getDMD();
ResultSet rs = dmd.getSchemas();
checkSchemas(rs, new String[0]);
}
/**
* Test getSchemas().
*
* @throws SQLException
*/
public void testGetSchemasModify() throws SQLException {
createSchemasForTests();
DatabaseMetaData dmd = getDMD();
ResultSet rs = dmd.getSchemas();
checkSchemas(rs, IDS);
}
private void createSchemasForTests() throws SQLException
{
// Set to cleanup on teardown.
modifiedDatabase = true;
Statement s = createStatement();
for (int i = 0; i < IDS.length; i++)
s.executeUpdate("CREATE SCHEMA " + IDS[i]);
s.close();
commit();
}
/**
* Check the returned information from a getSchemas().
* The passed in String[] expected is a list of the
* schemas expected to be present in the returned
* set. The returned set may contain additional
* schemas which will be ignored, thus this test
* can be used regardless of the database state.
* The builtin schemas are automatically checked
* and must not be part of the passed in list.
*/
public static void checkSchemas(ResultSet rs,
String[] userExpected) throws SQLException
{
checkSchemasShape(rs);
// Add in the system schemas
String[] expected =
new String[BUILTIN_SCHEMAS.length + userExpected.length];
System.arraycopy(BUILTIN_SCHEMAS, 0,
expected, 0, BUILTIN_SCHEMAS.length);
System.arraycopy(userExpected, 0,
expected, BUILTIN_SCHEMAS.length, userExpected.length);
// Remove any quotes from user schemas and upper case
// those without quotes.
for (int i = BUILTIN_SCHEMAS.length; i < expected.length; i++)
{
expected[i] = getStoredIdentifier(expected[i]);
}
//output is ordered by TABLE_SCHEM
Arrays.sort(expected);
int nextMatch = 0;
while (rs.next()) {
String schema = rs.getString("TABLE_SCHEM");
assertNotNull(schema);
// Catalogs not supported
assertNull(rs.getString("TABLE_CATALOG"));
if (nextMatch < expected.length)
{
if (expected[nextMatch].equals(schema))
nextMatch++;
}
}
rs.close();
assertEquals("Schemas missing ", expected.length, nextMatch);
}
/**
* Check the shape of the ResultSet from any
* getSchemas call.
*/
private static void checkSchemasShape(ResultSet rs) throws SQLException
{
assertMetaDataResultSet(rs,
new String[] {
"TABLE_SCHEM", "TABLE_CATALOG"
},
new int[] {
Types.VARCHAR, Types.VARCHAR
}
, new boolean[] {false, true}
);
}
/**
* Execute dmd.getTables() but perform additional checking
* of the ODBC variant.
* @throws IOException
*/
private ResultSet getDMDTables(DatabaseMetaData dmd,
String catalog, String schema, String table, String[] tableTypes)
throws SQLException, IOException
{
checkGetTablesODBC(catalog, schema, table, tableTypes);
return dmd.getTables(catalog, schema, table, tableTypes);
}
/**
* Test getTables() without modifying the database.
*
* @throws SQLException
* @throws IOException
*/
public void testGetTablesReadOnly() throws SQLException, IOException {
DatabaseMetaData dmd = getDMD();
ResultSet rs;
rs = getDMDTables(dmd, null, null, null, null);
checkTablesShape(rs);
int allTableCount = JDBC.assertDrainResults(rs);
assertTrue("getTables() on all was empty!", allTableCount > 0);
rs = getDMDTables(dmd, "%", "%", "%", null);
checkTablesShape(rs);
assertEquals("Different counts from getTables",
allTableCount, JDBC.assertDrainResults(rs));
rs = getDMDTables(dmd, null, "NO_such_schema", null, null);
checkTablesShape(rs);
JDBC.assertEmpty(rs);
rs = getDMDTables(dmd, null, "SQLJ", null, null);
checkTablesShape(rs);
JDBC.assertEmpty(rs);
rs = getDMDTables(dmd, null, "SQLJ", "%", null);
checkTablesShape(rs);
JDBC.assertEmpty(rs);
rs = getDMDTables(dmd, null, "SYS", "No_such_table", null);
checkTablesShape(rs);
JDBC.assertEmpty(rs);
String[] userTableOnly = new String[] {"TABLE"};
// no user tables in SYS
rs = getDMDTables(dmd, null, "SYS", null, userTableOnly);
checkTablesShape(rs);
JDBC.assertEmpty(rs);
rs = getDMDTables(dmd, null, "SYS", "%", userTableOnly);
checkTablesShape(rs);
JDBC.assertEmpty(rs);
String[] systemTableOnly = new String[] {"SYSTEM_TABLE"};
rs = getDMDTables(dmd, null, "SYS", null, systemTableOnly);
checkTablesShape(rs);
int systemTableCount = JDBC.assertDrainResults(rs);
assertTrue("getTables() on system tables was empty!", systemTableCount > 0);
rs = getDMDTables(dmd, null, "SYS", "%", systemTableOnly);
checkTablesShape(rs);
assertEquals(systemTableCount, JDBC.assertDrainResults(rs));
String[] viewOnly = new String[] {"VIEW"};
rs = getDMDTables(dmd, null, "SYS", null, viewOnly);
JDBC.assertEmpty(rs);
rs = getDMDTables(dmd, null, "SYS", "%", viewOnly);
JDBC.assertEmpty(rs);
String[] allTables = {"SYNONYM","SYSTEM TABLE","TABLE","VIEW"};
rs = getDMDTables(dmd, null, null, null, allTables);
checkTablesShape(rs);
assertEquals("Different counts from getTables",
allTableCount, JDBC.assertDrainResults(rs));
rs = getDMDTables(dmd, "%", "%", "%", allTables);
checkTablesShape(rs);
assertEquals("Different counts from getTables",
allTableCount, JDBC.assertDrainResults(rs));
}
/**
* Test getTables() with modifying the database.
*
* @throws SQLException
* @throws IOException
*/
public void testGetTablesModify() throws SQLException, IOException {
int totalTables = createTablesForTest(false);
DatabaseMetaData dmd = getDMD();
ResultSet rs;
String[] userTableOnly = new String[] {"TABLE"};
// Get the list of idenifiers from IDS as the database
// would store them in the order required.
String[] dbIDS = getSortedIdentifiers();
// Check the contents, ordered by TABLE_CAT, TABLE_SCHEMA, TABLE_NAME
rs = getDMDTables(dmd, null, null, null, userTableOnly);
checkTablesShape(rs);
int rowPosition = 0;
while (rs.next())
{
//boolean ourTable;
assertEquals("TABLE_CAT", "", rs.getString("TABLE_CAT"));
String schema = rs.getString("TABLE_SCHEM");
// See if the table is in one of the schemas we created.
// If not we perform what checking we can.
boolean ourSchema = Arrays.binarySearch(dbIDS, schema) >= 0;
if (ourSchema) {
assertEquals("TABLE_SCHEM",
dbIDS[rowPosition/dbIDS.length], schema);
assertEquals("TABLE_NAME",
dbIDS[rowPosition%dbIDS.length], rs.getString("TABLE_NAME"));
}
assertEquals("TABLE_TYPE", "TABLE", rs.getString("TABLE_TYPE"));
assertEquals("REMARKS", "", rs.getString("REMARKS"));
assertNull("TYPE_CAT", rs.getString("TYPE_CAT"));
assertNull("TYPE_SCHEM", rs.getString("TYPE_SCHEM"));
assertNull("TYPE_NAME", rs.getString("TYPE_NAME"));
assertNull("SELF_REFERENCING_COL_NAME", rs.getString("SELF_REFERENCING_COL_NAME"));
assertNull("REF_GENERATION", rs.getString("REF_GENERATION"));
if (ourSchema)
rowPosition++;
}
rs.close();
assertEquals("getTables count for all user tables",
totalTables, rowPosition);
Random rand = new Random();
// Test using schema pattern with a pattern unique to
// a single schema.
for (int i = 0; i < dbIDS.length; i++)
{
String schema = dbIDS[i];
int pc = rand.nextInt(6);
String schemaPattern = schema.substring(0, pc + 2) + "%";
rs = getDMDTables(dmd, null, schemaPattern, null, userTableOnly);
checkTablesShape(rs);
rowPosition = 0;
while (rs.next())
{
assertEquals("TABLE_SCHEM",
schema, rs.getString("TABLE_SCHEM"));
assertEquals("TABLE_NAME",
dbIDS[rowPosition%dbIDS.length], rs.getString("TABLE_NAME"));
assertEquals("TABLE_TYPE", "TABLE", rs.getString("TABLE_TYPE"));
rowPosition++;
}
rs.close();
assertEquals("getTables count schema pattern",
dbIDS.length, rowPosition);
}
// Test using table pattern with a pattern unique to
// a single table per schema.
for (int i = 0; i < dbIDS.length; i++)
{
String table = dbIDS[i];
int pc = rand.nextInt(6);
String tablePattern = table.substring(0, pc + 2) + "%";
rs = getDMDTables(dmd, null, null, tablePattern, userTableOnly);
checkTablesShape(rs);
rowPosition = 0;
while (rs.next())
{
assertEquals("TABLE_SCHEM",
dbIDS[rowPosition%dbIDS.length], rs.getString("TABLE_SCHEM"));
assertEquals("TABLE_TYPE", "TABLE", rs.getString("TABLE_TYPE"));
assertEquals("TABLE_NAME",
table, rs.getString("TABLE_NAME"));
rowPosition++;
}
rs.close();
assertEquals("getTables count schema pattern",
dbIDS.length, rowPosition);
}
}
/**
* Execute and check the ODBC variant of getTables which
* uses a procedure to provide the same information to ODBC clients.
* @throws IOException
*/
private void checkGetTablesODBC(String catalog, String schema,
String table, String[] tableTypes) throws SQLException, IOException
{
String tableTypesAsString = null;
if (tableTypes != null) {
int count = tableTypes.length;
StringBuffer sb = new StringBuffer();
for (int i = 0; i < count; i++) {
if (i > 0)
sb.append(",");
sb.append(tableTypes[i]);
}
tableTypesAsString = sb.toString();
}
CallableStatement cs = prepareCall(
"CALL SYSIBM.SQLTABLES(?, ?, ?, ?, 'DATATYPE=''ODBC''')");
cs.setString(1, catalog);
cs.setString(2, schema);
cs.setString(3, table);
cs.setString(4, tableTypesAsString);
cs.execute();
ResultSet odbcrs = cs.getResultSet();
assertNotNull(odbcrs);
// Returned ResultSet will have the same shape as
// DatabaseMetaData.getTables() even though ODBC
// only defines the first five columns.
checkTablesShape(odbcrs);
// Expect the contents of JDBC and ODBC metadata to be the same.
ResultSet dmdrs = getDMD().getTables(catalog, schema, table, tableTypes);
JDBC.assertSameContents(odbcrs, dmdrs);
cs.close();
}
/**
* Create a set of tables using the identifiers in IDS.
* For each identifier in IDS a schema is created.
* For each identifier in IDS create a table in every schema just created.
* Each table has five columns with names using the identifiers from IDS
* suffixed with _N where N is the column number in the table. The base
* name for each column is round-robined from the set of IDS.
* The type of each column is round-robined from the set of supported
* types returned by getSQLTypes.
*
* <BR>
* skipXML can be set to true to create tables without any XML
* columns. This is useful for getColumns() testing where
* the fixture compares the output of DatabaseMetaData to
* ResultSetMetaData by a SELCT * from the table. However
* for XML columns they cannot be returned through JDBC yet.
*
* @param skipXML true if tables with the XML column should not
* be created.
* @throws SQLException
*/
private int createTablesForTest(boolean skipXML) throws SQLException
{
getConnection().setAutoCommit(false);
List types = getSQLTypes(getConnection());
if (skipXML)
types.remove("XML");
int typeCount = types.size();
createSchemasForTests();
Statement s = createStatement();
int columnCounter = 0;
for (int sid = 0; sid < IDS.length; sid++) {
for (int tid = 0; tid < IDS.length; tid++)
{
StringBuffer sb = new StringBuffer();
sb.append("CREATE TABLE ");
sb.append(IDS[sid]);
sb.append('.');
sb.append(IDS[tid]);
sb.append(" (");
// Five columns per table
for (int c = 1; c <= 5; c++) {
String colName = IDS[columnCounter % IDS.length];
boolean delimited = colName.charAt(colName.length() - 1) == '"';
if (delimited)
colName = colName.substring(0, colName.length() - 1);
sb.append(colName);
sb.append('_');
sb.append(c); // append the column number
if (delimited)
sb.append('"');
sb.append(' ');
sb.append(types.get(columnCounter++ % typeCount));
if (c < 5)
sb.append(", ");
}
sb.append(")");
s.execute(sb.toString());
}
}
s.close();
commit();
return IDS.length * IDS.length;
}
/**
* Test getTableColumns().
* Contents are compared to the ResultSetMetaData
* for a SELECT * from the table. All columns in
* all tables are checked.
*/
public void testGetColumnsReadOnly() throws SQLException
{
DatabaseMetaData dmd = getDMD();
ResultSet rs = dmd.getColumns(null, null, null, null);
checkColumnsShape(rs);
crossCheckGetColumnsAndResultSetMetaData(rs, false);
}
/**
* Test getColumns() with modifying the database.
*
* @throws SQLException
*/
public void testGetColumnsModify() throws SQLException {
// skip XML datatype as our cross check with
// ResultSetMetaData will fail
int totalTables = createTablesForTest(true);
// First cross check all the columns in the database
// with the ResultSetMetaData.
testGetColumnsReadOnly();
Random rand = new Random();
String[] dbIDS = getSortedIdentifiers();
DatabaseMetaData dmd = this.getDMD();
for (int i = 1; i < 20; i++) {
int seenColumnCount = 0;
// These are the pattern matching parameters
String schemaPattern = getPattern(rand, dbIDS);
String tableNamePattern = getPattern(rand, dbIDS);
String columnNamePattern = getPattern(rand, dbIDS);
ResultSet rs = dmd.getColumns(null,
schemaPattern, tableNamePattern, columnNamePattern);
checkColumnsShape(rs);
while (rs.next())
{
String schema = rs.getString("TABLE_SCHEM");
String table = rs.getString("TABLE_NAME");
String column = rs.getString("COLUMN_NAME");
assertMatchesPattern(schemaPattern, schema);
assertMatchesPattern(tableNamePattern, table);
assertMatchesPattern(columnNamePattern, column);
seenColumnCount++;
}
rs.close();
// Re-run to check the correct data is returned
// when filtering is enabled
rs = dmd.getColumns(null,
schemaPattern, tableNamePattern, columnNamePattern);
crossCheckGetColumnsAndResultSetMetaData(rs, true);
// Now re-execute fetching all schemas, columns etc.
// and see we can the same result when we "filter"
// in the application
int appColumnCount = 0;
rs = dmd.getColumns(null,null, null, null);
while (rs.next())
{
String schema = rs.getString("TABLE_SCHEM");
String table = rs.getString("TABLE_NAME");
String column = rs.getString("COLUMN_NAME");
if (!doesMatch(schemaPattern, 0, schema, 0))
continue;
if (!doesMatch(tableNamePattern, 0, table, 0))
continue;
if (!doesMatch(columnNamePattern, 0, column, 0))
continue;
appColumnCount++;
}
rs.close();
assertEquals("Mismatched column count on getColumns() filtering",
seenColumnCount, appColumnCount);
}
}
private void assertMatchesPattern(String pattern, String result)
{
if (!doesMatch(pattern, 0, result, 0))
{
fail("Bad pattern matching:" + pattern +
" result:" + result);
}
}
/**
* See if a string matches the pattern as defined by
* DatabaseMetaData. By passing in non-zero values
* can check sub-sets of the pattern against the
* sub strings of the result.
* <BR>
* _ matches a single character
* <BR>
* % matches zero or more characters
* <BR>
* Other characters match themselves.
* @param pattern Pattern
* @param pp Position in pattern to start the actual pattern from
* @param result result string
* @param rp position in result to starting checking
* @return true if a match is found
*/
private boolean doesMatch(String pattern, int pp,
String result, int rp)
{
// Find a match
for (;;)
{
if (pp == pattern.length() && rp == result.length())
return true;
// more characters to match in the result but
// no more pattern.
if (pp == pattern.length())
return false;
char pc = pattern.charAt(pp);
if (pc == '_')
{
// need to match a single character but
// exhausted result, so no match.
if (rp == result.length())
return false;
pp++;
rp++;
}
else if (pc == '%')
{
// % at end, complete match regardless of
// position of result since % matches zero or more.
if (pp == pattern.length() - 1)
{
return true;
}
// Brut force, we have a pattern like %X
// and we are say in the third character of
// abCdefgX
// then start a 'CdefgX' and look for a match,
// then 'defgX' etc.
for (int sp = rp; sp < result.length(); sp++)
{
if (doesMatch(pattern, pp+1, result, sp))
{
// Have a match for the pattern after the %
// which means we have a match for the pattern
// with the % since we can match 0 or mor characters
// with %.
return true;
}
}
// Could not match the pattern after the %
return false;
}
else
{
// need to match a single character but
// exhausted result, so no match.
if (rp == result.length())
return false;
// Single character, must match exactly.
if (pc != result.charAt(rp))
{
//Computer says no.
return false;
}
pp++;
rp++;
}
}
}
private String getPattern(Random rand, String[] dbIDS)
{
int y = rand.nextInt(100);
if (y < 10)
return "%"; // All
if (y < 30)
return dbIDS[rand.nextInt(dbIDS.length)]; // exact match
String base;
if (y < 40)
{
// Base for some pattern that can never match
base = "XxZZzXXZZZxxXxZz";
}
else
{
base = dbIDS[rand.nextInt(dbIDS.length)];
}
StringBuffer sb = new StringBuffer();
for (int i = 0; i < base.length();)
{
int x = rand.nextInt(10);
if (x < 5)
x = 0; // bias towards keeping the characters.
boolean inWild;
if (sb.length() == 0)
inWild = false;
else
{
char last = sb.charAt(sb.length() - 1);
inWild = last == '_' || last == '%';
}
if (x == 0)
{
// character from base
sb.append(base.charAt(i++));
}
else if (x == 5)
{
i++;
// single character match
if (!inWild)
sb.append('_');
}
else
{
i += (x - 5);
// replace a number of characters with %
if (!inWild)
sb.append('%');
}
}
// Some pattern involving
return sb.toString();
}
/**
* Compare a ResultSet from getColumns() with ResultSetMetaData
* returned from a SELECT * against the table. This method
* handles situations where a full set of the columns are in
* the ResultSet.
* The first action is to call rs.next().
* The ResultSet will be closed by this method.
* @param rs
* @throws SQLException
*/
private void crossCheckGetColumnsAndResultSetMetaData(ResultSet rs,
boolean partial)
throws SQLException
{
Statement s = createStatement();
while (rs.next())
{
String schema = rs.getString("TABLE_SCHEM");
String table = rs.getString("TABLE_NAME");
ResultSet rst = s.executeQuery(
"SELECT * FROM " + JDBC.escape(schema, table));
ResultSetMetaData rsmdt = rst.getMetaData();
for (int col = 1; col <= rsmdt.getColumnCount() ; col++)
{
if (!partial) {
if (col != 1)
assertTrue(rs.next());
assertEquals("ORDINAL_POSITION",
col, rs.getInt("ORDINAL_POSITION"));
}
assertEquals("TABLE_CAT",
"", rs.getString("TABLE_CAT"));
assertEquals("TABLE_SCHEM",
schema, rs.getString("TABLE_SCHEM"));
assertEquals("TABLE_NAME",
table, rs.getString("TABLE_NAME"));
crossCheckGetColumnRowAndResultSetMetaData(rs, rsmdt);
if (partial)
break;
}
rst.close();
}
rs.close();
s.close();
}
/**
* Cross check a single row from getColumns() with ResultSetMetaData
* for a SELECT * from the same table.
* @param rs ResultSet from getColumns already positioned on the row.
* @param rsmdt ResultSetMetaData for the SELECT *
* @throws SQLException
*/
public static void crossCheckGetColumnRowAndResultSetMetaData(
ResultSet rs, ResultSetMetaData rsmdt)
throws SQLException
{
int col = rs.getInt("ORDINAL_POSITION");
assertEquals("RSMD.getCatalogName",
rsmdt.getCatalogName(col), rs.getString("TABLE_CAT"));
assertEquals("RSMD.getSchemaName",
rsmdt.getSchemaName(col), rs.getString("TABLE_SCHEM"));
assertEquals("RSMD.getTableName",
rsmdt.getTableName(col), rs.getString("TABLE_NAME"));
assertEquals("COLUMN_NAME",
rsmdt.getColumnName(col), rs.getString("COLUMN_NAME"));
// DERBY-2285 BOOLEAN columns appear different on
// network client.
// DMD returns BOOLEAN
// RSMD returns SMALLINT
int dmdColumnType = rs.getInt("DATA_TYPE");
if (dmdColumnType == Types.BOOLEAN && usingDerbyNetClient())
{
assertEquals("TYPE_NAME",
"BOOLEAN", rs.getString("TYPE_NAME"));
assertEquals("TYPE_NAME",
"SMALLINT", rsmdt.getColumnTypeName(col));
assertEquals("DATA_TYPE",
Types.SMALLINT, rsmdt.getColumnType(col));
}
else if (dmdColumnType == Types.JAVA_OBJECT && usingDerbyNetClient())
{
// DMD returns JAVA_OBJECT
// RSMD returns LONGVARBINARY!
assertEquals("DATA_TYPE",
Types.LONGVARBINARY, rsmdt.getColumnType(col));
}
else if (dmdColumnType == Types.VARBINARY && usingDerbyNetClient())
{
// DMD returns different type name to RSMD
assertEquals("DATA_TYPE",
Types.VARBINARY, rsmdt.getColumnType(col));
}
else if (dmdColumnType == Types.BINARY && usingDerbyNetClient())
{
// DMD returns different type name to RSMD
assertEquals("DATA_TYPE",
Types.BINARY, rsmdt.getColumnType(col));
}
else if (dmdColumnType == Types.NUMERIC && usingDerbyNetClient())
{
// DERBY-584 inconsistency in numeric & decimal
assertEquals("DATA_TYPE",
Types.DECIMAL, rsmdt.getColumnType(col));
assertEquals("TYPE_NAME",
"DECIMAL", rsmdt.getColumnTypeName(col));
assertEquals("TYPE_NAME",
"NUMERIC", rs.getString("TYPE_NAME"));
}
else
{
assertEquals("DATA_TYPE",
rsmdt.getColumnType(col), rs.getInt("DATA_TYPE"));
assertEquals("TYPE_NAME",
rsmdt.getColumnTypeName(col), rs.getString("TYPE_NAME"));
}
/*
if (dmdColumnType != Types.JAVA_OBJECT) {
System.out.println("TYPE " + rs.getInt("DATA_TYPE"));
System.out.println(JDBC.escape(schema, table) + " " + rs.getString("COLUMN_NAME"));
assertEquals("COLUMN_SIZE",
rsmdt.getPrecision(col), rs.getInt("COLUMN_SIZE"));
}
*/
// not used by JDBC spec
assertEquals("BUFFER_LENGTH", 0, rs.getInt("BUFFER_LENGTH"));
assertTrue("BUFFER_LENGTH", rs.wasNull());
/*
assertEquals("DECIMAL_DIGITS",
rsmdt.getScale(col), rs.getInt("DECIMAL_DIGITS"));
*/
// This assumes the constants defined by DMD and ResultSet
// for nullability are equal. They are by inspection
// and since they are static final and part of a defined
// api by definition they cannot change. We also
// check statically this is true in the testConstants fixture.
assertEquals("NULLABLE",
rsmdt.isNullable(col), rs.getInt("NULLABLE"));
// REMARKS set to empty string by Derby
assertEquals("REMARKS", "", rs.getString("REMARKS"));
// COLUMN_DEF ??
// both unused by JDBC spec
assertEquals("SQL_DATA_TYPE", 0, rs.getInt("SQL_DATA_TYPE"));
assertTrue(rs.wasNull());
assertEquals("SQL_DATETIME_SUB", 0, rs.getInt("SQL_DATETIME_SUB"));
assertTrue(rs.wasNull());
// IS_NULLABLE
switch (rsmdt.isNullable(col))
{
case ResultSetMetaData.columnNoNulls:
assertEquals("IS_NULLABLE", "NO", rs.getString("IS_NULLABLE"));
break;
case ResultSetMetaData.columnNullable:
assertEquals("IS_NULLABLE", "YES", rs.getString("IS_NULLABLE"));
break;
case ResultSetMetaData.columnNullableUnknown:
assertEquals("IS_NULLABLE", "", rs.getString("IS_NULLABLE"));
break;
default:
fail("invalid return from rsmdt.isNullable(col)");
}
// SCOPE not supported
assertNull("SCOPE_CATLOG", rs.getString("SCOPE_CATLOG"));
assertNull("SCOPE_SCHEMA", rs.getString("SCOPE_SCHEMA"));
assertNull("SCOPE_TABLE", rs.getString("SCOPE_TABLE"));
// DISTINCT not supported
assertEquals("SOURCE_DATA_TYPE", 0, rs.getShort("SOURCE_DATA_TYPE"));
assertTrue(rs.wasNull());
// IS_AUTOINCREMENT added in JDBC 4.0
assertEquals("IS_AUTOINCREMENT",
rsmdt.isAutoIncrement(col) ? "YES" : "NO",
rs.getString("IS_AUTOINCREMENT"));
assertFalse(rs.wasNull());
}
/**
* Test getTableTypes()
*/
public void testTableTypes() throws SQLException
{
DatabaseMetaData dmd = getDMD();
ResultSet rs = dmd.getTableTypes();
assertMetaDataResultSet(rs,
new String[] {
"TABLE_TYPE"
},
new int[] {
Types.VARCHAR
}
, null
);
JDBC.assertFullResultSet(rs, new String[][]
{
{"SYNONYM"},{"SYSTEM TABLE"},{"TABLE"},{"VIEW"},
}, true);
rs.close();
}
/**
* Test getTypeInfo
* @throws SQLException
*/
public void testGetTypeInfo() throws SQLException
{
// Client returns BOOLEAN type from the engine as SMALLINT
int BOOLEAN = Types.BOOLEAN;
if (usingDerbyNetClient())
BOOLEAN = Types.SMALLINT;
String[] JDBC_COLUMN_NAMES = new String[] {
"TYPE_NAME", "DATA_TYPE", "PRECISION", "LITERAL_PREFIX",
"LITERAL_SUFFIX", "CREATE_PARAMS", "NULLABLE", "CASE_SENSITIVE",
"SEARCHABLE", "UNSIGNED_ATTRIBUTE", "FIXED_PREC_SCALE",
"AUTO_INCREMENT", "LOCAL_TYPE_NAME",
"MINIMUM_SCALE", "MAXIMUM_SCALE",
"SQL_DATA_TYPE", "SQL_DATETIME_SUB",
"NUM_PREC_RADIX"
};
int[] JDBC_COLUMN_TYPES = new int[] {
Types.VARCHAR, Types.INTEGER, Types.INTEGER, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR, Types.SMALLINT, BOOLEAN,
Types.SMALLINT, BOOLEAN, BOOLEAN,
BOOLEAN, Types.VARCHAR,
Types.SMALLINT, Types.SMALLINT,
Types.INTEGER, Types.INTEGER,
Types.INTEGER
};
boolean[] JDBC_COLUMN_NULLABILITY = {
false, false, true, true,
true, true, false, false,
false, true, false,
true, true,
true, true,
true, true,
true
};
// DERBY-2307 Nullablity is wrong for columns 1,7,9 (1-based)
// Make a modified copy of JDBC_COLUMN_NULLABILITY
// here to allow the test to pass. Left JDBC_COLUMN_NULLABILITY
// as the expected versions as it is also used for the ODBC
// checks below and has the correct values.
boolean[] JDBC_COLUMN_NULLABILITY_DERBY_2307 = {
true, false, true, true,
true, true, true, false,
true, true, false,
true, true,
true, true,
true, true,
true
};
ResultSet rs = getDMD().getTypeInfo();
assertMetaDataResultSet(rs, JDBC_COLUMN_NAMES, JDBC_COLUMN_TYPES
, JDBC_COLUMN_NULLABILITY_DERBY_2307
);
/*
Derby-2258 Removed 3 data types which are not supported by Derby
and added XML data type which is supported by Derby
*/
int[] supportedTypes = new int[] {
Types.BIGINT, Types.BINARY, Types.BLOB,
Types.CHAR, Types.CLOB, Types.DATE,
Types.DECIMAL, Types.DOUBLE, Types.FLOAT,
Types.INTEGER, Types.LONGVARBINARY, Types.LONGVARCHAR,
Types.NUMERIC, Types.REAL, Types.SMALLINT,
Types.TIME, Types.TIMESTAMP, Types.VARBINARY,
Types.VARCHAR, JDBC.SQLXML
};
// Rows are returned from getTypeInfo in order of
// "DATA_TYPE" (which is a constant from java.sql.Types)
Arrays.sort(supportedTypes);
int offset = 0;
while (rs.next()) {
// TYPE_NAME (column 1)
String typeName = rs.getString("TYPE_NAME");
assertNotNull(typeName);
// DATA_TYPE (column 2)
int type = rs.getInt("DATA_TYPE");
assertFalse(rs.wasNull());
if (supportedTypes[offset] != type)
{
fail("Unexpected type " + typeName);
}
else
{
offset++;
}
// PRECISION (column 3)
int precision = -1;
switch (type)
{
case Types.BINARY:
case Types.CHAR:
precision = 254;
break;
case Types.BLOB:
case Types.CLOB:
precision = Integer.MAX_VALUE;
break;
case Types.DATE:
precision = 10;
break;
case Types.TIME:
precision = 8;
break;
case Types.TIMESTAMP:
precision = 26;
break;
case Types.DECIMAL:
case Types.NUMERIC:
precision = 31;
break;
case Types.DOUBLE:
case Types.FLOAT:
precision = 52;
break;
case Types.REAL:
precision = 23;
break;
case Types.BIGINT:
precision = 19;
break;
case Types.INTEGER:
precision = 10;
break;
case Types.SMALLINT:
precision = 5;
break;
case Types.LONGVARBINARY:
case Types.LONGVARCHAR:
precision = 32700;
break;
/*
Derby-2260 Correcting the precision value for VARCHAR FOR BIT DATA
Thus this test also now expects the correct value i.e. 32672
Also adding precision check for SQLXML data type
*/
case Types.VARBINARY:
precision = 32672;
break;
case Types.VARCHAR:
precision = 32672;
break;
case JDBC.SQLXML:
precision = 0;
break;
}
assertEquals("PRECISION " + typeName,
precision, rs.getInt("PRECISION"));
/*
Precision value is null for XML data type
*/
if (typeName.equals("XML" ))
assertTrue(rs.wasNull());
else
assertFalse(rs.wasNull());
// LITERAL_PREFIX (column 4)
// LITERAL_SUFFIX (column 5)
// CREATE_PARAMS (column 6)
String createParams;
switch (type)
{
case Types.CHAR:
case Types.VARCHAR:
case Types.BLOB:
case Types.CLOB:
case Types.BINARY:
case Types.VARBINARY:
createParams = "length";
break;
case Types.DECIMAL:
case Types.NUMERIC:
createParams = "precision,scale";
break;
case Types.FLOAT:
createParams = "precision";
break;
default:
createParams = null;
break;
}
assertEquals("CREATE_PARAMS " + typeName,
createParams, rs.getString("CREATE_PARAMS"));
// NULLABLE (column 7) - all types are nullable in Derby
assertEquals("NULLABLE " + typeName,
DatabaseMetaData.typeNullable, rs.getInt("NULLABLE"));
assertFalse(rs.wasNull());
// CASE_SENSITIVE (column 8)
// SEARCHABLE (column 9) - most types searchable
{
int searchable;
switch (type)
{
/*
Derby-2259 Correcting the searchable value for
LONGVARBINARY, LONGVARCHAR & BLOB data type
also adding SQLXML data type in the test.
*/
case Types.LONGVARBINARY:
searchable = DatabaseMetaData.typePredNone;
break;
case Types.LONGVARCHAR:
searchable = DatabaseMetaData.typePredChar;
break;
case Types.BLOB:
searchable = DatabaseMetaData.typePredNone;
break;
case Types.CLOB:
searchable = DatabaseMetaData.typePredChar;
break;
case Types.CHAR:
case Types.VARCHAR:
searchable = DatabaseMetaData.typeSearchable;
break;
case JDBC.SQLXML:
searchable = DatabaseMetaData.typePredNone;
break;
default:
searchable = DatabaseMetaData.typePredBasic;
break;
}
assertEquals("SEARCHABLE " + typeName,
searchable, rs.getInt("SEARCHABLE"));
}
// UNSIGNED_ATTRIBUTE (column 10)
//assertFalse("UNSIGNED_ATTRIBUTE " + typeName,
// rs.getBoolean("UNSIGNED_ATTRIBUTE"));
// FIXED_PREC_SCALE (column 11)
boolean fixedScale = type == Types.DECIMAL || type == Types.NUMERIC;
assertEquals("FIXED_PREC_SCALE " + typeName,
fixedScale, rs.getBoolean("FIXED_PREC_SCALE"));
assertFalse(rs.wasNull());
// AUTO_INCREMENT (column 12)
boolean autoIncrement;
switch (type)
{
case Types.BIGINT:
case Types.INTEGER:
case Types.SMALLINT:
autoIncrement = true;
break;
default:
autoIncrement = false;
break;
}
assertEquals("AUTO_INCREMENT " + typeName,
autoIncrement, rs.getBoolean("AUTO_INCREMENT"));
// LOCAL_TYPE_NAME (column 13) always the same as TYPE_NAME
assertEquals("LOCAL_TYPE_NAME " + typeName,
typeName, rs.getString("LOCAL_TYPE_NAME"));
int maxScale;
boolean hasScale = true;
switch (type)
{
case Types.DECIMAL:
case Types.NUMERIC:
maxScale = 31; // Max Scale for Decimal & Numeric is 31: Derby-2262
break;
case Types.TIMESTAMP:
maxScale = 6;
break;
case Types.SMALLINT:
case Types.INTEGER:
case Types.BIGINT:
case Types.DATE:
case Types.TIME:
maxScale = 0;
break;
default:
maxScale = 0;
hasScale = false;
break;
}
// MINIMUM_SCALE (column 14)
assertEquals("MINIMUM_SCALE " + typeName,
0, rs.getInt("MINIMUM_SCALE"));
assertEquals("MINIMUM_SCALE (wasNull) " + typeName,
!hasScale, rs.wasNull());
// MAXIMUM_SCALE (column 15)
assertEquals("MAXIMUM_SCALE " + typeName,
maxScale, rs.getInt("MAXIMUM_SCALE"));
assertEquals("MAXIMUM_SCALE (wasNull)" + typeName,
!hasScale, rs.wasNull());
// SQL_DATA_TYPE (column 16) - Unused
assertEquals("SQL_DATA_TYPE " + typeName,
0, rs.getInt("SQL_DATA_TYPE"));
assertTrue(rs.wasNull());
// SQL_DATETIME_SUB (column 17) - Unused
assertEquals("SQL_DATETIME_SUB " + typeName,
0, rs.getInt("SQL_DATETIME_SUB"));
assertTrue(rs.wasNull());
// NUM_PREC_RADIX (column 18)
}
rs.close();
// Now check the ODBC version:
// ODBC column names & types differ from JDBC slightly.
// ODBC has one more column.
String[] ODBC_COLUMN_NAMES = new String[19];
System.arraycopy(JDBC_COLUMN_NAMES, 0, ODBC_COLUMN_NAMES, 0,
JDBC_COLUMN_NAMES.length);
ODBC_COLUMN_NAMES[2] = "COLUMN_SIZE";
ODBC_COLUMN_NAMES[11] = "AUTO_UNIQUE_VAL";
ODBC_COLUMN_NAMES[18] = "INTERVAL_PRECISION";
int[] ODBC_COLUMN_TYPES = new int[ODBC_COLUMN_NAMES.length];
System.arraycopy(JDBC_COLUMN_TYPES, 0, ODBC_COLUMN_TYPES, 0,
JDBC_COLUMN_TYPES.length);
ODBC_COLUMN_TYPES[1] = Types.SMALLINT; // DATA_TYPE
ODBC_COLUMN_TYPES[7] = Types.SMALLINT; // CASE_SENSITIVE
ODBC_COLUMN_TYPES[9] = Types.SMALLINT; // UNSIGNED_ATTRIBUTE
ODBC_COLUMN_TYPES[10] = Types.SMALLINT; // FIXED_PREC_SCALE
ODBC_COLUMN_TYPES[11] = Types.SMALLINT; // AUTO_UNIQUE_VAL
ODBC_COLUMN_TYPES[15] = Types.SMALLINT; // SQL_DATA_TYPE
ODBC_COLUMN_TYPES[16] = Types.SMALLINT; // SQL_DATETIME_SUB
ODBC_COLUMN_TYPES[18] = Types.SMALLINT; // INTERVAL_PRECISION
boolean[] ODBC_COLUMN_NULLABILITY = new boolean[ODBC_COLUMN_NAMES.length];
System.arraycopy(JDBC_COLUMN_NULLABILITY, 0, ODBC_COLUMN_NULLABILITY, 0,
JDBC_COLUMN_NULLABILITY.length);
ODBC_COLUMN_NULLABILITY[15] = false; // // SQL_DATETIME_SUB (JDBC unused)
ODBC_COLUMN_NULLABILITY[18] = true; // INTERVAL_PRECISION
CallableStatement cs = prepareCall(
"CALL SYSIBM.SQLGETTYPEINFO (0, 'DATATYPE=''ODBC''')");
cs.execute();
ResultSet odbcrs = cs.getResultSet();
assertNotNull(odbcrs);
assertMetaDataResultSet(odbcrs, ODBC_COLUMN_NAMES, ODBC_COLUMN_TYPES, null);
odbcrs.close();
cs.close();
}
/*
* Check the shape of the ResultSet from any getColumns call.
*/
private void checkColumnsShape(ResultSet rs) throws SQLException
{
assertMetaDataResultSet(rs,
new String[] {
"TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", "COLUMN_NAME",
"DATA_TYPE", "TYPE_NAME", "COLUMN_SIZE", "BUFFER_LENGTH",
"DECIMAL_DIGITS", "NUM_PREC_RADIX", "NULLABLE", "REMARKS",
"COLUMN_DEF", "SQL_DATA_TYPE", "SQL_DATETIME_SUB", "CHAR_OCTET_LENGTH",
"ORDINAL_POSITION", "IS_NULLABLE", "SCOPE_CATLOG", "SCOPE_SCHEMA",
"SCOPE_TABLE", "SOURCE_DATA_TYPE", "IS_AUTOINCREMENT"
},
new int[] {
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.INTEGER, Types.VARCHAR, Types.INTEGER, Types.INTEGER,
Types.INTEGER, Types.INTEGER, Types.INTEGER, Types.VARCHAR,
Types.VARCHAR, Types.INTEGER, Types.INTEGER, Types.INTEGER,
Types.INTEGER, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.SMALLINT, Types.VARCHAR
}
, null
);
}
/**
* Check the shape of the ResultSet from any getTables call.
*/
private void checkTablesShape(ResultSet rs) throws SQLException
{
assertMetaDataResultSet(rs,
new String[] {
"TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", "TABLE_TYPE",
"REMARKS", "TYPE_CAT", "TYPE_SCHEM", "TYPE_NAME",
"SELF_REFERENCING_COL_NAME", "REF_GENERATION"
},
new int[] {
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR
}
, new boolean[] {
true, false, false, true, // TABLE_SCHEM cannot be NULL in Derby
true, true, true, true,
true, true
}
);
}
/**
* Check the shape of the ResultSet from any getCatlogs call.
*/
private void checkCatalogsShape(ResultSet rs) throws SQLException
{
assertMetaDataResultSet(rs,
new String[] {
"TABLE_CAT"
},
new int[] {
Types.CHAR
}
, new boolean[] {false}
);
}
/**
* Check the shape of the ResultSet from any
* getVersionColumns call.
*/
private static void checkVersionColumnsShape(ResultSet rs) throws SQLException
{
assertMetaDataResultSet(rs,
new String[] {
"SCOPE", "COLUMN_NAME", "DATA_TYPE", "TYPE_NAME",
"COLUMN_SIZE", "BUFFER_LENGTH", "DECIMAL_DIGITS", "PSEUDO_COLUMN"
},
new int[] {
Types.SMALLINT, Types.VARCHAR, Types.INTEGER, Types.VARCHAR,
Types.INTEGER, Types.INTEGER, Types.SMALLINT, Types.SMALLINT
}
, null
);
}
public static void assertMetaDataResultSet(ResultSet rs,
String[] columnNames, int[] columnTypes,
boolean[] nullability) throws SQLException
{
assertEquals(ResultSet.TYPE_FORWARD_ONLY, rs.getType());
assertEquals(ResultSet.CONCUR_READ_ONLY, rs.getConcurrency());
//assertNull(rs.getStatement());
if (columnNames != null)
JDBC.assertColumnNames(rs, columnNames);
if (columnTypes != null)
JDBC.assertColumnTypes(rs, columnTypes);
if (nullability != null)
JDBC.assertNullability(rs, nullability);
}
/*
** Set of escaped functions.
*/
/**
* JDBC escaped numeric functions - JDBC 3.0 C.1
* @throws SQLException
*/
public void testNumericFunctions() throws SQLException
{
escapedFunctions(NUMERIC_FUNCTIONS,
getDMD().getNumericFunctions());
}
/**
* JDBC escaped string functions - JDBC 3.0 C.2
* @throws SQLException
*/
public void testStringFunctions() throws SQLException
{
escapedFunctions(STRING_FUNCTIONS,
getDMD().getStringFunctions());
}
/**
* JDBC escaped date time functions - JDBC 3.0 C.3
* @throws SQLException
*/
public void testTimeDataFunctions() throws SQLException
{
escapedFunctions(TIMEDATE_FUNCTIONS,
getDMD().getTimeDateFunctions());
}
/**
* JDBC escaped system functions - JDBC 3.0 C.4
* @throws SQLException
*/
public void testSystemFunctions() throws SQLException
{
escapedFunctions(SYSTEM_FUNCTIONS,
getDMD().getSystemFunctions());
}
/**
* Check that the list of escaped functions provided by
* the driver is a strict subet of the specified set,
* the list does not contain duplicates, all the functions
* listed can be executed and that if a function is not
* in the list but is specified it cannot be executed.
*/
private void escapedFunctions(String[][] specList, String metaDataList)
throws SQLException
{
boolean[] seenFunction = new boolean[specList.length];
StringTokenizer st = new StringTokenizer(metaDataList, ",");
while (st.hasMoreTokens())
{
String function = st.nextToken();
// find this function in the list
boolean isSpecFunction = false;
for (int f = 0; f < specList.length; f++)
{
String[] specDetails = specList[f];
if (function.equals(specDetails[0]))
{
// Matched spec.
if (seenFunction[f])
fail("Function in list twice: " + function);
seenFunction[f] = true;
isSpecFunction = true;
executeEscaped(specDetails);
break;
}
}
if (!isSpecFunction)
{
fail("Non-JDBC spec function in list: " + function);
}
}
// Now see if any speced functions are not in the metadata list
for (int f = 0; f < specList.length; f++)
{
if (seenFunction[f])
continue;
String[] specDetails = specList[f];
// bug DERBY-723 CHAR maps to wrong function
if ("CHAR".equals(specDetails[0]))
continue;
try {
executeEscaped(specDetails);
fail("function works but not declared in list: " + specDetails[0]);
} catch (SQLException e) {
assertSQLState("42X01", e);
}
}
}
/**
* Test we can execute a function listed as a supported
* JDBC escaped function. We don't care about the actual
* return value, that should be tested elsewhere in
* the specific test of a function.
*/
private void executeEscaped(String[] specDetails)
throws SQLException
{
String sql = "VALUES { fn " + specDetails[0] + "(";
for (int p = 0; p < specDetails.length - 1; p++)
{
if (p != 0)
sql = sql + ", ";
sql = sql + specDetails[p + 1];
}
sql = sql + ") }";
PreparedStatement ps = prepareStatement(sql);
ResultSet rs = ps.executeQuery();
JDBC.assertDrainResults(rs);
rs.close();
ps.close();
}
/**
* Return a list of all valid supported datatypes as Strings
* suitable for use in any SQL statement where a SQL type is
* expected. For variable sixzed types the string will
* have random valid length information. E.g. CHAR(37).
*/
public static List getSQLTypes(Connection conn) throws SQLException
{
List list = new ArrayList();
Random rand = new Random();
ResultSet rs = conn.getMetaData().getTypeInfo();
while (rs.next())
{
String typeName = rs.getString("TYPE_NAME");
String createParams = rs.getString("CREATE_PARAMS");
if (createParams == null) {
// Type name stands by itself.
list.add(typeName);
continue;
}
if (createParams.indexOf("length") != -1)
{
int maxLength = rs.getInt("PRECISION");
// nextInt returns a value between 0 and maxLength-1
int length = rand.nextInt(maxLength) + 1;
int paren = typeName.indexOf('(');
if (paren == -1) {
list.add(typeName + "(" + length + ")");
} else {
StringBuffer sb = new StringBuffer();
sb.append(typeName.substring(0, paren+1));
sb.append(length);
sb.append(typeName.substring(paren+1));
list.add(sb.toString());
}
continue;
}
if (createParams.indexOf("scale") != -1)
{
int maxPrecision = rs.getInt("PRECISION");
StringBuffer sb = new StringBuffer();
int precision = rand.nextInt(maxPrecision) + 1;
sb.append(typeName);
sb.append("(");
sb.append(precision);
// Most DECIMAL usage does have a scale
// but randomly pick some that do not.
if (rand.nextInt(100) < 95) {
sb.append(",");
sb.append(rand.nextInt(precision+1));
}
sb.append(")");
list.add(sb.toString());
continue;
}
if (createParams.indexOf("precision") != -1)
{
list.add(typeName);
continue;
}
fail("unknown how to generate valid type for " + typeName
+ " CREATE_PARAMS=" + createParams);
}
return list;
}
/**
* Given a valid SQL type return the corresponding
* JDBC type identifier from java.sql.Types.
* Will assert if the type is not known
* (in future, currently just return Types.NULL).
*/
public static int getJDBCType(String type)
{
if ("SMALLINT".equals(type))
return Types.SMALLINT;
if ("INTEGER".equals(type) || "INT".equals(type))
return Types.INTEGER;
if ("BIGINT".equals(type))
return Types.BIGINT;
if (type.equals("FLOAT") || type.startsWith("FLOAT("))
return Types.FLOAT;
if (type.equals("REAL"))
return Types.REAL;
if ("DOUBLE".equals(type) || "DOUBLE PRECISION".equals(type))
return Types.DOUBLE;
if ("DATE".equals(type))
return Types.DATE;
if ("TIME".equals(type))
return Types.TIME;
if ("TIMESTAMP".equals(type))
return Types.TIMESTAMP;
if (type.equals("DECIMAL") || type.startsWith("DECIMAL("))
return Types.DECIMAL;
if (type.equals("NUMERIC") || type.startsWith("NUMERIC("))
return Types.NUMERIC;
if (type.endsWith("FOR BIT DATA")) {
if (type.startsWith("CHAR"))
return Types.BINARY;
if (type.startsWith("CHARACTER"))
return Types.BINARY;
if (type.startsWith("VARCHAR"))
return Types.VARBINARY;
if (type.startsWith("CHARACTER VARYING"))
return Types.VARBINARY;
if (type.startsWith("CHAR VARYING"))
return Types.VARBINARY;
}
if ("LONG VARCHAR".equals(type))
return Types.LONGVARCHAR;
if ("LONG VARCHAR FOR BIT DATA".equals(type))
return Types.LONGVARBINARY;
if (type.equals("CHAR") || type.startsWith("CHAR("))
return Types.CHAR;
if (type.equals("CHARACTER") ||
type.startsWith("CHARACTER("))
return Types.CHAR;
if (type.equals("VARCHAR") || type.startsWith("VARCHAR("))
return Types.VARCHAR;
if (type.equals("CHARACTER VARYING") ||
type.startsWith("CHARACTER VARYING("))
return Types.VARCHAR;
if (type.equals("CHAR VARYING") ||
type.startsWith("CHAR VARYING("))
return Types.VARCHAR;
if (type.equals("BLOB") || type.startsWith("BLOB("))
return Types.BLOB;
if (type.equals("BINARY LARGE OBJECT") ||
type.startsWith("BINARY LARGE OBJECT("))
return Types.BLOB;
if (type.equals("CLOB") || type.startsWith("CLOB("))
return Types.CLOB;
if (type.equals("CHARACTER LARGE OBJECT") ||
type.startsWith("CHARACTER LARGE OBJECT("))
return Types.CLOB;
if ("XML".equals(type))
return JDBC.SQLXML;
fail("Unexpected SQL type: " + type);
return Types.NULL;
}
/**
* Given a valid SQL type return the corresponding
* precision/length for this specific value
* if the type is variable, e.g. CHAR(5) will
* return 5, but LONG VARCHAR will return 0.
*/
public static int getPrecision(int jdbcType, String type)
{
switch (jdbcType)
{
case Types.CHAR:
case Types.VARCHAR:
case Types.CLOB:
case Types.BINARY:
case Types.VARBINARY:
case Types.BLOB:
int lp = type.indexOf('(');
int rp = type.indexOf(')');
int precision =
Integer.valueOf(type.substring(lp+1, rp)).intValue();
return precision;
default:
return 0;
}
}
/**
* Execute and check the ODBC variant of getImported/Exported keys, which
* uses the SQLFOREIGNKEYS system procedure to provide the same information
* to ODBC clients. Note that for "correctness" we just compare the results
* to those of the equivalent JDBC calls; this fixture assumes that the
* the JDBC calls return correct results (testing of the JDBC results occurs
* elsewhere, esp. jdbcapi/metadata_test.java).
*/
public void testGetXXportedKeysODBC() throws SQLException, IOException
{
Statement st = createStatement();
// Create some simple tables with primary/foreign keys.
st.execute("create table pkt1 (i int not null, c char(1) not null)");
st.execute("create table pkt2 (i int not null, c char(1) not null)");
st.execute("create table pkt3 (i int not null, c char(1) not null)");
st.execute("alter table pkt1 add constraint pk1 primary key (i)");
st.execute("alter table pkt2 add constraint pk2 primary key (c)");
st.execute("alter table pkt3 add constraint pk3 primary key (i, c)");
st.execute("create table fkt1 (fi int, fc char(1), vc varchar(80))");
st.execute("create table fkt2 (fi int, fc char(1), vc varchar(80))");
st.execute("alter table fkt1 add constraint fk1 foreign key (fi) " +
"references pkt1(i)");
st.execute("alter table fkt1 add constraint fk2 foreign key (fc) " +
"references pkt2(c)");
st.execute("alter table fkt2 add constraint fk3 foreign key (fi, fc) " +
"references pkt3(i, c)");
/* Check for all arguments NULL; SQLFOREIGNKEYS allows this, though
* there is no equivalent in JDBC.
*/
checkODBCKeys(null, null, null, null, null, null);
/* Run equivalent of getImportedKeys(), getExportedKeys(),
* and getCrossReference for each of the primary/foreign
* key pairs.
*/
checkODBCKeys(null, null, null, null, null, "FKT1");
checkODBCKeys(null, null, "PKT1", null, null, null);
checkODBCKeys(null, null, "PKT1", null, null, "FKT1");
checkODBCKeys(null, null, null, null, null, "FKT2");
checkODBCKeys(null, null, "PKT2", null, null, null);
checkODBCKeys(null, null, "PKT2", null, null, "FKT2");
checkODBCKeys(null, null, null, null, null, "FKT3");
checkODBCKeys(null, null, "PKT3", null, null, null);
checkODBCKeys(null, null, "PKT3", null, null, "FKT3");
// Reverse primary and foreign tables.
checkODBCKeys(null, null, "FKT1", null, null, null);
checkODBCKeys(null, null, null, null, null, "PKT3");
checkODBCKeys(null, null, "FKT1", null, null, "PKT1");
checkODBCKeys(null, null, "FKT2", null, null, "PKT2");
checkODBCKeys(null, null, "FKT3", null, null, "PKT3");
// Mix-and-match primary key tables and foreign key tables.
checkODBCKeys(null, null, "PKT1", null, null, "FKT2");
checkODBCKeys(null, null, "PKT1", null, null, "FKT3");
checkODBCKeys(null, null, "PKT2", null, null, "FKT3");
checkODBCKeys(null, null, "FKT1", null, null, "PKT2");
checkODBCKeys(null, null, "FKT1", null, null, "PKT3");
checkODBCKeys(null, null, "FKT2", null, null, "PKT3");
// Cleanup.
st.execute("drop table fkt1");
st.execute("drop table fkt2");
st.execute("drop table pkt1");
st.execute("drop table pkt2");
st.execute("drop table pkt3");
st.close();
}
/**
* Execute a call to the ODBC system procedure "SQLFOREIGNKEYS"
* and verify the results by comparing them with the results of
* an equivalent JDBC call (if one exists).
*/
private void checkODBCKeys(String pCatalog, String pSchema,
String pTable, String fCatalog, String fSchema, String fTable)
throws SQLException, IOException
{
/* To mimic the behavior of the issue which prompted this test
* (DERBY-2758) we only send the "ODBC" option; we do *not*
* explicitly send the "IMPORTEDKEY=1" nor "EXPORTEDKEY=1"
* options, as DB2 Runtime Client does not send those, either.
* This effectively means that the SQLFOREIGNKEYS function
* will always be mapped to getCrossReference() internally.
* Since that worked fine prior to 10.3, we need to preserve
* that behavior if we want to maintina backward compatibility.
*/
CallableStatement cs = prepareCall(
"CALL SYSIBM.SQLFOREIGNKEYS(?, ?, ?, ?, ?, ?, " +
"'DATATYPE=''ODBC''')");
cs.setString(1, pCatalog);
cs.setString(2, pSchema);
cs.setString(3, pTable);
cs.setString(4, fCatalog);
cs.setString(5, fSchema);
cs.setString(6, fTable);
cs.execute();
ResultSet odbcrs = cs.getResultSet();
assertNotNull(odbcrs);
/* Returned ResultSet will have the same shape as
* DatabaseMetaData.getImportedKeys()
*/
checkODBCKeysShape(odbcrs);
/* Expect the contents of JDBC and ODBC metadata to be the same,
* except if both pTable and cTable are null. In that case
* ODBC treats everything as a wildcard (and so effectively
* returns all foreign key columns), while JDBC throws
* an error.
*/
ResultSet dmdrs = null;
if ((pTable != null) && (fTable == null))
dmdrs = getDMD().getExportedKeys(pCatalog, pSchema, pTable);
else if ((pTable == null) && (fTable != null))
dmdrs = getDMD().getImportedKeys(fCatalog, fSchema, fTable);
else if (pTable != null)
{
dmdrs = getDMD().getCrossReference(
pCatalog, pSchema, pTable, fCatalog, fSchema, fTable);
}
else
{
/* Must be the case of pTable and fTable both null. Check
* results for ODBC (one row for each foreign key column)
* and assert error for JDBC.
*/
JDBC.assertFullResultSet(odbcrs,
new String [][] {
{"","APP","PKT1","I","","APP","FKT1","FI",
"1","3","3","FK1","PK1","7"},
{"","APP","PKT2","C","","APP","FKT1","FC",
"1","3","3","FK2","PK2","7"},
{"","APP","PKT3","I","","APP","FKT2","FI",
"1","3","3","FK3","PK3","7"},
{"","APP","PKT3","C","","APP","FKT2","FC",
"2","3","3","FK3","PK3","7"}
});
try {
getDMD().getCrossReference(
pCatalog, pSchema, pTable, fCatalog, fSchema, fTable);
fail("Expected error from call to DMD.getCrossReference() " +
"with NULL primary and foreign key tables.");
} catch (SQLException se) {
/* Looks like embedded and client have different (but similar)
* errors for this...
*/
assertSQLState(usingEmbedded() ? "XJ103" : "XJ110", se);
}
}
/* If both pTable and fTable are null then dmdrs will be null, as
* well. So nothing to compare in that case.
*/
if (dmdrs != null)
{
// Next call closes both results sets as a side effect.
JDBC.assertSameContents(odbcrs, dmdrs);
}
cs.close();
}
/**
* Check the shape of the ResultSet from a call to the ODBC function
* SQLForeignKeys.
*/
private void checkODBCKeysShape(ResultSet rs) throws SQLException
{
assertMetaDataResultSet(rs,
// ODBC and JDBC agree on column names and types.
new String[] {
"PKTABLE_CAT", "PKTABLE_SCHEM", "PKTABLE_NAME", "PKCOLUMN_NAME",
"FKTABLE_CAT", "FKTABLE_SCHEM", "FKTABLE_NAME", "FKCOLUMN_NAME",
"KEY_SEQ", "UPDATE_RULE", "DELETE_RULE", "FK_NAME",
"PK_NAME", "DEFERRABILITY"
},
new int[] {
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.SMALLINT, Types.SMALLINT, Types.SMALLINT, Types.VARCHAR,
Types.VARCHAR, Types.SMALLINT
},
// Nullability comes from ODBC spec, not JDBC.
/* DERBY-2797: Nullability of columns in ODBC's SQLForeignKey
* result set is incorrect. Un-comment the correct boolean array
* when DERBY-2797 has been fixed.
*/
// incorrect
new boolean[] {
true, false, false, false,
true, false, false, false,
true, true, true, false,
false, true
}
// correct
/* new boolean[] {
true, true, false, false,
true, true, false, false,
false, true, true, true,
true, true
} */
);
}
/**
* Test getBestRowIdentifier
* @throws SQLException
*/
public void testGetBestRowIdentifier() throws SQLException
{
Statement st = createStatement();
// First, create the test tables and indexes/keys
// Create 5 tables which have only one best row identifier
st.execute("create table brit1 (i int not null primary key, j int)");
st.execute("create table brit2 (i int not null unique, j int)");
// adding not null unique to j - otherwise brit2 & brit3 would be same.
st.execute("create table brit3 (i int not null unique, " +
"j int not null unique)");
st.execute("create table brit4 (i int, j int)");
st.execute("create unique index brit4i on brit4(i)");
st.execute("create table brit5 (i int, j int)");
// following have more than one best row identifier
st.execute("create table brit6 (i int not null unique, " +
"j int not null primary key)");
// PK preferred to unique index
st.execute("create table brit7 (i int not null, " +
"j int not null primary key)");
st.execute("create unique index brit7i on brit7(i)");
// unique con preferred to unique index
st.execute("create table brit8 (i int not null, " +
"j int not null unique)");
st.execute("create unique index brit8i on brit8(i)");
// non-unique index just ignored
st.execute("create table brit9 (i int, j int)");
st.execute("create index brit9i on brit9(i)");
// fewer cols unique con still ignored over primary key
st.execute("create table brit10 " +
"(i int unique not null , j int not null, primary key (i,j))");
// fewer cols unique index still ignored over primary key
st.execute("create table brit11 (i int not null, j int not null, "
+ "primary key (i,j))");
st.execute("create unique index brit11i on brit11(i)");
// fewer cols unique index still ignored over unique con
st.execute("create table brit12 (i int not null, j int not null, "
+ "unique (i,j))");
st.execute("create unique index brit12i on brit12(i)");
st.execute("create table brit13 (i int not null, j int)");
// fewest cols unique con is the one picked of several
st.execute("create table brit14 (i int not null unique, j int not "
+ "null, k int, unique (i,j))");
// fewest cols unique index is the one picked of several
st.execute("create table brit15 (i int not null, j int not null, k int)");
st.execute("create unique index brit15ij on brit15(i,j)");
st.execute("create unique index brit15i on brit15(i)");
st.execute("create table brit16 (i int not null primary key, j int)");
// from old metadata test
// DERBY-3180; if this table gets created here, running the entire test
// twice with defaultSuite runs into into trouble.
// Moving into separate fixture does not have this problem.
st.execute("create table brit17 (i int not null default 10, " +
"s smallint not null, c30 char(30) not null, " +
"vc10 varchar(10) not null default 'asdf', " +
"constraint PRIMKEY primary key(vc10, i), " +
"constraint UNIQUEKEY unique(c30, s), ai bigint " +
"generated always as identity " +
"(start with -10, increment by 2001))");
// Create another unique index on brit17
st.execute("create unique index brit17i on brit17(s, i)");
// Create a non-unique index on brit17
st.execute("create index brit17ij on brit17(s)");
getConnection().setAutoCommit(false);
// except for the last table, the expected results are
// column i, column j, or columns i and j.
String [][] expRSI = {
{"2", "I", "4", "INTEGER", "4", null, "10", "1"}};
String [][] expRSJ = {
{"2", "J", "4", "INTEGER", "4", null, "10", "1"}};
String [][] expRSIJ = {
{"2", "I", "4", "INTEGER", "4", null, "10", "1"},
{"2", "J", "4", "INTEGER", "4", null, "10", "1"}};
boolean [] nullability = {
true, false, true, true, true, true, true, true};
DatabaseMetaData dmd = getConnection().getMetaData();
// result: column i
ResultSet rs = dmd.getBestRowIdentifier(null,"APP","BRIT1",0,true);
verifyBRIResults(rs, expRSI, nullability);
// result: column i
rs = dmd.getBestRowIdentifier(null,"APP","BRIT2",0,true);
verifyBRIResults(rs, expRSI, nullability);
// result: column j
rs = dmd.getBestRowIdentifier(null,"APP","BRIT3",0,true);
verifyBRIResults(rs, expRSJ, nullability);
// result: column i
rs = dmd.getBestRowIdentifier(null,"APP","BRIT4",0,true);
verifyBRIResults(rs, expRSI, nullability);
// result: columns i and j
rs = dmd.getBestRowIdentifier(null,"APP","BRIT5",0,true);
verifyBRIResults(rs, expRSIJ, nullability);
// result: column j
rs = dmd.getBestRowIdentifier(null,"APP","BRIT6",0,true);
verifyBRIResults(rs, expRSJ, nullability);
// result: column j
rs = dmd.getBestRowIdentifier(null,"APP","BRIT7",0,true);
verifyBRIResults(rs, expRSJ, nullability);
// result: column j
rs = dmd.getBestRowIdentifier(null,"APP","BRIT8",0,true);
verifyBRIResults(rs, expRSJ, nullability);
// result: columns i,j
rs = dmd.getBestRowIdentifier(null,"APP","BRIT9",0,true);
verifyBRIResults(rs, expRSIJ, nullability);
// result: columns i,j
rs = dmd.getBestRowIdentifier(null,"APP","BRIT10",0,true);
verifyBRIResults(rs, expRSIJ, nullability);
// result: columns i,j
rs = dmd.getBestRowIdentifier(null,"APP","BRIT11",0,true);
verifyBRIResults(rs, expRSIJ, nullability);
// result: columns i,j
rs = dmd.getBestRowIdentifier(null,"APP","BRIT12",0,true);
verifyBRIResults(rs, expRSIJ, nullability);
// Verify nullOK flas makes a difference. See also DERBY-3182
// result: column i, should've ignored null column
rs = dmd.getBestRowIdentifier(null,"APP","BRIT13",0,false);
verifyBRIResults(rs, expRSI, nullability);
// result: columns i, j
rs = dmd.getBestRowIdentifier(null,"APP","BRIT13",0,true);
verifyBRIResults(rs, expRSIJ, nullability);
// result: columns i
rs = dmd.getBestRowIdentifier(null,"APP","BRIT14",0,true);
verifyBRIResults(rs, expRSI, nullability);
// result: columns i
rs = dmd.getBestRowIdentifier(null,"APP","BRIT15",0,true);
verifyBRIResults(rs, expRSI, nullability);
// we don't do anything with SCOPE except detect bad values
// result: columns i
rs = dmd.getBestRowIdentifier(null,"APP","BRIT16",1,true);
verifyBRIResults(rs, expRSI, nullability);
// result: columns i
rs = dmd.getBestRowIdentifier(null,"APP","BRIT16",2,true);
verifyBRIResults(rs, expRSI, nullability);
// result: no rows
rs = dmd.getBestRowIdentifier(null,"APP","BRIT16",-1,true);
// column nullability is opposite to with scope=1 or 2...DERBY-3181
nullability = new boolean [] {
false, true, false, true, false, false, false, false};
assertBestRowIdentifierMetaDataResultSet(rs, nullability);
JDBC.assertDrainResults(rs, 0);
// result: no rows
rs = dmd.getBestRowIdentifier(null,"APP","BRIT16",3,true);
assertBestRowIdentifierMetaDataResultSet(rs, nullability);
JDBC.assertDrainResults(rs, 0);
// set back nullability
nullability = new boolean[] {
true, false, true, true, true, true, true, true};
rs = dmd.getBestRowIdentifier(null, "APP","BRIT17",0,true);
String [][] expRS = new String [][] {
{"2", "I", "4", "INTEGER", "4", null, "10", "1"},
{"2", "VC10", "12", "VARCHAR", "10", null, null, "1"}
};
verifyBRIResults(rs, expRS, nullability);
// test DERBY-2610 for fun; can't pass in null table name
try {
rs = dmd.getBestRowIdentifier(null,"APP",null,3,true);
} catch (SQLException sqle) {
assertSQLState( "XJ103", sqle);
}
// check on systables
rs = dmd.getBestRowIdentifier(null,"SYS","SYSTABLES",0,true);
expRS = new String [][] {
{"2", "TABLEID", "1", "CHAR", "36", null, null, "1"}
};
verifyBRIResults(rs, expRS, nullability);
getConnection().setAutoCommit(true);
st.execute("drop table brit1");
st.execute("drop table brit2");
st.execute("drop table brit3");
st.execute("drop index brit4i");
st.execute("drop table brit4");
st.execute("drop table brit5");
st.execute("drop table brit6");
st.execute("drop index brit7i");
st.execute("drop table brit7");
st.execute("drop index brit8i");
st.execute("drop table brit8");
st.execute("drop index brit9i");
st.execute("drop table brit9");
st.execute("drop table brit10");
st.execute("drop index brit11i");
st.execute("drop table brit11");
st.execute("drop index brit12i");
st.execute("drop table brit12");
st.execute("drop table brit13");
st.execute("drop table brit14");
st.execute("drop index brit15i");
st.execute("drop index brit15ij");
st.execute("drop table brit15");
st.execute("drop table brit16");
st.execute("drop index brit17i");
st.execute("drop index brit17ij");
st.execute("drop table brit17");
st.close();
}
/**
* helper method for test testGetBestRowIdentifier
* @param rs - Resultset from dmd.getBestRowIdentifier
* @param expRS - bidimensional String array with expected result row(s)
* @param nullability - boolean array holding expected nullability
* values. This needs to be a paramter because of DERBY-3081
* @throws SQLException
*/
public void verifyBRIResults(ResultSet rs, String[][] expRS,
boolean[] nullability) throws SQLException {
assertBestRowIdentifierMetaDataResultSet(rs, nullability);
JDBC.assertFullResultSet(rs, expRS, true);
}
// helper method for testGetBestRowIdentifier
public void assertBestRowIdentifierMetaDataResultSet(
ResultSet rs, boolean[] nullability) throws SQLException {
String[] columnNames = {
"SCOPE", "COLUMN_NAME", "DATA_TYPE", "TYPE_NAME",
"COLUMN_SIZE", "BUFFER_LENGTH", "DECIMAL_DIGITS",
"PSEUDO_COLUMN"};
int[] columnTypes = {
Types.SMALLINT, Types.VARCHAR, Types.INTEGER, Types.VARCHAR,
Types.INTEGER, Types.INTEGER, Types.SMALLINT, Types.SMALLINT};
assertMetaDataResultSet(rs, columnNames, columnTypes, nullability);
}
}
| java/testing/org/apache/derbyTesting/functionTests/tests/jdbcapi/DatabaseMetaDataTest.java | /*
Derby - Class org.apache.derbyTesting.functionTests.tests.jdbcapi.DatabaseMetaDataTest
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.jdbcapi;
import java.io.IOException;
//import java.lang.reflect.Constructor;
//import java.lang.reflect.Method;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Arrays;
//import java.util.HashMap;
//import java.util.Iterator;
import java.util.List;
import java.util.Locale;
//import java.util.Map;
import java.util.Random;
import java.util.StringTokenizer;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.derbyTesting.junit.BaseJDBCTestCase;
//import org.apache.derbyTesting.junit.CleanDatabaseTestSetup;
import org.apache.derbyTesting.junit.DatabasePropertyTestSetup;
import org.apache.derbyTesting.junit.JDBC;
import org.apache.derbyTesting.junit.TestConfiguration;
//import org.apache.derby.shared.common.reference.JDBC40Translation;
/**
* Test the DatabaseMetaData api.
* <P>
* For the methods that return a ResultSet to determine the
* attributes of SQL objects (e.g. getTables) two methods
* are provided. A non-modify and a modify one.
*
* <BR>
* The non-modify method tests that the getXXX method call works.
* This can be used by other tests where issues have been seen
* with database meta data, such as upgrade and read-only databases.
* The non-modify means that the test method does not change the database
* in order to test the return of the getXXX method is correct.
* <BR>
* The modify versions test
* Work in progress.
* TODO: Methods left to test from JDBC 3
*
* getColumnPrivileges
* getCrossReference
* getExportedKeys
* getImportedKeys
* getIndexInfo
* getPrimaryKeys
* getProcedureColumns
* getProcedures
* getTablePrivileges
* <P>
* This test is also called from the upgrade tests to test that
* metadata continues to work at various points in the upgrade.
*/
public class DatabaseMetaDataTest extends BaseJDBCTestCase {
/*
** Escaped function testing
*/
private static final String[][] NUMERIC_FUNCTIONS =
{
// Section C.1 JDBC 3.0 spec.
{ "ABS", "-25.67" },
{ "ACOS", "0.0707" },
{ "ASIN", "0.997" },
{ "ATAN", "14.10" },
{ "ATAN2", "0.56", "1.2" },
{ "CEILING", "3.45" },
{ "COS", "1.2" },
{ "COT", "3.4" },
{ "DEGREES", "2.1" },
{ "EXP", "2.3" },
{ "FLOOR", "3.22" },
{ "LOG", "34.1" },
{ "LOG10", "18.7" },
{ "MOD", "124", "7" },
{ "PI" },
{ "POWER", "2", "3" },
{ "RADIANS", "54" },
{ "RAND", "17" },
{ "ROUND", "345.345", "1" },
{ "SIGN", "-34" },
{ "SIN", "0.32" },
{ "SQRT", "6.22" },
{ "TAN", "0.57", },
{ "TRUNCATE", "345.395", "1" }
};
private static final String[][] TIMEDATE_FUNCTIONS =
{
// Section C.3 JDBC 3.0 spec.
{ "CURDATE" },
{ "CURTIME" },
{ "DAYNAME", "{d '1995-12-19'h}" },
{ "DAYOFMONTH", "{d '1995-12-19'}" },
{ "DAYOFWEEK", "{d '1995-12-19'}" },
{ "DAYOFYEAR", "{d '1995-12-19'}" },
{ "HOUR", "{t '16:13:03'}" },
{ "MINUTE", "{t '16:13:03'}" },
{ "MONTH", "{d '1995-12-19'}" },
{ "MONTHNAME", "{d '1995-12-19'}" },
{ "NOW" },
{ "QUARTER", "{d '1995-12-19'}" },
{ "SECOND", "{t '16:13:03'}" },
{ "TIMESTAMPADD", "SQL_TSI_DAY", "7", "{ts '1995-12-19 12:15:54'}" },
{ "TIMESTAMPDIFF", "SQL_TSI_DAY", "{ts '1995-12-19 12:15:54'}", "{ts '1997-11-02 00:15:23'}" },
{ "WEEK", "{d '1995-12-19'}" },
{ "YEAR", "{d '1995-12-19'}" },
};
private static final String[][] SYSTEM_FUNCTIONS =
{
// Section C.4 JDBC 3.0 spec.
{ "DATABASE" },
{ "IFNULL", "'this'", "'that'" },
{ "USER"},
};
private static final String[][] STRING_FUNCTIONS =
{
// Section C.2 JDBC 3.0 spec.
{ "ASCII" , "'Yellow'" },
{ "CHAR", "65" },
{ "CONCAT", "'hello'", "'there'" },
{ "DIFFERENCE", "'Pires'", "'Piers'" },
{ "INSERT", "'Bill Clinton'", "4", "'William'" },
{ "LCASE", "'Fernando Alonso'" },
{ "LEFT", "'Bonjour'", "3" },
{ "LENGTH", "'four '" } ,
{ "LOCATE", "'jour'", "'Bonjour'" },
{ "LTRIM", "' left trim '"},
{ "REPEAT", "'echo'", "3" },
{ "REPLACE", "'to be or not to be'", "'be'", "'England'" },
{ "RTRIM", "' right trim '"},
{ "SOUNDEX", "'Derby'" },
{ "SPACE", "12"},
{ "SUBSTRING", "'Ruby the Rubicon Jeep'", "10", "7", },
{ "UCASE", "'Fernando Alonso'" }
};
/**
* Did the test modifiy the database.
*/
private boolean modifiedDatabase;
public DatabaseMetaDataTest(String name) {
super(name);
}
protected void tearDown() throws Exception
{
if (modifiedDatabase)
{
Connection conn = getConnection();
conn.setAutoCommit(false);
DatabaseMetaData dmd = getDMD();
for (int i = 0; i < IDS.length; i++)
JDBC.dropSchema(dmd, getStoredIdentifier(IDS[i]));
commit();
}
super.tearDown();
}
/**
* Default suite for running this test.
*/
public static Test suite() {
TestSuite suite = new TestSuite("DatabaseMetaDataTest");
suite.addTest(
TestConfiguration.defaultSuite(DatabaseMetaDataTest.class));
// Test for DERBY-2584 needs a fresh database to ensure that the
// meta-data queries haven't already been compiled. No need to run the
// test in client/server mode since it only tests the compilation of
// meta-data queries.
suite.addTest(
TestConfiguration.singleUseDatabaseDecorator(
// until DERBY-177 is fixed, set lock timeout to prevent the
// test from waiting one minute
DatabasePropertyTestSetup.setLockTimeouts(
new DatabaseMetaDataTest("initialCompilationTest"), 2, 4)));
return suite;
}
/**
* Return the identifiers used to create schemas,
* tables etc. in the order the database stores them.
*/
private String[] getSortedIdentifiers()
{
String[] dbIDS = new String[IDS.length];
// Remove any quotes from user schemas and upper case
// those without quotes.
for (int i = 0; i < IDS.length; i++)
{
dbIDS[i] = getStoredIdentifier(IDS[i]);
}
Arrays.sort(dbIDS);
return dbIDS;
}
private final DatabaseMetaData getDMD() throws SQLException
{
return getConnection().getMetaData();
}
/**
* Tests that a meta-data query is compiled and stored correctly even when
* there's a lock on the system tables (DERBY-2584). This test must run on
* a fresh database (that is, <code>getIndexInfo</code> must not have been
* prepared and stored in <code>SYS.SYSSTATEMENTS</code>).
*/
public void initialCompilationTest() throws SQLException {
Connection c = getConnection();
c.setAutoCommit(false);
c.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
Statement s = createStatement();
// First get shared row locks on the SYSSTATEMENTS table.
JDBC.assertDrainResults(
s.executeQuery("SELECT * FROM SYS.SYSSTATEMENTS"));
s.close();
// Execute getIndexInfo() for the first time. Because of the shared
// locks on SYSSTATEMENTS, the query is compiled in the main
// transaction.
getDMD().getIndexInfo(null, null, "T", false, false).close();
// Re-use the previously compiled query from disk. Fails with
// ArrayIndexOutOfBoundsException before DERBY-2584.
getDMD().getIndexInfo(null, null, "T", false, false).close();
}
/**
* Test the methods that indicate if a feature
* is supported or not. Methods start with
* 'support'. See secton 7.3 in JDBC 3.0 specification.
*
* @throws SQLException
*
*/
public void testDetermineFeatureSupport() throws SQLException
{
DatabaseMetaData dmd = getDMD();
assertTrue(dmd.supportsAlterTableWithAddColumn());
assertTrue(dmd.supportsAlterTableWithDropColumn());
/* DERBY-2243 Derby does support ANSI 92 standards
* and this behaviour is now consistant across drivers
*/
assertTrue(dmd.supportsANSI92EntryLevelSQL());
assertFalse(dmd.supportsANSI92FullSQL());
assertFalse(dmd.supportsANSI92IntermediateSQL());
assertTrue(dmd.supportsBatchUpdates());
assertFalse(dmd.supportsCatalogsInDataManipulation());
assertFalse(dmd.supportsCatalogsInIndexDefinitions());
assertFalse(dmd.supportsCatalogsInPrivilegeDefinitions());
assertFalse(dmd.supportsCatalogsInProcedureCalls());
assertFalse(dmd.supportsCatalogsInTableDefinitions());
assertTrue(dmd.supportsColumnAliasing());
// Bug DERBY-462 should return false.
assertTrue(dmd.supportsConvert());
// Simple check since convert is not supported.
// A comprehensive test should be added when convert
// is supported, though most likely in a test class
// specific to convert.
assertFalse(dmd.supportsConvert(Types.INTEGER, Types.SMALLINT));
assertFalse(dmd.supportsCoreSQLGrammar());
assertTrue(dmd.supportsCorrelatedSubqueries());
assertTrue(dmd.supportsDataDefinitionAndDataManipulationTransactions());
assertFalse(dmd.supportsDataManipulationTransactionsOnly());
assertTrue(dmd.supportsDifferentTableCorrelationNames());
/* DERBY-2244 Derby does support Order By clause
* thus the changing the assert condition to TRUE
*/
assertTrue(dmd.supportsExpressionsInOrderBy());
assertFalse(dmd.supportsExtendedSQLGrammar());
assertFalse(dmd.supportsFullOuterJoins());
assertFalse(dmd.supportsGetGeneratedKeys());
assertTrue(dmd.supportsGroupBy());
assertTrue(dmd.supportsGroupByBeyondSelect());
assertTrue(dmd.supportsGroupByUnrelated());
assertFalse(dmd.supportsIntegrityEnhancementFacility());
assertTrue(dmd.supportsLikeEscapeClause());
assertTrue(dmd.supportsLimitedOuterJoins());
assertTrue(dmd.supportsMinimumSQLGrammar());
assertFalse(dmd.supportsMixedCaseIdentifiers());
assertTrue(dmd.supportsMixedCaseQuotedIdentifiers());
assertTrue(dmd.supportsMultipleOpenResults());
assertTrue(dmd.supportsMultipleResultSets());
assertTrue(dmd.supportsMultipleTransactions());
assertFalse(dmd.supportsNamedParameters());
assertTrue(dmd.supportsNonNullableColumns());
// Open cursors are not supported across global
// (XA) transactions so the driver returns false.
assertFalse(dmd.supportsOpenCursorsAcrossCommit());
assertFalse(dmd.supportsOpenCursorsAcrossRollback());
assertTrue(dmd.supportsOpenStatementsAcrossCommit());
assertFalse(dmd.supportsOpenStatementsAcrossRollback());
assertFalse(dmd.supportsOrderByUnrelated());
assertTrue(dmd.supportsOuterJoins());
assertTrue(dmd.supportsPositionedDelete());
assertTrue(dmd.supportsPositionedUpdate());
assertTrue(dmd.supportsResultSetConcurrency(
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY));
assertTrue(dmd.supportsResultSetConcurrency(
ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE));
assertTrue(dmd.supportsResultSetConcurrency(
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY));
assertTrue(dmd.supportsResultSetConcurrency(
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE));
assertFalse(dmd.supportsResultSetConcurrency(
ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY));
assertFalse(dmd.supportsResultSetConcurrency(
ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE));
assertTrue(dmd.supportsResultSetHoldability(
ResultSet.CLOSE_CURSORS_AT_COMMIT));
assertTrue(dmd.supportsResultSetHoldability(
ResultSet.HOLD_CURSORS_OVER_COMMIT));
assertTrue(dmd.supportsResultSetType(
ResultSet.TYPE_FORWARD_ONLY));
assertTrue(dmd.supportsResultSetType(
ResultSet.TYPE_SCROLL_INSENSITIVE));
assertFalse(dmd.supportsResultSetType(
ResultSet.TYPE_SCROLL_SENSITIVE));
assertTrue(dmd.supportsSavepoints());
assertTrue(dmd.supportsSchemasInDataManipulation());
assertTrue(dmd.supportsSchemasInIndexDefinitions());
assertTrue(dmd.supportsSchemasInPrivilegeDefinitions());
assertTrue(dmd.supportsSchemasInProcedureCalls());
assertTrue(dmd.supportsSchemasInTableDefinitions());
assertTrue(dmd.supportsSelectForUpdate());
assertFalse(dmd.supportsStatementPooling());
assertTrue(dmd.supportsStoredProcedures());
assertTrue(dmd.supportsSubqueriesInComparisons());
assertTrue(dmd.supportsSubqueriesInExists());
assertTrue(dmd.supportsSubqueriesInIns());
assertTrue(dmd.supportsSubqueriesInQuantifieds());
assertTrue(dmd.supportsTableCorrelationNames());
assertTrue(dmd.supportsTransactionIsolationLevel(
Connection.TRANSACTION_READ_COMMITTED));
assertTrue(dmd.supportsTransactionIsolationLevel(
Connection.TRANSACTION_READ_UNCOMMITTED));
assertTrue(dmd.supportsTransactionIsolationLevel(
Connection.TRANSACTION_REPEATABLE_READ));
assertTrue(dmd.supportsTransactionIsolationLevel(
Connection.TRANSACTION_SERIALIZABLE));
assertTrue(dmd.supportsTransactions());
assertTrue(dmd.supportsUnion());
assertTrue(dmd.supportsUnionAll());
}
/**
* Test group of methods provides the limits imposed by a given data source
* Methods start with
* 'getMax'. See section 7.4 in JDBC 3.0 specification.
*
* Note a return of zero from one of these functions means
* no limit or limit not known.
*
* @throws SQLException
*
*/
public void testDataSourceLimits() throws SQLException
{
DatabaseMetaData dmd = getDMD();
assertEquals(0, dmd.getMaxBinaryLiteralLength());
// Catalogs not supported.
assertEquals(0, dmd.getMaxCatalogNameLength());
assertEquals(0, dmd.getMaxCharLiteralLength());
assertEquals(128, dmd.getMaxColumnNameLength());
assertEquals(0, dmd.getMaxColumnsInGroupBy());
assertEquals(0, dmd.getMaxColumnsInIndex());
assertEquals(0, dmd.getMaxColumnsInOrderBy());
assertEquals(0, dmd.getMaxColumnsInSelect());
assertEquals(0, dmd.getMaxColumnsInTable());
assertEquals(0, dmd.getMaxConnections());
assertEquals(128, dmd.getMaxCursorNameLength());
assertEquals(0, dmd.getMaxIndexLength());
assertEquals(128, dmd.getMaxProcedureNameLength());
assertEquals(0, dmd.getMaxRowSize());
assertEquals(128, dmd.getMaxSchemaNameLength());
assertEquals(0, dmd.getMaxStatementLength());
assertEquals(0, dmd.getMaxStatements());
assertEquals(128, dmd.getMaxTableNameLength());
assertEquals(0, dmd.getMaxTablesInSelect());
assertEquals(30, dmd.getMaxUserNameLength());
}
public void testMiscellaneous() throws SQLException
{
DatabaseMetaData dmd = getDMD();
assertTrue(dmd.allProceduresAreCallable());
assertTrue(dmd.allTablesAreSelectable());
assertFalse(dmd.dataDefinitionCausesTransactionCommit());
assertFalse(dmd.dataDefinitionIgnoredInTransactions());
assertFalse(dmd.deletesAreDetected(ResultSet.TYPE_FORWARD_ONLY));
assertTrue(dmd.deletesAreDetected(ResultSet.TYPE_SCROLL_INSENSITIVE));
assertFalse(dmd.deletesAreDetected(ResultSet.TYPE_SCROLL_SENSITIVE));
assertTrue(dmd.doesMaxRowSizeIncludeBlobs());
// Catalogs not supported, so empty string returned for separator.
assertEquals("", dmd.getCatalogSeparator());
assertEquals("CATALOG", dmd.getCatalogTerm());
assertEquals(Connection.TRANSACTION_READ_COMMITTED,
dmd.getDefaultTransactionIsolation());
assertEquals("", dmd.getExtraNameCharacters());
assertEquals("\"", dmd.getIdentifierQuoteString());
assertEquals("PROCEDURE", dmd.getProcedureTerm());
assertEquals(ResultSet.HOLD_CURSORS_OVER_COMMIT,
dmd.getResultSetHoldability());
assertEquals("SCHEMA", dmd.getSchemaTerm());
assertEquals("", dmd.getSearchStringEscape());
assertEquals(DatabaseMetaData.sqlStateSQL99,
dmd.getSQLStateType());
assertFalse(dmd.isCatalogAtStart());
assertTrue(dmd.locatorsUpdateCopy());
assertTrue(dmd.usesLocalFilePerTable());
assertTrue(dmd.usesLocalFiles());
}
/**
* Methods that describe the version of the
* driver and database.
*/
public void testVersionInfo() throws SQLException
{
DatabaseMetaData dmd = getDMD();
int databaseMajor = dmd.getDatabaseMajorVersion();
int databaseMinor = dmd.getDatabaseMinorVersion();
int driverMajor = dmd.getDriverMajorVersion();
int driverMinor = dmd.getDriverMinorVersion();
String databaseVersion = dmd.getDatabaseProductVersion();
String driverVersion = dmd.getDriverVersion();
if (usingEmbedded())
{
// Database *is* the driver.
assertEquals("Embedded Major version ",
databaseMajor, driverMajor);
assertEquals("Embedded Minor version ",
databaseMinor, driverMinor);
assertEquals("Embedded version",
databaseVersion, driverVersion);
}
assertEquals("Apache Derby", dmd.getDatabaseProductName());
String driverName = dmd.getDriverName();
if (usingEmbedded())
{
assertEquals("Apache Derby Embedded JDBC Driver",
driverName);
}
else if (usingDerbyNetClient())
{
assertEquals("Apache Derby Network Client JDBC Driver",
driverName);
}
int jdbcMajor = dmd.getJDBCMajorVersion();
int jdbcMinor = dmd.getJDBCMinorVersion();
int expectedJDBCMajor = -1;
if (JDBC.vmSupportsJDBC4())
{
expectedJDBCMajor = 4;
}
else if (JDBC.vmSupportsJDBC3())
{
expectedJDBCMajor = 3;
}
else if (JDBC.vmSupportsJSR169())
{
// Not sure what is the correct output for JSR 169
expectedJDBCMajor = -1;
}
if (expectedJDBCMajor != -1)
{
assertEquals("JDBC Major version",
expectedJDBCMajor, jdbcMajor);
assertEquals("JDBC Minor version", 0, jdbcMinor);
}
}
/**
* getURL() method. Note that this method
* is the only JDBC 3 DatabaseMetaData method
* that is dropped in JSR169.
*/
public void testGetURL() throws SQLException
{
DatabaseMetaData dmd = getDMD();
String url;
try {
url = dmd.getURL();
} catch (NoSuchMethodError e) {
// JSR 169 - method must not be there!
assertTrue("getURL not supported", JDBC.vmSupportsJSR169());
assertFalse("getURL not supported", JDBC.vmSupportsJDBC2());
return;
}
assertFalse("getURL is supported!", JDBC.vmSupportsJSR169());
assertTrue("getURL is supported!", JDBC.vmSupportsJDBC2());
assertEquals("getURL match",
getTestConfiguration().getJDBCUrl(),
url);
}
/**
* Derby stores unquoted identifiers as upper
* case and quoted ones as mixed case.
* They are always compared case sensitive.
*/
public void testIdentifierStorage() throws SQLException
{
DatabaseMetaData dmd = getDMD();
assertFalse(dmd.storesLowerCaseIdentifiers());
assertFalse(dmd.storesLowerCaseQuotedIdentifiers());
assertFalse(dmd.storesMixedCaseIdentifiers());
assertTrue(dmd.storesMixedCaseQuotedIdentifiers());
assertTrue(dmd.storesUpperCaseIdentifiers());
assertFalse(dmd.storesUpperCaseQuotedIdentifiers());
}
/**
* methods that return information about handling NULL.
*/
public void testNullInfo() throws SQLException
{
DatabaseMetaData dmd = getDMD();
assertTrue(dmd.nullPlusNonNullIsNull());
assertFalse(dmd.nullsAreSortedAtEnd());
assertFalse(dmd.nullsAreSortedAtStart());
assertTrue(dmd.nullsAreSortedHigh());
assertFalse(dmd.nullsAreSortedLow());
}
/**
* Method getSQLKeywords, returns list of SQL keywords
* that are not defined by SQL92.
*/
public void testSQLKeywords() throws SQLException
{
String keywords = getDMD().getSQLKeywords();
assertNotNull(keywords);
//TODO: more testing but not sure what!
}
/**
* Methods that return information specific to
* the current connection.
*/
public void testConnectionSpecific() throws SQLException
{
DatabaseMetaData dmd = getDMD();
assertSame(getConnection(), dmd.getConnection());
assertEquals(getTestConfiguration().getUserName(),
dmd.getUserName());
assertEquals(getConnection().isReadOnly(), dmd.isReadOnly());
}
/**
* This is not a test of Derby but JDBC constants for meta data
* that this test depends on.
* The constants for nullability are the same but let's check to make sure.
*
*/
public void testConstants()
{
assertEquals(DatabaseMetaData.columnNoNulls, ResultSetMetaData.columnNoNulls);
assertEquals(DatabaseMetaData.columnNullable, ResultSetMetaData.columnNullable);
assertEquals(DatabaseMetaData.columnNullableUnknown, ResultSetMetaData.columnNullableUnknown);
}
/*
** DatabaseMetaData calls that return ResultSets.
*/
/**
* Test methods that describe attributes of SQL Objects
* that are not supported by derby. In each case the
* metadata should return an empty ResultSet of the
* correct shape, and with correct names, datatypes and
* nullability for the columns in the ResultSet.
*
*/
public void testUnimplementedSQLObjectAttributes() throws SQLException
{
DatabaseMetaData dmd = getDMD();
ResultSet rs;
rs = dmd.getAttributes(null,null,null,null);
String [] columnNames = {
"TYPE_CAT", "TYPE_SCHEM", "TYPE_NAME", "ATTR_NAME", "DATA_TYPE",
"ATTR_TYPE_NAME", "ATTR_SIZE", "DECIMAL_DIGITS", "NUM_PREC_RADIX",
"NULLABLE", "REMARKS", "ATTR_DEF", "SQL_DATA_TYPE",
"SQL_DATETIME_SUB", "CHAR_OCTET_LENGTH", "ORDINAL_POSITION",
"IS_NULLABLE", "SCOPE_CATALOG", "SCOPE_SCHEMA", "SCOPE_TABLE",
"SOURCE_DATA_TYPE"
};
int [] columnTypes = {
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.INTEGER, Types.VARCHAR, Types.INTEGER, Types.INTEGER, Types.INTEGER,
Types.INTEGER, Types.VARCHAR, Types.VARCHAR, Types.INTEGER,
Types.INTEGER, Types.INTEGER, Types.INTEGER,
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.SMALLINT
};
// DERBY-3171; we get a different value back for nullability for
// a number of the columns with networkserver/client vs. embedded
boolean nullval = true;
if (usingDerbyNetClient())
nullval = false;
boolean [] nullability = {
true, true, true, true, nullval, true, nullval,
nullval, nullval, nullval, true, true, nullval, nullval,
nullval, nullval, true, true, true, true, true
};
assertMetaDataResultSet(rs, columnNames, columnTypes, nullability);
JDBC.assertEmpty(rs);
rs = dmd.getCatalogs();
checkCatalogsShape(rs);
JDBC.assertEmpty(rs);
rs = dmd.getSuperTables(null,null,null);
columnNames = new String[] {
"TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", "SUPERTABLE_NAME"};
columnTypes = new int[] {
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR};
nullability = new boolean[] {
true, true, true, true};
assertMetaDataResultSet(rs, columnNames, columnTypes, nullability);
JDBC.assertEmpty(rs);
rs = dmd.getSuperTypes(null,null,null);
columnNames = new String[] {
"TYPE_CAT", "TYPE_SCHEM", "TYPE_NAME", "SUPERTYPE_CAT",
"SUPERTYPE_SCHEM", "SUPERTYPE_NAME"};
columnTypes = new int[] {
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR};
nullability = new boolean[] {
true, true, true, true, true, true};
assertMetaDataResultSet(rs, columnNames, columnTypes, nullability);
JDBC.assertEmpty(rs);
rs = dmd.getUDTs(null,null,null,null);
columnNames = new String[] {
"TYPE_CAT", "TYPE_SCHEM", "TYPE_NAME", "CLASS_NAME",
"DATA_TYPE", "REMARKS", "BASE_TYPE"};
columnTypes = new int[] {
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR};
nullability = new boolean[] {
true, true, true, true};
assertMetaDataResultSet(rs, null, null, null);
JDBC.assertEmpty(rs);
rs = dmd.getVersionColumns(null,null, "No_such_table");
checkVersionColumnsShape(rs);
JDBC.assertEmpty(rs);
}
/**
* Six combinations of valid identifiers with mixed
* case, to see how the various pattern matching
* and returned values handle them.
* This test only creates objects in these schemas.
*/
private static final String[] IDS =
{
"one_dmd_test",
"TWO_dmd_test",
"ThReE_dmd_test",
"\"four_dmd_test\"",
"\"FIVE_dmd_test\"",
"\"sIx_dmd_test\""
};
/**
* All the builtin schemas.
*/
private static final String[] BUILTIN_SCHEMAS = {
"APP", "NULLID", "SQLJ", "SYS", "SYSCAT", "SYSCS_DIAG",
"SYSCS_UTIL", "SYSFUN", "SYSIBM", "SYSPROC", "SYSSTAT"};
public static String getStoredIdentifier(String sqlIdentifier)
{
if (sqlIdentifier.charAt(0) == '"')
return sqlIdentifier.substring(1, sqlIdentifier.length() - 1);
else
return sqlIdentifier.toUpperCase(Locale.ENGLISH);
}
/**
* Test getSchemas() without modifying the database.
*
* @throws SQLException
*/
public void testGetSchemasReadOnly() throws SQLException {
DatabaseMetaData dmd = getDMD();
ResultSet rs = dmd.getSchemas();
checkSchemas(rs, new String[0]);
}
/**
* Test getSchemas().
*
* @throws SQLException
*/
public void testGetSchemasModify() throws SQLException {
createSchemasForTests();
DatabaseMetaData dmd = getDMD();
ResultSet rs = dmd.getSchemas();
checkSchemas(rs, IDS);
}
private void createSchemasForTests() throws SQLException
{
// Set to cleanup on teardown.
modifiedDatabase = true;
Statement s = createStatement();
for (int i = 0; i < IDS.length; i++)
s.executeUpdate("CREATE SCHEMA " + IDS[i]);
s.close();
commit();
}
/**
* Check the returned information from a getSchemas().
* The passed in String[] expected is a list of the
* schemas expected to be present in the returned
* set. The returned set may contain additional
* schemas which will be ignored, thus this test
* can be used regardless of the database state.
* The builtin schemas are automatically checked
* and must not be part of the passed in list.
*/
public static void checkSchemas(ResultSet rs,
String[] userExpected) throws SQLException
{
checkSchemasShape(rs);
// Add in the system schemas
String[] expected =
new String[BUILTIN_SCHEMAS.length + userExpected.length];
System.arraycopy(BUILTIN_SCHEMAS, 0,
expected, 0, BUILTIN_SCHEMAS.length);
System.arraycopy(userExpected, 0,
expected, BUILTIN_SCHEMAS.length, userExpected.length);
// Remove any quotes from user schemas and upper case
// those without quotes.
for (int i = BUILTIN_SCHEMAS.length; i < expected.length; i++)
{
expected[i] = getStoredIdentifier(expected[i]);
}
//output is ordered by TABLE_SCHEM
Arrays.sort(expected);
int nextMatch = 0;
while (rs.next()) {
String schema = rs.getString("TABLE_SCHEM");
assertNotNull(schema);
// Catalogs not supported
assertNull(rs.getString("TABLE_CATALOG"));
if (nextMatch < expected.length)
{
if (expected[nextMatch].equals(schema))
nextMatch++;
}
}
rs.close();
assertEquals("Schemas missing ", expected.length, nextMatch);
}
/**
* Check the shape of the ResultSet from any
* getSchemas call.
*/
private static void checkSchemasShape(ResultSet rs) throws SQLException
{
assertMetaDataResultSet(rs,
new String[] {
"TABLE_SCHEM", "TABLE_CATALOG"
},
new int[] {
Types.VARCHAR, Types.VARCHAR
}
, new boolean[] {false, true}
);
}
/**
* Execute dmd.getTables() but perform additional checking
* of the ODBC variant.
* @throws IOException
*/
private ResultSet getDMDTables(DatabaseMetaData dmd,
String catalog, String schema, String table, String[] tableTypes)
throws SQLException, IOException
{
checkGetTablesODBC(catalog, schema, table, tableTypes);
return dmd.getTables(catalog, schema, table, tableTypes);
}
/**
* Test getTables() without modifying the database.
*
* @throws SQLException
* @throws IOException
*/
public void testGetTablesReadOnly() throws SQLException, IOException {
DatabaseMetaData dmd = getDMD();
ResultSet rs;
rs = getDMDTables(dmd, null, null, null, null);
checkTablesShape(rs);
int allTableCount = JDBC.assertDrainResults(rs);
assertTrue("getTables() on all was empty!", allTableCount > 0);
rs = getDMDTables(dmd, "%", "%", "%", null);
checkTablesShape(rs);
assertEquals("Different counts from getTables",
allTableCount, JDBC.assertDrainResults(rs));
rs = getDMDTables(dmd, null, "NO_such_schema", null, null);
checkTablesShape(rs);
JDBC.assertEmpty(rs);
rs = getDMDTables(dmd, null, "SQLJ", null, null);
checkTablesShape(rs);
JDBC.assertEmpty(rs);
rs = getDMDTables(dmd, null, "SQLJ", "%", null);
checkTablesShape(rs);
JDBC.assertEmpty(rs);
rs = getDMDTables(dmd, null, "SYS", "No_such_table", null);
checkTablesShape(rs);
JDBC.assertEmpty(rs);
String[] userTableOnly = new String[] {"TABLE"};
// no user tables in SYS
rs = getDMDTables(dmd, null, "SYS", null, userTableOnly);
checkTablesShape(rs);
JDBC.assertEmpty(rs);
rs = getDMDTables(dmd, null, "SYS", "%", userTableOnly);
checkTablesShape(rs);
JDBC.assertEmpty(rs);
String[] systemTableOnly = new String[] {"SYSTEM_TABLE"};
rs = getDMDTables(dmd, null, "SYS", null, systemTableOnly);
checkTablesShape(rs);
int systemTableCount = JDBC.assertDrainResults(rs);
assertTrue("getTables() on system tables was empty!", systemTableCount > 0);
rs = getDMDTables(dmd, null, "SYS", "%", systemTableOnly);
checkTablesShape(rs);
assertEquals(systemTableCount, JDBC.assertDrainResults(rs));
String[] viewOnly = new String[] {"VIEW"};
rs = getDMDTables(dmd, null, "SYS", null, viewOnly);
JDBC.assertEmpty(rs);
rs = getDMDTables(dmd, null, "SYS", "%", viewOnly);
JDBC.assertEmpty(rs);
String[] allTables = {"SYNONYM","SYSTEM TABLE","TABLE","VIEW"};
rs = getDMDTables(dmd, null, null, null, allTables);
checkTablesShape(rs);
assertEquals("Different counts from getTables",
allTableCount, JDBC.assertDrainResults(rs));
rs = getDMDTables(dmd, "%", "%", "%", allTables);
checkTablesShape(rs);
assertEquals("Different counts from getTables",
allTableCount, JDBC.assertDrainResults(rs));
}
/**
* Test getTables() with modifying the database.
*
* @throws SQLException
* @throws IOException
*/
public void testGetTablesModify() throws SQLException, IOException {
int totalTables = createTablesForTest(false);
DatabaseMetaData dmd = getDMD();
ResultSet rs;
String[] userTableOnly = new String[] {"TABLE"};
// Get the list of idenifiers from IDS as the database
// would store them in the order required.
String[] dbIDS = getSortedIdentifiers();
// Check the contents, ordered by TABLE_CAT, TABLE_SCHEMA, TABLE_NAME
rs = getDMDTables(dmd, null, null, null, userTableOnly);
checkTablesShape(rs);
int rowPosition = 0;
while (rs.next())
{
//boolean ourTable;
assertEquals("TABLE_CAT", "", rs.getString("TABLE_CAT"));
String schema = rs.getString("TABLE_SCHEM");
// See if the table is in one of the schemas we created.
// If not we perform what checking we can.
boolean ourSchema = Arrays.binarySearch(dbIDS, schema) >= 0;
if (ourSchema) {
assertEquals("TABLE_SCHEM",
dbIDS[rowPosition/dbIDS.length], schema);
assertEquals("TABLE_NAME",
dbIDS[rowPosition%dbIDS.length], rs.getString("TABLE_NAME"));
}
assertEquals("TABLE_TYPE", "TABLE", rs.getString("TABLE_TYPE"));
assertEquals("REMARKS", "", rs.getString("REMARKS"));
assertNull("TYPE_CAT", rs.getString("TYPE_CAT"));
assertNull("TYPE_SCHEM", rs.getString("TYPE_SCHEM"));
assertNull("TYPE_NAME", rs.getString("TYPE_NAME"));
assertNull("SELF_REFERENCING_COL_NAME", rs.getString("SELF_REFERENCING_COL_NAME"));
assertNull("REF_GENERATION", rs.getString("REF_GENERATION"));
if (ourSchema)
rowPosition++;
}
rs.close();
assertEquals("getTables count for all user tables",
totalTables, rowPosition);
Random rand = new Random();
// Test using schema pattern with a pattern unique to
// a single schema.
for (int i = 0; i < dbIDS.length; i++)
{
String schema = dbIDS[i];
int pc = rand.nextInt(6);
String schemaPattern = schema.substring(0, pc + 2) + "%";
rs = getDMDTables(dmd, null, schemaPattern, null, userTableOnly);
checkTablesShape(rs);
rowPosition = 0;
while (rs.next())
{
assertEquals("TABLE_SCHEM",
schema, rs.getString("TABLE_SCHEM"));
assertEquals("TABLE_NAME",
dbIDS[rowPosition%dbIDS.length], rs.getString("TABLE_NAME"));
assertEquals("TABLE_TYPE", "TABLE", rs.getString("TABLE_TYPE"));
rowPosition++;
}
rs.close();
assertEquals("getTables count schema pattern",
dbIDS.length, rowPosition);
}
// Test using table pattern with a pattern unique to
// a single table per schema.
for (int i = 0; i < dbIDS.length; i++)
{
String table = dbIDS[i];
int pc = rand.nextInt(6);
String tablePattern = table.substring(0, pc + 2) + "%";
rs = getDMDTables(dmd, null, null, tablePattern, userTableOnly);
checkTablesShape(rs);
rowPosition = 0;
while (rs.next())
{
assertEquals("TABLE_SCHEM",
dbIDS[rowPosition%dbIDS.length], rs.getString("TABLE_SCHEM"));
assertEquals("TABLE_TYPE", "TABLE", rs.getString("TABLE_TYPE"));
assertEquals("TABLE_NAME",
table, rs.getString("TABLE_NAME"));
rowPosition++;
}
rs.close();
assertEquals("getTables count schema pattern",
dbIDS.length, rowPosition);
}
}
/**
* Execute and check the ODBC variant of getTables which
* uses a procedure to provide the same information to ODBC clients.
* @throws IOException
*/
private void checkGetTablesODBC(String catalog, String schema,
String table, String[] tableTypes) throws SQLException, IOException
{
String tableTypesAsString = null;
if (tableTypes != null) {
int count = tableTypes.length;
StringBuffer sb = new StringBuffer();
for (int i = 0; i < count; i++) {
if (i > 0)
sb.append(",");
sb.append(tableTypes[i]);
}
tableTypesAsString = sb.toString();
}
CallableStatement cs = prepareCall(
"CALL SYSIBM.SQLTABLES(?, ?, ?, ?, 'DATATYPE=''ODBC''')");
cs.setString(1, catalog);
cs.setString(2, schema);
cs.setString(3, table);
cs.setString(4, tableTypesAsString);
cs.execute();
ResultSet odbcrs = cs.getResultSet();
assertNotNull(odbcrs);
// Returned ResultSet will have the same shape as
// DatabaseMetaData.getTables() even though ODBC
// only defines the first five columns.
checkTablesShape(odbcrs);
// Expect the contents of JDBC and ODBC metadata to be the same.
ResultSet dmdrs = getDMD().getTables(catalog, schema, table, tableTypes);
JDBC.assertSameContents(odbcrs, dmdrs);
cs.close();
}
/**
* Create a set of tables using the identifiers in IDS.
* For each identifier in IDS a schema is created.
* For each identifier in IDS create a table in every schema just created.
* Each table has five columns with names using the identifiers from IDS
* suffixed with _N where N is the column number in the table. The base
* name for each column is round-robined from the set of IDS.
* The type of each column is round-robined from the set of supported
* types returned by getSQLTypes.
*
* <BR>
* skipXML can be set to true to create tables without any XML
* columns. This is useful for getColumns() testing where
* the fixture compares the output of DatabaseMetaData to
* ResultSetMetaData by a SELCT * from the table. However
* for XML columns they cannot be returned through JDBC yet.
*
* @param skipXML true if tables with the XML column should not
* be created.
* @throws SQLException
*/
private int createTablesForTest(boolean skipXML) throws SQLException
{
getConnection().setAutoCommit(false);
List types = getSQLTypes(getConnection());
if (skipXML)
types.remove("XML");
int typeCount = types.size();
createSchemasForTests();
Statement s = createStatement();
int columnCounter = 0;
for (int sid = 0; sid < IDS.length; sid++) {
for (int tid = 0; tid < IDS.length; tid++)
{
StringBuffer sb = new StringBuffer();
sb.append("CREATE TABLE ");
sb.append(IDS[sid]);
sb.append('.');
sb.append(IDS[tid]);
sb.append(" (");
// Five columns per table
for (int c = 1; c <= 5; c++) {
String colName = IDS[columnCounter % IDS.length];
boolean delimited = colName.charAt(colName.length() - 1) == '"';
if (delimited)
colName = colName.substring(0, colName.length() - 1);
sb.append(colName);
sb.append('_');
sb.append(c); // append the column number
if (delimited)
sb.append('"');
sb.append(' ');
sb.append(types.get(columnCounter++ % typeCount));
if (c < 5)
sb.append(", ");
}
sb.append(")");
s.execute(sb.toString());
}
}
s.close();
commit();
return IDS.length * IDS.length;
}
/**
* Test getTableColumns().
* Contents are compared to the ResultSetMetaData
* for a SELECT * from the table. All columns in
* all tables are checked.
*/
public void testGetColumnsReadOnly() throws SQLException
{
DatabaseMetaData dmd = getDMD();
ResultSet rs = dmd.getColumns(null, null, null, null);
checkColumnsShape(rs);
crossCheckGetColumnsAndResultSetMetaData(rs, false);
}
/**
* Test getColumns() with modifying the database.
*
* @throws SQLException
*/
public void testGetColumnsModify() throws SQLException {
// skip XML datatype as our cross check with
// ResultSetMetaData will fail
int totalTables = createTablesForTest(true);
// First cross check all the columns in the database
// with the ResultSetMetaData.
testGetColumnsReadOnly();
Random rand = new Random();
String[] dbIDS = getSortedIdentifiers();
DatabaseMetaData dmd = this.getDMD();
for (int i = 1; i < 20; i++) {
int seenColumnCount = 0;
// These are the pattern matching parameters
String schemaPattern = getPattern(rand, dbIDS);
String tableNamePattern = getPattern(rand, dbIDS);
String columnNamePattern = getPattern(rand, dbIDS);
ResultSet rs = dmd.getColumns(null,
schemaPattern, tableNamePattern, columnNamePattern);
checkColumnsShape(rs);
while (rs.next())
{
String schema = rs.getString("TABLE_SCHEM");
String table = rs.getString("TABLE_NAME");
String column = rs.getString("COLUMN_NAME");
assertMatchesPattern(schemaPattern, schema);
assertMatchesPattern(tableNamePattern, table);
assertMatchesPattern(columnNamePattern, column);
seenColumnCount++;
}
rs.close();
// Re-run to check the correct data is returned
// when filtering is enabled
rs = dmd.getColumns(null,
schemaPattern, tableNamePattern, columnNamePattern);
crossCheckGetColumnsAndResultSetMetaData(rs, true);
// Now re-execute fetching all schemas, columns etc.
// and see we can the same result when we "filter"
// in the application
int appColumnCount = 0;
rs = dmd.getColumns(null,null, null, null);
while (rs.next())
{
String schema = rs.getString("TABLE_SCHEM");
String table = rs.getString("TABLE_NAME");
String column = rs.getString("COLUMN_NAME");
if (!doesMatch(schemaPattern, 0, schema, 0))
continue;
if (!doesMatch(tableNamePattern, 0, table, 0))
continue;
if (!doesMatch(columnNamePattern, 0, column, 0))
continue;
appColumnCount++;
}
rs.close();
assertEquals("Mismatched column count on getColumns() filtering",
seenColumnCount, appColumnCount);
}
}
private void assertMatchesPattern(String pattern, String result)
{
if (!doesMatch(pattern, 0, result, 0))
{
fail("Bad pattern matching:" + pattern +
" result:" + result);
}
}
/**
* See if a string matches the pattern as defined by
* DatabaseMetaData. By passing in non-zero values
* can check sub-sets of the pattern against the
* sub strings of the result.
* <BR>
* _ matches a single character
* <BR>
* % matches zero or more characters
* <BR>
* Other characters match themselves.
* @param pattern Pattern
* @param pp Position in pattern to start the actual pattern from
* @param result result string
* @param rp position in result to starting checking
* @return true if a match is found
*/
private boolean doesMatch(String pattern, int pp,
String result, int rp)
{
// Find a match
for (;;)
{
if (pp == pattern.length() && rp == result.length())
return true;
// more characters to match in the result but
// no more pattern.
if (pp == pattern.length())
return false;
char pc = pattern.charAt(pp);
if (pc == '_')
{
// need to match a single character but
// exhausted result, so no match.
if (rp == result.length())
return false;
pp++;
rp++;
}
else if (pc == '%')
{
// % at end, complete match regardless of
// position of result since % matches zero or more.
if (pp == pattern.length() - 1)
{
return true;
}
// Brut force, we have a pattern like %X
// and we are say in the third character of
// abCdefgX
// then start a 'CdefgX' and look for a match,
// then 'defgX' etc.
for (int sp = rp; sp < result.length(); sp++)
{
if (doesMatch(pattern, pp+1, result, sp))
{
// Have a match for the pattern after the %
// which means we have a match for the pattern
// with the % since we can match 0 or mor characters
// with %.
return true;
}
}
// Could not match the pattern after the %
return false;
}
else
{
// need to match a single character but
// exhausted result, so no match.
if (rp == result.length())
return false;
// Single character, must match exactly.
if (pc != result.charAt(rp))
{
//Computer says no.
return false;
}
pp++;
rp++;
}
}
}
private String getPattern(Random rand, String[] dbIDS)
{
int y = rand.nextInt(100);
if (y < 10)
return "%"; // All
if (y < 30)
return dbIDS[rand.nextInt(dbIDS.length)]; // exact match
String base;
if (y < 40)
{
// Base for some pattern that can never match
base = "XxZZzXXZZZxxXxZz";
}
else
{
base = dbIDS[rand.nextInt(dbIDS.length)];
}
StringBuffer sb = new StringBuffer();
for (int i = 0; i < base.length();)
{
int x = rand.nextInt(10);
if (x < 5)
x = 0; // bias towards keeping the characters.
boolean inWild;
if (sb.length() == 0)
inWild = false;
else
{
char last = sb.charAt(sb.length() - 1);
inWild = last == '_' || last == '%';
}
if (x == 0)
{
// character from base
sb.append(base.charAt(i++));
}
else if (x == 5)
{
i++;
// single character match
if (!inWild)
sb.append('_');
}
else
{
i += (x - 5);
// replace a number of characters with %
if (!inWild)
sb.append('%');
}
}
// Some pattern involving
return sb.toString();
}
/**
* Compare a ResultSet from getColumns() with ResultSetMetaData
* returned from a SELECT * against the table. This method
* handles situations where a full set of the columns are in
* the ResultSet.
* The first action is to call rs.next().
* The ResultSet will be closed by this method.
* @param rs
* @throws SQLException
*/
private void crossCheckGetColumnsAndResultSetMetaData(ResultSet rs,
boolean partial)
throws SQLException
{
Statement s = createStatement();
while (rs.next())
{
String schema = rs.getString("TABLE_SCHEM");
String table = rs.getString("TABLE_NAME");
ResultSet rst = s.executeQuery(
"SELECT * FROM " + JDBC.escape(schema, table));
ResultSetMetaData rsmdt = rst.getMetaData();
for (int col = 1; col <= rsmdt.getColumnCount() ; col++)
{
if (!partial) {
if (col != 1)
assertTrue(rs.next());
assertEquals("ORDINAL_POSITION",
col, rs.getInt("ORDINAL_POSITION"));
}
assertEquals("TABLE_CAT",
"", rs.getString("TABLE_CAT"));
assertEquals("TABLE_SCHEM",
schema, rs.getString("TABLE_SCHEM"));
assertEquals("TABLE_NAME",
table, rs.getString("TABLE_NAME"));
crossCheckGetColumnRowAndResultSetMetaData(rs, rsmdt);
if (partial)
break;
}
rst.close();
}
rs.close();
s.close();
}
/**
* Cross check a single row from getColumns() with ResultSetMetaData
* for a SELECT * from the same table.
* @param rs ResultSet from getColumns already positioned on the row.
* @param rsmdt ResultSetMetaData for the SELECT *
* @throws SQLException
*/
public static void crossCheckGetColumnRowAndResultSetMetaData(
ResultSet rs, ResultSetMetaData rsmdt)
throws SQLException
{
int col = rs.getInt("ORDINAL_POSITION");
assertEquals("RSMD.getCatalogName",
rsmdt.getCatalogName(col), rs.getString("TABLE_CAT"));
assertEquals("RSMD.getSchemaName",
rsmdt.getSchemaName(col), rs.getString("TABLE_SCHEM"));
assertEquals("RSMD.getTableName",
rsmdt.getTableName(col), rs.getString("TABLE_NAME"));
assertEquals("COLUMN_NAME",
rsmdt.getColumnName(col), rs.getString("COLUMN_NAME"));
// DERBY-2285 BOOLEAN columns appear different on
// network client.
// DMD returns BOOLEAN
// RSMD returns SMALLINT
int dmdColumnType = rs.getInt("DATA_TYPE");
if (dmdColumnType == Types.BOOLEAN && usingDerbyNetClient())
{
assertEquals("TYPE_NAME",
"BOOLEAN", rs.getString("TYPE_NAME"));
assertEquals("TYPE_NAME",
"SMALLINT", rsmdt.getColumnTypeName(col));
assertEquals("DATA_TYPE",
Types.SMALLINT, rsmdt.getColumnType(col));
}
else if (dmdColumnType == Types.JAVA_OBJECT && usingDerbyNetClient())
{
// DMD returns JAVA_OBJECT
// RSMD returns LONGVARBINARY!
assertEquals("DATA_TYPE",
Types.LONGVARBINARY, rsmdt.getColumnType(col));
}
else if (dmdColumnType == Types.VARBINARY && usingDerbyNetClient())
{
// DMD returns different type name to RSMD
assertEquals("DATA_TYPE",
Types.VARBINARY, rsmdt.getColumnType(col));
}
else if (dmdColumnType == Types.BINARY && usingDerbyNetClient())
{
// DMD returns different type name to RSMD
assertEquals("DATA_TYPE",
Types.BINARY, rsmdt.getColumnType(col));
}
else if (dmdColumnType == Types.NUMERIC && usingDerbyNetClient())
{
// DERBY-584 inconsistency in numeric & decimal
assertEquals("DATA_TYPE",
Types.DECIMAL, rsmdt.getColumnType(col));
assertEquals("TYPE_NAME",
"DECIMAL", rsmdt.getColumnTypeName(col));
assertEquals("TYPE_NAME",
"NUMERIC", rs.getString("TYPE_NAME"));
}
else
{
assertEquals("DATA_TYPE",
rsmdt.getColumnType(col), rs.getInt("DATA_TYPE"));
assertEquals("TYPE_NAME",
rsmdt.getColumnTypeName(col), rs.getString("TYPE_NAME"));
}
/*
if (dmdColumnType != Types.JAVA_OBJECT) {
System.out.println("TYPE " + rs.getInt("DATA_TYPE"));
System.out.println(JDBC.escape(schema, table) + " " + rs.getString("COLUMN_NAME"));
assertEquals("COLUMN_SIZE",
rsmdt.getPrecision(col), rs.getInt("COLUMN_SIZE"));
}
*/
// not used by JDBC spec
assertEquals("BUFFER_LENGTH", 0, rs.getInt("BUFFER_LENGTH"));
assertTrue("BUFFER_LENGTH", rs.wasNull());
/*
assertEquals("DECIMAL_DIGITS",
rsmdt.getScale(col), rs.getInt("DECIMAL_DIGITS"));
*/
// This assumes the constants defined by DMD and ResultSet
// for nullability are equal. They are by inspection
// and since they are static final and part of a defined
// api by definition they cannot change. We also
// check statically this is true in the testConstants fixture.
assertEquals("NULLABLE",
rsmdt.isNullable(col), rs.getInt("NULLABLE"));
// REMARKS set to empty string by Derby
assertEquals("REMARKS", "", rs.getString("REMARKS"));
// COLUMN_DEF ??
// both unused by JDBC spec
assertEquals("SQL_DATA_TYPE", 0, rs.getInt("SQL_DATA_TYPE"));
assertTrue(rs.wasNull());
assertEquals("SQL_DATETIME_SUB", 0, rs.getInt("SQL_DATETIME_SUB"));
assertTrue(rs.wasNull());
// IS_NULLABLE
switch (rsmdt.isNullable(col))
{
case ResultSetMetaData.columnNoNulls:
assertEquals("IS_NULLABLE", "NO", rs.getString("IS_NULLABLE"));
break;
case ResultSetMetaData.columnNullable:
assertEquals("IS_NULLABLE", "YES", rs.getString("IS_NULLABLE"));
break;
case ResultSetMetaData.columnNullableUnknown:
assertEquals("IS_NULLABLE", "", rs.getString("IS_NULLABLE"));
break;
default:
fail("invalid return from rsmdt.isNullable(col)");
}
// SCOPE not supported
assertNull("SCOPE_CATLOG", rs.getString("SCOPE_CATLOG"));
assertNull("SCOPE_SCHEMA", rs.getString("SCOPE_SCHEMA"));
assertNull("SCOPE_TABLE", rs.getString("SCOPE_TABLE"));
// DISTINCT not supported
assertEquals("SOURCE_DATA_TYPE", 0, rs.getShort("SOURCE_DATA_TYPE"));
assertTrue(rs.wasNull());
// IS_AUTOINCREMENT added in JDBC 4.0
assertEquals("IS_AUTOINCREMENT",
rsmdt.isAutoIncrement(col) ? "YES" : "NO",
rs.getString("IS_AUTOINCREMENT"));
assertFalse(rs.wasNull());
}
/**
* Test getTableTypes()
*/
public void testTableTypes() throws SQLException
{
DatabaseMetaData dmd = getDMD();
ResultSet rs = dmd.getTableTypes();
assertMetaDataResultSet(rs,
new String[] {
"TABLE_TYPE"
},
new int[] {
Types.VARCHAR
}
, null
);
JDBC.assertFullResultSet(rs, new String[][]
{
{"SYNONYM"},{"SYSTEM TABLE"},{"TABLE"},{"VIEW"},
}, true);
rs.close();
}
/**
* Test getTypeInfo
* @throws SQLException
*/
public void testGetTypeInfo() throws SQLException
{
// Client returns BOOLEAN type from the engine as SMALLINT
int BOOLEAN = Types.BOOLEAN;
if (usingDerbyNetClient())
BOOLEAN = Types.SMALLINT;
String[] JDBC_COLUMN_NAMES = new String[] {
"TYPE_NAME", "DATA_TYPE", "PRECISION", "LITERAL_PREFIX",
"LITERAL_SUFFIX", "CREATE_PARAMS", "NULLABLE", "CASE_SENSITIVE",
"SEARCHABLE", "UNSIGNED_ATTRIBUTE", "FIXED_PREC_SCALE",
"AUTO_INCREMENT", "LOCAL_TYPE_NAME",
"MINIMUM_SCALE", "MAXIMUM_SCALE",
"SQL_DATA_TYPE", "SQL_DATETIME_SUB",
"NUM_PREC_RADIX"
};
int[] JDBC_COLUMN_TYPES = new int[] {
Types.VARCHAR, Types.INTEGER, Types.INTEGER, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR, Types.SMALLINT, BOOLEAN,
Types.SMALLINT, BOOLEAN, BOOLEAN,
BOOLEAN, Types.VARCHAR,
Types.SMALLINT, Types.SMALLINT,
Types.INTEGER, Types.INTEGER,
Types.INTEGER
};
boolean[] JDBC_COLUMN_NULLABILITY = {
false, false, true, true,
true, true, false, false,
false, true, false,
true, true,
true, true,
true, true,
true
};
// DERBY-2307 Nullablity is wrong for columns 1,7,9 (1-based)
// Make a modified copy of JDBC_COLUMN_NULLABILITY
// here to allow the test to pass. Left JDBC_COLUMN_NULLABILITY
// as the expected versions as it is also used for the ODBC
// checks below and has the correct values.
boolean[] JDBC_COLUMN_NULLABILITY_DERBY_2307 = {
true, false, true, true,
true, true, true, false,
true, true, false,
true, true,
true, true,
true, true,
true
};
ResultSet rs = getDMD().getTypeInfo();
assertMetaDataResultSet(rs, JDBC_COLUMN_NAMES, JDBC_COLUMN_TYPES
, JDBC_COLUMN_NULLABILITY_DERBY_2307
);
/*
Derby-2258 Removed 3 data types which are not supported by Derby
and added XML data type which is supported by Derby
*/
int[] supportedTypes = new int[] {
Types.BIGINT, Types.BINARY, Types.BLOB,
Types.CHAR, Types.CLOB, Types.DATE,
Types.DECIMAL, Types.DOUBLE, Types.FLOAT,
Types.INTEGER, Types.LONGVARBINARY, Types.LONGVARCHAR,
Types.NUMERIC, Types.REAL, Types.SMALLINT,
Types.TIME, Types.TIMESTAMP, Types.VARBINARY,
Types.VARCHAR, JDBC.SQLXML
};
// Rows are returned from getTypeInfo in order of
// "DATA_TYPE" (which is a constant from java.sql.Types)
Arrays.sort(supportedTypes);
int offset = 0;
while (rs.next()) {
// TYPE_NAME (column 1)
String typeName = rs.getString("TYPE_NAME");
assertNotNull(typeName);
// DATA_TYPE (column 2)
int type = rs.getInt("DATA_TYPE");
assertFalse(rs.wasNull());
if (supportedTypes[offset] != type)
{
fail("Unexpected type " + typeName);
}
else
{
offset++;
}
// PRECISION (column 3)
int precision = -1;
switch (type)
{
case Types.BINARY:
case Types.CHAR:
precision = 254;
break;
case Types.BLOB:
case Types.CLOB:
precision = Integer.MAX_VALUE;
break;
case Types.DATE:
precision = 10;
break;
case Types.TIME:
precision = 8;
break;
case Types.TIMESTAMP:
precision = 26;
break;
case Types.DECIMAL:
case Types.NUMERIC:
precision = 31;
break;
case Types.DOUBLE:
case Types.FLOAT:
precision = 52;
break;
case Types.REAL:
precision = 23;
break;
case Types.BIGINT:
precision = 19;
break;
case Types.INTEGER:
precision = 10;
break;
case Types.SMALLINT:
precision = 5;
break;
case Types.LONGVARBINARY:
case Types.LONGVARCHAR:
precision = 32700;
break;
/*
Derby-2260 Correcting the precision value for VARCHAR FOR BIT DATA
Thus this test also now expects the correct value i.e. 32672
Also adding precision check for SQLXML data type
*/
case Types.VARBINARY:
precision = 32672;
break;
case Types.VARCHAR:
precision = 32672;
break;
case JDBC.SQLXML:
precision = 0;
break;
}
assertEquals("PRECISION " + typeName,
precision, rs.getInt("PRECISION"));
/*
Precision value is null for XML data type
*/
if (typeName.equals("XML" ))
assertTrue(rs.wasNull());
else
assertFalse(rs.wasNull());
// LITERAL_PREFIX (column 4)
// LITERAL_SUFFIX (column 5)
// CREATE_PARAMS (column 6)
String createParams;
switch (type)
{
case Types.CHAR:
case Types.VARCHAR:
case Types.BLOB:
case Types.CLOB:
case Types.BINARY:
case Types.VARBINARY:
createParams = "length";
break;
case Types.DECIMAL:
case Types.NUMERIC:
createParams = "precision,scale";
break;
case Types.FLOAT:
createParams = "precision";
break;
default:
createParams = null;
break;
}
assertEquals("CREATE_PARAMS " + typeName,
createParams, rs.getString("CREATE_PARAMS"));
// NULLABLE (column 7) - all types are nullable in Derby
assertEquals("NULLABLE " + typeName,
DatabaseMetaData.typeNullable, rs.getInt("NULLABLE"));
assertFalse(rs.wasNull());
// CASE_SENSITIVE (column 8)
// SEARCHABLE (column 9) - most types searchable
{
int searchable;
switch (type)
{
/*
Derby-2259 Correcting the searchable value for
LONGVARBINARY, LONGVARCHAR & BLOB data type
also adding SQLXML data type in the test.
*/
case Types.LONGVARBINARY:
searchable = DatabaseMetaData.typePredNone;
break;
case Types.LONGVARCHAR:
searchable = DatabaseMetaData.typePredChar;
break;
case Types.BLOB:
searchable = DatabaseMetaData.typePredNone;
break;
case Types.CLOB:
searchable = DatabaseMetaData.typePredChar;
break;
case Types.CHAR:
case Types.VARCHAR:
searchable = DatabaseMetaData.typeSearchable;
break;
case JDBC.SQLXML:
searchable = DatabaseMetaData.typePredNone;
break;
default:
searchable = DatabaseMetaData.typePredBasic;
break;
}
assertEquals("SEARCHABLE " + typeName,
searchable, rs.getInt("SEARCHABLE"));
}
// UNSIGNED_ATTRIBUTE (column 10)
//assertFalse("UNSIGNED_ATTRIBUTE " + typeName,
// rs.getBoolean("UNSIGNED_ATTRIBUTE"));
// FIXED_PREC_SCALE (column 11)
boolean fixedScale = type == Types.DECIMAL || type == Types.NUMERIC;
assertEquals("FIXED_PREC_SCALE " + typeName,
fixedScale, rs.getBoolean("FIXED_PREC_SCALE"));
assertFalse(rs.wasNull());
// AUTO_INCREMENT (column 12)
boolean autoIncrement;
switch (type)
{
case Types.BIGINT:
case Types.INTEGER:
case Types.SMALLINT:
autoIncrement = true;
break;
default:
autoIncrement = false;
break;
}
assertEquals("AUTO_INCREMENT " + typeName,
autoIncrement, rs.getBoolean("AUTO_INCREMENT"));
// LOCAL_TYPE_NAME (column 13) always the same as TYPE_NAME
assertEquals("LOCAL_TYPE_NAME " + typeName,
typeName, rs.getString("LOCAL_TYPE_NAME"));
int maxScale;
boolean hasScale = true;
switch (type)
{
case Types.DECIMAL:
case Types.NUMERIC:
maxScale = 31; // Max Scale for Decimal & Numeric is 31: Derby-2262
break;
case Types.TIMESTAMP:
maxScale = 6;
break;
case Types.SMALLINT:
case Types.INTEGER:
case Types.BIGINT:
case Types.DATE:
case Types.TIME:
maxScale = 0;
break;
default:
maxScale = 0;
hasScale = false;
break;
}
// MINIMUM_SCALE (column 14)
assertEquals("MINIMUM_SCALE " + typeName,
0, rs.getInt("MINIMUM_SCALE"));
assertEquals("MINIMUM_SCALE (wasNull) " + typeName,
!hasScale, rs.wasNull());
// MAXIMUM_SCALE (column 15)
assertEquals("MAXIMUM_SCALE " + typeName,
maxScale, rs.getInt("MAXIMUM_SCALE"));
assertEquals("MAXIMUM_SCALE (wasNull)" + typeName,
!hasScale, rs.wasNull());
// SQL_DATA_TYPE (column 16) - Unused
assertEquals("SQL_DATA_TYPE " + typeName,
0, rs.getInt("SQL_DATA_TYPE"));
assertTrue(rs.wasNull());
// SQL_DATETIME_SUB (column 17) - Unused
assertEquals("SQL_DATETIME_SUB " + typeName,
0, rs.getInt("SQL_DATETIME_SUB"));
assertTrue(rs.wasNull());
// NUM_PREC_RADIX (column 18)
}
rs.close();
// Now check the ODBC version:
// ODBC column names & types differ from JDBC slightly.
// ODBC has one more column.
String[] ODBC_COLUMN_NAMES = new String[19];
System.arraycopy(JDBC_COLUMN_NAMES, 0, ODBC_COLUMN_NAMES, 0,
JDBC_COLUMN_NAMES.length);
ODBC_COLUMN_NAMES[2] = "COLUMN_SIZE";
ODBC_COLUMN_NAMES[11] = "AUTO_UNIQUE_VAL";
ODBC_COLUMN_NAMES[18] = "INTERVAL_PRECISION";
int[] ODBC_COLUMN_TYPES = new int[ODBC_COLUMN_NAMES.length];
System.arraycopy(JDBC_COLUMN_TYPES, 0, ODBC_COLUMN_TYPES, 0,
JDBC_COLUMN_TYPES.length);
ODBC_COLUMN_TYPES[1] = Types.SMALLINT; // DATA_TYPE
ODBC_COLUMN_TYPES[7] = Types.SMALLINT; // CASE_SENSITIVE
ODBC_COLUMN_TYPES[9] = Types.SMALLINT; // UNSIGNED_ATTRIBUTE
ODBC_COLUMN_TYPES[10] = Types.SMALLINT; // FIXED_PREC_SCALE
ODBC_COLUMN_TYPES[11] = Types.SMALLINT; // AUTO_UNIQUE_VAL
ODBC_COLUMN_TYPES[15] = Types.SMALLINT; // SQL_DATA_TYPE
ODBC_COLUMN_TYPES[16] = Types.SMALLINT; // SQL_DATETIME_SUB
ODBC_COLUMN_TYPES[18] = Types.SMALLINT; // INTERVAL_PRECISION
boolean[] ODBC_COLUMN_NULLABILITY = new boolean[ODBC_COLUMN_NAMES.length];
System.arraycopy(JDBC_COLUMN_NULLABILITY, 0, ODBC_COLUMN_NULLABILITY, 0,
JDBC_COLUMN_NULLABILITY.length);
ODBC_COLUMN_NULLABILITY[15] = false; // // SQL_DATETIME_SUB (JDBC unused)
ODBC_COLUMN_NULLABILITY[18] = true; // INTERVAL_PRECISION
CallableStatement cs = prepareCall(
"CALL SYSIBM.SQLGETTYPEINFO (0, 'DATATYPE=''ODBC''')");
cs.execute();
ResultSet odbcrs = cs.getResultSet();
assertNotNull(odbcrs);
assertMetaDataResultSet(odbcrs, ODBC_COLUMN_NAMES, ODBC_COLUMN_TYPES, null);
odbcrs.close();
cs.close();
}
/*
* Check the shape of the ResultSet from any getColumns call.
*/
private void checkColumnsShape(ResultSet rs) throws SQLException
{
assertMetaDataResultSet(rs,
new String[] {
"TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", "COLUMN_NAME",
"DATA_TYPE", "TYPE_NAME", "COLUMN_SIZE", "BUFFER_LENGTH",
"DECIMAL_DIGITS", "NUM_PREC_RADIX", "NULLABLE", "REMARKS",
"COLUMN_DEF", "SQL_DATA_TYPE", "SQL_DATETIME_SUB", "CHAR_OCTET_LENGTH",
"ORDINAL_POSITION", "IS_NULLABLE", "SCOPE_CATLOG", "SCOPE_SCHEMA",
"SCOPE_TABLE", "SOURCE_DATA_TYPE", "IS_AUTOINCREMENT"
},
new int[] {
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.INTEGER, Types.VARCHAR, Types.INTEGER, Types.INTEGER,
Types.INTEGER, Types.INTEGER, Types.INTEGER, Types.VARCHAR,
Types.VARCHAR, Types.INTEGER, Types.INTEGER, Types.INTEGER,
Types.INTEGER, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.SMALLINT, Types.VARCHAR
}
, null
);
}
/**
* Check the shape of the ResultSet from any getTables call.
*/
private void checkTablesShape(ResultSet rs) throws SQLException
{
assertMetaDataResultSet(rs,
new String[] {
"TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", "TABLE_TYPE",
"REMARKS", "TYPE_CAT", "TYPE_SCHEM", "TYPE_NAME",
"SELF_REFERENCING_COL_NAME", "REF_GENERATION"
},
new int[] {
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR
}
, new boolean[] {
true, false, false, true, // TABLE_SCHEM cannot be NULL in Derby
true, true, true, true,
true, true
}
);
}
/**
* Check the shape of the ResultSet from any getCatlogs call.
*/
private void checkCatalogsShape(ResultSet rs) throws SQLException
{
assertMetaDataResultSet(rs,
new String[] {
"TABLE_CAT"
},
new int[] {
Types.CHAR
}
, new boolean[] {false}
);
}
/**
* Check the shape of the ResultSet from any
* getVersionColumns call.
*/
private static void checkVersionColumnsShape(ResultSet rs) throws SQLException
{
assertMetaDataResultSet(rs,
new String[] {
"SCOPE", "COLUMN_NAME", "DATA_TYPE", "TYPE_NAME",
"COLUMN_SIZE", "BUFFER_LENGTH", "DECIMAL_DIGITS", "PSEUDO_COLUMN"
},
new int[] {
Types.SMALLINT, Types.VARCHAR, Types.INTEGER, Types.VARCHAR,
Types.INTEGER, Types.INTEGER, Types.SMALLINT, Types.SMALLINT
}
, null
);
}
public static void assertMetaDataResultSet(ResultSet rs,
String[] columnNames, int[] columnTypes,
boolean[] nullability) throws SQLException
{
assertEquals(ResultSet.TYPE_FORWARD_ONLY, rs.getType());
assertEquals(ResultSet.CONCUR_READ_ONLY, rs.getConcurrency());
//assertNull(rs.getStatement());
if (columnNames != null)
JDBC.assertColumnNames(rs, columnNames);
if (columnTypes != null)
JDBC.assertColumnTypes(rs, columnTypes);
if (nullability != null)
JDBC.assertNullability(rs, nullability);
}
/*
** Set of escaped functions.
*/
/**
* JDBC escaped numeric functions - JDBC 3.0 C.1
* @throws SQLException
*/
public void testNumericFunctions() throws SQLException
{
escapedFunctions(NUMERIC_FUNCTIONS,
getDMD().getNumericFunctions());
}
/**
* JDBC escaped string functions - JDBC 3.0 C.2
* @throws SQLException
*/
public void testStringFunctions() throws SQLException
{
escapedFunctions(STRING_FUNCTIONS,
getDMD().getStringFunctions());
}
/**
* JDBC escaped date time functions - JDBC 3.0 C.3
* @throws SQLException
*/
public void testTimeDataFunctions() throws SQLException
{
escapedFunctions(TIMEDATE_FUNCTIONS,
getDMD().getTimeDateFunctions());
}
/**
* JDBC escaped system functions - JDBC 3.0 C.4
* @throws SQLException
*/
public void testSystemFunctions() throws SQLException
{
escapedFunctions(SYSTEM_FUNCTIONS,
getDMD().getSystemFunctions());
}
/**
* Check that the list of escaped functions provided by
* the driver is a strict subet of the specified set,
* the list does not contain duplicates, all the functions
* listed can be executed and that if a function is not
* in the list but is specified it cannot be executed.
*/
private void escapedFunctions(String[][] specList, String metaDataList)
throws SQLException
{
boolean[] seenFunction = new boolean[specList.length];
StringTokenizer st = new StringTokenizer(metaDataList, ",");
while (st.hasMoreTokens())
{
String function = st.nextToken();
// find this function in the list
boolean isSpecFunction = false;
for (int f = 0; f < specList.length; f++)
{
String[] specDetails = specList[f];
if (function.equals(specDetails[0]))
{
// Matched spec.
if (seenFunction[f])
fail("Function in list twice: " + function);
seenFunction[f] = true;
isSpecFunction = true;
executeEscaped(specDetails);
break;
}
}
if (!isSpecFunction)
{
fail("Non-JDBC spec function in list: " + function);
}
}
// Now see if any speced functions are not in the metadata list
for (int f = 0; f < specList.length; f++)
{
if (seenFunction[f])
continue;
String[] specDetails = specList[f];
// bug DERBY-723 CHAR maps to wrong function
if ("CHAR".equals(specDetails[0]))
continue;
try {
executeEscaped(specDetails);
fail("function works but not declared in list: " + specDetails[0]);
} catch (SQLException e) {
assertSQLState("42X01", e);
}
}
}
/**
* Test we can execute a function listed as a supported
* JDBC escaped function. We don't care about the actual
* return value, that should be tested elsewhere in
* the specific test of a function.
*/
private void executeEscaped(String[] specDetails)
throws SQLException
{
String sql = "VALUES { fn " + specDetails[0] + "(";
for (int p = 0; p < specDetails.length - 1; p++)
{
if (p != 0)
sql = sql + ", ";
sql = sql + specDetails[p + 1];
}
sql = sql + ") }";
PreparedStatement ps = prepareStatement(sql);
ResultSet rs = ps.executeQuery();
JDBC.assertDrainResults(rs);
rs.close();
ps.close();
}
/**
* Return a list of all valid supported datatypes as Strings
* suitable for use in any SQL statement where a SQL type is
* expected. For variable sixzed types the string will
* have random valid length information. E.g. CHAR(37).
*/
public static List getSQLTypes(Connection conn) throws SQLException
{
List list = new ArrayList();
Random rand = new Random();
ResultSet rs = conn.getMetaData().getTypeInfo();
while (rs.next())
{
String typeName = rs.getString("TYPE_NAME");
String createParams = rs.getString("CREATE_PARAMS");
if (createParams == null) {
// Type name stands by itself.
list.add(typeName);
continue;
}
if (createParams.indexOf("length") != -1)
{
int maxLength = rs.getInt("PRECISION");
// nextInt returns a value between 0 and maxLength-1
int length = rand.nextInt(maxLength) + 1;
int paren = typeName.indexOf('(');
if (paren == -1) {
list.add(typeName + "(" + length + ")");
} else {
StringBuffer sb = new StringBuffer();
sb.append(typeName.substring(0, paren+1));
sb.append(length);
sb.append(typeName.substring(paren+1));
list.add(sb.toString());
}
continue;
}
if (createParams.indexOf("scale") != -1)
{
int maxPrecision = rs.getInt("PRECISION");
StringBuffer sb = new StringBuffer();
int precision = rand.nextInt(maxPrecision) + 1;
sb.append(typeName);
sb.append("(");
sb.append(precision);
// Most DECIMAL usage does have a scale
// but randomly pick some that do not.
if (rand.nextInt(100) < 95) {
sb.append(",");
sb.append(rand.nextInt(precision+1));
}
sb.append(")");
list.add(sb.toString());
continue;
}
if (createParams.indexOf("precision") != -1)
{
list.add(typeName);
continue;
}
fail("unknown how to generate valid type for " + typeName
+ " CREATE_PARAMS=" + createParams);
}
return list;
}
/**
* Given a valid SQL type return the corresponding
* JDBC type identifier from java.sql.Types.
* Will assert if the type is not known
* (in future, currently just return Types.NULL).
*/
public static int getJDBCType(String type)
{
if ("SMALLINT".equals(type))
return Types.SMALLINT;
if ("INTEGER".equals(type) || "INT".equals(type))
return Types.INTEGER;
if ("BIGINT".equals(type))
return Types.BIGINT;
if (type.equals("FLOAT") || type.startsWith("FLOAT("))
return Types.FLOAT;
if (type.equals("REAL"))
return Types.REAL;
if ("DOUBLE".equals(type) || "DOUBLE PRECISION".equals(type))
return Types.DOUBLE;
if ("DATE".equals(type))
return Types.DATE;
if ("TIME".equals(type))
return Types.TIME;
if ("TIMESTAMP".equals(type))
return Types.TIMESTAMP;
if (type.equals("DECIMAL") || type.startsWith("DECIMAL("))
return Types.DECIMAL;
if (type.equals("NUMERIC") || type.startsWith("NUMERIC("))
return Types.NUMERIC;
if (type.endsWith("FOR BIT DATA")) {
if (type.startsWith("CHAR"))
return Types.BINARY;
if (type.startsWith("CHARACTER"))
return Types.BINARY;
if (type.startsWith("VARCHAR"))
return Types.VARBINARY;
if (type.startsWith("CHARACTER VARYING"))
return Types.VARBINARY;
if (type.startsWith("CHAR VARYING"))
return Types.VARBINARY;
}
if ("LONG VARCHAR".equals(type))
return Types.LONGVARCHAR;
if ("LONG VARCHAR FOR BIT DATA".equals(type))
return Types.LONGVARBINARY;
if (type.equals("CHAR") || type.startsWith("CHAR("))
return Types.CHAR;
if (type.equals("CHARACTER") ||
type.startsWith("CHARACTER("))
return Types.CHAR;
if (type.equals("VARCHAR") || type.startsWith("VARCHAR("))
return Types.VARCHAR;
if (type.equals("CHARACTER VARYING") ||
type.startsWith("CHARACTER VARYING("))
return Types.VARCHAR;
if (type.equals("CHAR VARYING") ||
type.startsWith("CHAR VARYING("))
return Types.VARCHAR;
if (type.equals("BLOB") || type.startsWith("BLOB("))
return Types.BLOB;
if (type.equals("BINARY LARGE OBJECT") ||
type.startsWith("BINARY LARGE OBJECT("))
return Types.BLOB;
if (type.equals("CLOB") || type.startsWith("CLOB("))
return Types.CLOB;
if (type.equals("CHARACTER LARGE OBJECT") ||
type.startsWith("CHARACTER LARGE OBJECT("))
return Types.CLOB;
if ("XML".equals(type))
return JDBC.SQLXML;
fail("Unexpected SQL type: " + type);
return Types.NULL;
}
/**
* Given a valid SQL type return the corresponding
* precision/length for this specific value
* if the type is variable, e.g. CHAR(5) will
* return 5, but LONG VARCHAR will return 0.
*/
public static int getPrecision(int jdbcType, String type)
{
switch (jdbcType)
{
case Types.CHAR:
case Types.VARCHAR:
case Types.CLOB:
case Types.BINARY:
case Types.VARBINARY:
case Types.BLOB:
int lp = type.indexOf('(');
int rp = type.indexOf(')');
int precision =
Integer.valueOf(type.substring(lp+1, rp)).intValue();
return precision;
default:
return 0;
}
}
/**
* Execute and check the ODBC variant of getImported/Exported keys, which
* uses the SQLFOREIGNKEYS system procedure to provide the same information
* to ODBC clients. Note that for "correctness" we just compare the results
* to those of the equivalent JDBC calls; this fixture assumes that the
* the JDBC calls return correct results (testing of the JDBC results occurs
* elsewhere, esp. jdbcapi/metadata_test.java).
*/
public void testGetXXportedKeysODBC() throws SQLException, IOException
{
Statement st = createStatement();
// Create some simple tables with primary/foreign keys.
st.execute("create table pkt1 (i int not null, c char(1) not null)");
st.execute("create table pkt2 (i int not null, c char(1) not null)");
st.execute("create table pkt3 (i int not null, c char(1) not null)");
st.execute("alter table pkt1 add constraint pk1 primary key (i)");
st.execute("alter table pkt2 add constraint pk2 primary key (c)");
st.execute("alter table pkt3 add constraint pk3 primary key (i, c)");
st.execute("create table fkt1 (fi int, fc char(1), vc varchar(80))");
st.execute("create table fkt2 (fi int, fc char(1), vc varchar(80))");
st.execute("alter table fkt1 add constraint fk1 foreign key (fi) " +
"references pkt1(i)");
st.execute("alter table fkt1 add constraint fk2 foreign key (fc) " +
"references pkt2(c)");
st.execute("alter table fkt2 add constraint fk3 foreign key (fi, fc) " +
"references pkt3(i, c)");
/* Check for all arguments NULL; SQLFOREIGNKEYS allows this, though
* there is no equivalent in JDBC.
*/
checkODBCKeys(null, null, null, null, null, null);
/* Run equivalent of getImportedKeys(), getExportedKeys(),
* and getCrossReference for each of the primary/foreign
* key pairs.
*/
checkODBCKeys(null, null, null, null, null, "FKT1");
checkODBCKeys(null, null, "PKT1", null, null, null);
checkODBCKeys(null, null, "PKT1", null, null, "FKT1");
checkODBCKeys(null, null, null, null, null, "FKT2");
checkODBCKeys(null, null, "PKT2", null, null, null);
checkODBCKeys(null, null, "PKT2", null, null, "FKT2");
checkODBCKeys(null, null, null, null, null, "FKT3");
checkODBCKeys(null, null, "PKT3", null, null, null);
checkODBCKeys(null, null, "PKT3", null, null, "FKT3");
// Reverse primary and foreign tables.
checkODBCKeys(null, null, "FKT1", null, null, null);
checkODBCKeys(null, null, null, null, null, "PKT3");
checkODBCKeys(null, null, "FKT1", null, null, "PKT1");
checkODBCKeys(null, null, "FKT2", null, null, "PKT2");
checkODBCKeys(null, null, "FKT3", null, null, "PKT3");
// Mix-and-match primary key tables and foreign key tables.
checkODBCKeys(null, null, "PKT1", null, null, "FKT2");
checkODBCKeys(null, null, "PKT1", null, null, "FKT3");
checkODBCKeys(null, null, "PKT2", null, null, "FKT3");
checkODBCKeys(null, null, "FKT1", null, null, "PKT2");
checkODBCKeys(null, null, "FKT1", null, null, "PKT3");
checkODBCKeys(null, null, "FKT2", null, null, "PKT3");
// Cleanup.
st.execute("drop table fkt1");
st.execute("drop table fkt2");
st.execute("drop table pkt1");
st.execute("drop table pkt2");
st.execute("drop table pkt3");
st.close();
}
/**
* Execute a call to the ODBC system procedure "SQLFOREIGNKEYS"
* and verify the results by comparing them with the results of
* an equivalent JDBC call (if one exists).
*/
private void checkODBCKeys(String pCatalog, String pSchema,
String pTable, String fCatalog, String fSchema, String fTable)
throws SQLException, IOException
{
/* To mimic the behavior of the issue which prompted this test
* (DERBY-2758) we only send the "ODBC" option; we do *not*
* explicitly send the "IMPORTEDKEY=1" nor "EXPORTEDKEY=1"
* options, as DB2 Runtime Client does not send those, either.
* This effectively means that the SQLFOREIGNKEYS function
* will always be mapped to getCrossReference() internally.
* Since that worked fine prior to 10.3, we need to preserve
* that behavior if we want to maintina backward compatibility.
*/
CallableStatement cs = prepareCall(
"CALL SYSIBM.SQLFOREIGNKEYS(?, ?, ?, ?, ?, ?, " +
"'DATATYPE=''ODBC''')");
cs.setString(1, pCatalog);
cs.setString(2, pSchema);
cs.setString(3, pTable);
cs.setString(4, fCatalog);
cs.setString(5, fSchema);
cs.setString(6, fTable);
cs.execute();
ResultSet odbcrs = cs.getResultSet();
assertNotNull(odbcrs);
/* Returned ResultSet will have the same shape as
* DatabaseMetaData.getImportedKeys()
*/
checkODBCKeysShape(odbcrs);
/* Expect the contents of JDBC and ODBC metadata to be the same,
* except if both pTable and cTable are null. In that case
* ODBC treats everything as a wildcard (and so effectively
* returns all foreign key columns), while JDBC throws
* an error.
*/
ResultSet dmdrs = null;
if ((pTable != null) && (fTable == null))
dmdrs = getDMD().getExportedKeys(pCatalog, pSchema, pTable);
else if ((pTable == null) && (fTable != null))
dmdrs = getDMD().getImportedKeys(fCatalog, fSchema, fTable);
else if (pTable != null)
{
dmdrs = getDMD().getCrossReference(
pCatalog, pSchema, pTable, fCatalog, fSchema, fTable);
}
else
{
/* Must be the case of pTable and fTable both null. Check
* results for ODBC (one row for each foreign key column)
* and assert error for JDBC.
*/
JDBC.assertFullResultSet(odbcrs,
new String [][] {
{"","APP","PKT1","I","","APP","FKT1","FI",
"1","3","3","FK1","PK1","7"},
{"","APP","PKT2","C","","APP","FKT1","FC",
"1","3","3","FK2","PK2","7"},
{"","APP","PKT3","I","","APP","FKT2","FI",
"1","3","3","FK3","PK3","7"},
{"","APP","PKT3","C","","APP","FKT2","FC",
"2","3","3","FK3","PK3","7"}
});
try {
getDMD().getCrossReference(
pCatalog, pSchema, pTable, fCatalog, fSchema, fTable);
fail("Expected error from call to DMD.getCrossReference() " +
"with NULL primary and foreign key tables.");
} catch (SQLException se) {
/* Looks like embedded and client have different (but similar)
* errors for this...
*/
assertSQLState(usingEmbedded() ? "XJ103" : "XJ110", se);
}
}
/* If both pTable and fTable are null then dmdrs will be null, as
* well. So nothing to compare in that case.
*/
if (dmdrs != null)
{
// Next call closes both results sets as a side effect.
JDBC.assertSameContents(odbcrs, dmdrs);
}
cs.close();
}
/**
* Check the shape of the ResultSet from a call to the ODBC function
* SQLForeignKeys.
*/
private void checkODBCKeysShape(ResultSet rs) throws SQLException
{
assertMetaDataResultSet(rs,
// ODBC and JDBC agree on column names and types.
new String[] {
"PKTABLE_CAT", "PKTABLE_SCHEM", "PKTABLE_NAME", "PKCOLUMN_NAME",
"FKTABLE_CAT", "FKTABLE_SCHEM", "FKTABLE_NAME", "FKCOLUMN_NAME",
"KEY_SEQ", "UPDATE_RULE", "DELETE_RULE", "FK_NAME",
"PK_NAME", "DEFERRABILITY"
},
new int[] {
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.SMALLINT, Types.SMALLINT, Types.SMALLINT, Types.VARCHAR,
Types.VARCHAR, Types.SMALLINT
},
// Nullability comes from ODBC spec, not JDBC.
/* DERBY-2797: Nullability of columns in ODBC's SQLForeignKey
* result set is incorrect. Un-comment the correct boolean array
* when DERBY-2797 has been fixed.
*/
// incorrect
new boolean[] {
true, false, false, false,
true, false, false, false,
true, true, true, false,
false, true
}
// correct
/* new boolean[] {
true, true, false, false,
true, true, false, false,
false, true, true, true,
true, true
} */
);
}
/**
* Test getBestRowIdentifier
* @throws SQLException
*/
public void testGetBestRowIdentifier() throws SQLException
{
Statement st = createStatement();
// First, create the test tables and indexes/keys
// Create 5 tables which have only one best row identifier
st.execute("create table brit1 (i int not null primary key, j int)");
st.execute("create table brit2 (i int not null unique, j int)");
// adding not null unique to j - otherwise brit2 & brit3 would be same.
st.execute("create table brit3 (i int not null unique, " +
"j int not null unique)");
st.execute("create table brit4 (i int, j int)");
st.execute("create unique index brit4i on brit4(i)");
st.execute("create table brit5 (i int, j int)");
// following have more than one best row identifier
st.execute("create table brit6 (i int not null unique, " +
"j int not null primary key)");
// PK preferred to unique index
st.execute("create table brit7 (i int not null, " +
"j int not null primary key)");
st.execute("create unique index brit7i on brit7(i)");
// unique con preferred to unique index
st.execute("create table brit8 (i int not null, " +
"j int not null unique)");
st.execute("create unique index brit8i on brit8(i)");
// non-unique index just ignored
st.execute("create table brit9 (i int, j int)");
st.execute("create index brit9i on brit9(i)");
// fewer cols unique con still ignored over primary key
st.execute("create table brit10 " +
"(i int unique not null , j int not null, primary key (i,j))");
// fewer cols unique index still ignored over primary key
st.execute("create table brit11 (i int not null, j int not null, "
+ "primary key (i,j))");
st.execute("create unique index brit11i on brit11(i)");
// fewer cols unique index still ignored over unique con
st.execute("create table brit12 (i int not null, j int not null, "
+ "unique (i,j))");
st.execute("create unique index brit12i on brit12(i)");
st.execute("create table brit13 (i int not null, j int not null, k "
+ "int, unique (i,j))");
// fewest cols unique con is the one picked of several
st.execute("create table brit14 (i int not null unique, j int not "
+ "null, k int, unique (i,j))");
// fewest cols unique index is the one picked of several
st.execute("create table brit15 (i int not null, j int not null, k int)");
st.execute("create unique index brit15ij on brit15(i,j)");
st.execute("create unique index brit15i on brit15(i)");
st.execute("create table brit16 (i int not null primary key, j int)");
// from old metadata test
// DERBY-3180; if this table gets created here, running the entire test
// twice with defaultSuite runs into into trouble.
// Moving into separate fixture does not have this problem.
st.execute("create table brit17 (i int not null default 10, " +
"s smallint not null, c30 char(30) not null, " +
"vc10 varchar(10) not null default 'asdf', " +
"constraint PRIMKEY primary key(vc10, i), " +
"constraint UNIQUEKEY unique(c30, s), ai bigint " +
"generated always as identity " +
"(start with -10, increment by 2001))");
// Create another unique index on brit17
st.execute("create unique index brit17i on brit17(s, i)");
// Create a non-unique index on brit17
st.execute("create index brit17ij on brit17(s)");
getConnection().setAutoCommit(false);
// except for the last table, the expected results are
// column i, column j, or columns i and j.
String [][] expRSI = {
{"2", "I", "4", "INTEGER", "4", null, "10", "1"}};
String [][] expRSJ = {
{"2", "J", "4", "INTEGER", "4", null, "10", "1"}};
String [][] expRSIJ = {
{"2", "I", "4", "INTEGER", "4", null, "10", "1"},
{"2", "J", "4", "INTEGER", "4", null, "10", "1"}};
// not used unless DERBY-3182 is fixed
// String [][] expRSK =
// {"2", "K", "4", "INTEGER", "4", null, "10", "1"},
boolean [] nullability = {
true, false, true, true, true, true, true, true};
DatabaseMetaData dmd = getConnection().getMetaData();
// result: column i
ResultSet rs = dmd.getBestRowIdentifier(null,"APP","BRIT1",0,true);
verifyBRIResults(rs, expRSI, nullability);
// result: column i
rs = dmd.getBestRowIdentifier(null,"APP","BRIT2",0,true);
verifyBRIResults(rs, expRSI, nullability);
// result: column j
rs = dmd.getBestRowIdentifier(null,"APP","BRIT3",0,true);
verifyBRIResults(rs, expRSJ, nullability);
// result: column i
rs = dmd.getBestRowIdentifier(null,"APP","BRIT4",0,true);
verifyBRIResults(rs, expRSI, nullability);
// result: columns i and j
rs = dmd.getBestRowIdentifier(null,"APP","BRIT5",0,true);
verifyBRIResults(rs, expRSIJ, nullability);
// result: column j
rs = dmd.getBestRowIdentifier(null,"APP","BRIT6",0,true);
verifyBRIResults(rs, expRSJ, nullability);
// result: column j
rs = dmd.getBestRowIdentifier(null,"APP","BRIT7",0,true);
verifyBRIResults(rs, expRSJ, nullability);
// result: column j
rs = dmd.getBestRowIdentifier(null,"APP","BRIT8",0,true);
verifyBRIResults(rs, expRSJ, nullability);
// result: columns i,j
rs = dmd.getBestRowIdentifier(null,"APP","BRIT9",0,true);
verifyBRIResults(rs, expRSIJ, nullability);
// result: columns i,j
rs = dmd.getBestRowIdentifier(null,"APP","BRIT10",0,true);
verifyBRIResults(rs, expRSIJ, nullability);
// result: columns i,j
rs = dmd.getBestRowIdentifier(null,"APP","BRIT11",0,true);
verifyBRIResults(rs, expRSIJ, nullability);
// result: columns i,j
rs = dmd.getBestRowIdentifier(null,"APP","BRIT12",0,true);
verifyBRIResults(rs, expRSIJ, nullability);
// DERBY-3182: we aren't handling nullOk flag correctly we
// just drop nullable cols, we should skip an answer that
// has nullable cols in it instead and look for another one.
// result: columns i, j (WRONG) the correct answer is k:
// the non-null columns of the table
rs = dmd.getBestRowIdentifier(null,"APP","BRIT13",0,false);
verifyBRIResults(rs, expRSIJ, nullability);
// result: columns i
rs = dmd.getBestRowIdentifier(null,"APP","BRIT14",0,true);
verifyBRIResults(rs, expRSI, nullability);
// result: columns i
rs = dmd.getBestRowIdentifier(null,"APP","BRIT15",0,true);
verifyBRIResults(rs, expRSI, nullability);
// we don't do anything with SCOPE except detect bad values
// result: columns i
rs = dmd.getBestRowIdentifier(null,"APP","BRIT16",1,true);
verifyBRIResults(rs, expRSI, nullability);
// result: columns i
rs = dmd.getBestRowIdentifier(null,"APP","BRIT16",2,true);
verifyBRIResults(rs, expRSI, nullability);
// result: no rows
rs = dmd.getBestRowIdentifier(null,"APP","BRIT16",-1,true);
// column nullability is opposite to with scope=1 or 2...DERBY-3181
nullability = new boolean [] {
false, true, false, true, false, false, false, false};
assertBestRowIdentifierMetaDataResultSet(rs, nullability);
JDBC.assertDrainResults(rs, 0);
// result: no rows
rs = dmd.getBestRowIdentifier(null,"APP","BRIT16",3,true);
assertBestRowIdentifierMetaDataResultSet(rs, nullability);
JDBC.assertDrainResults(rs, 0);
// set back nullability
nullability = new boolean[] {
true, false, true, true, true, true, true, true};
rs = dmd.getBestRowIdentifier(null, "APP","BRIT17",0,true);
String [][] expRS = new String [][] {
{"2", "I", "4", "INTEGER", "4", null, "10", "1"},
{"2", "VC10", "12", "VARCHAR", "10", null, null, "1"}
};
verifyBRIResults(rs, expRS, nullability);
// test DERBY-2610 for fun; can't pass in null table name
try {
rs = dmd.getBestRowIdentifier(null,"APP",null,3,true);
} catch (SQLException sqle) {
assertSQLState( "XJ103", sqle);
}
// check on systables
rs = dmd.getBestRowIdentifier(null,"SYS","SYSTABLES",0,true);
expRS = new String [][] {
{"2", "TABLEID", "1", "CHAR", "36", null, null, "1"}
};
verifyBRIResults(rs, expRS, nullability);
getConnection().setAutoCommit(true);
st.execute("drop table brit1");
st.execute("drop table brit2");
st.execute("drop table brit3");
st.execute("drop index brit4i");
st.execute("drop table brit4");
st.execute("drop table brit5");
st.execute("drop table brit6");
st.execute("drop index brit7i");
st.execute("drop table brit7");
st.execute("drop index brit8i");
st.execute("drop table brit8");
st.execute("drop index brit9i");
st.execute("drop table brit9");
st.execute("drop table brit10");
st.execute("drop index brit11i");
st.execute("drop table brit11");
st.execute("drop index brit12i");
st.execute("drop table brit12");
st.execute("drop table brit13");
st.execute("drop table brit14");
st.execute("drop index brit15i");
st.execute("drop index brit15ij");
st.execute("drop table brit15");
st.execute("drop table brit16");
st.execute("drop index brit17i");
st.execute("drop index brit17ij");
st.execute("drop table brit17");
st.close();
}
/**
* helper method for test testGetBestRowIdentifier
* @param rs - Resultset from dmd.getBestRowIdentifier
* @param expRS - bidimensional String array with expected result row(s)
* @param nullability - boolean array holding expected nullability
* values. This needs to be a paramter because of DERBY-3081
* @throws SQLException
*/
public void verifyBRIResults(ResultSet rs, String[][] expRS,
boolean[] nullability) throws SQLException {
assertBestRowIdentifierMetaDataResultSet(rs, nullability);
JDBC.assertFullResultSet(rs, expRS, true);
}
// helper method for testGetBestRowIdentifier
public void assertBestRowIdentifierMetaDataResultSet(
ResultSet rs, boolean[] nullability) throws SQLException {
String[] columnNames = {
"SCOPE", "COLUMN_NAME", "DATA_TYPE", "TYPE_NAME",
"COLUMN_SIZE", "BUFFER_LENGTH", "DECIMAL_DIGITS",
"PSEUDO_COLUMN"};
int[] columnTypes = {
Types.SMALLINT, Types.VARCHAR, Types.INTEGER, Types.VARCHAR,
Types.INTEGER, Types.INTEGER, Types.SMALLINT, Types.SMALLINT};
assertMetaDataResultSet(rs, columnNames, columnTypes, nullability);
}
}
| DERBY-3182 ; test comments re functioning of nullisok flag (5th parameter to
getBestRowIdentifier) were incorrect. Adjusting test.
git-svn-id: 2c06e9c5008124d912b69f0b82df29d4867c0ce2@593931 13f79535-47bb-0310-9956-ffa450edef68
| java/testing/org/apache/derbyTesting/functionTests/tests/jdbcapi/DatabaseMetaDataTest.java | DERBY-3182 ; test comments re functioning of nullisok flag (5th parameter to getBestRowIdentifier) were incorrect. Adjusting test. |
|
Java | bsd-2-clause | 8233cb974f27aa910c3931f0aa6ce56f0d6d0faa | 0 | stelfrich/imagej-ops,gab1one/imagej-ops,imagej/imagej-ops,kephale/imagej-ops |
package imagej.ops.loop;
import imagej.ops.Op;
import org.scijava.plugin.Plugin;
/**
* Default implementation of a {@link AbstractInplaceLoop}
*
* @author Christian Dietz
* @param <I>
* @param <O>
*/
@Plugin(type = Op.class, name = Loop.NAME)
public class DefaultInplaceLoop<I> extends AbstractInplaceLoop<I> {
@Override
public I compute(final I arg) {
for (int i = 0; i < n; i++) {
function.compute(arg, arg);
}
return arg;
}
}
| src/main/java/imagej/ops/loop/DefaultInplaceLoop.java |
package imagej.ops.loop;
import imagej.ops.Op;
import org.scijava.plugin.Plugin;
/**
* Default implementation of a {@link AbstractInplaceLoop}
*
* @author Christian Dietz
* @param <I>
* @param <O>
*/
@Plugin(type = Op.class, name = Loop.NAME)
public class DefaultInplaceLoop<I> extends AbstractInplaceLoop<I> {
@Override
public I compute(final I arg) {
for (int i = 0; i < n; i++) {
function.compute(arg);
}
return arg;
}
}
| DefaultInPlaceLoop: Can handle function
| src/main/java/imagej/ops/loop/DefaultInplaceLoop.java | DefaultInPlaceLoop: Can handle function |
|
Java | bsd-2-clause | d1524275dc7859271003e15ecc0d55fcc172faf1 | 0 | ratan12/Atarashii,AnimeNeko/Atarashii,AnimeNeko/Atarashii,ratan12/Atarashii | package net.somethingdreadful.MAL;
import net.somethingdreadful.MAL.R;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class Home extends FragmentActivity implements ActionBar.TabListener, AnimuFragment.IAnimeFragment {
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide fragments for each of the
* sections. We use a {@link android.support.v4.app.FragmentPagerAdapter} derivative, which will
* keep every loaded fragment in memory. If this becomes too memory intensive, it may be best
* to switch to a {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
HomeSectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
Context context;
PrefManager mPrefManager;
public MALManager mManager;
private boolean init = false;
private boolean upgradeInit = false;
AnimuFragment af;
public boolean instanceExists;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getApplicationContext();
mPrefManager = new PrefManager(context);
init = mPrefManager.getInit();
upgradeInit = mPrefManager.getUpgradeInit();
//The following is state handling code
if (savedInstanceState != null)
{
instanceExists = savedInstanceState.getBoolean("instanceExists", false);
}
else
{
instanceExists = false;
}
if (init == true) {
setContentView(R.layout.activity_home);
// Creates the adapter to return the Animu and Mango fragments
mSectionsPagerAdapter = new HomeSectionsPagerAdapter(
getSupportFragmentManager());
mManager = new MALManager(context);
if (!instanceExists)
{
}
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setPageMargin(32);
// When swiping between different sections, select the corresponding
// tab.
// We can also use ActionBar.Tab#select() to do this if we have a
// reference to the
// Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// Add tabs for the animu and mango lists
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title
// defined by the adapter.
// Also specify this Activity object, which implements the
// TabListener interface, as the
// listener for when this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
else //If the app hasn't been configured, take us to the first run screen to sign in
{
Intent firstRunInit = new Intent(this, FirstTimeInit.class);
firstRunInit.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(firstRunInit);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_home, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch(item.getItemId())
{
case R.id.menu_settings:
startActivity(new Intent (this, Settings.class));
break;
//The following is the code that handles switching the list. It calls the fragment to update, then update the menu by invalidating
case R.id.listType_all:
if (af != null)
{
af.getAnimeRecords(0, false);
invalidateOptionsMenu();
}
break;
case R.id.listType_watching:
if (af != null)
{
af.getAnimeRecords(1, false);
invalidateOptionsMenu();
}
break;
case R.id.listType_completed:
if (af != null)
{
af.getAnimeRecords(2, false);
invalidateOptionsMenu();
}
break;
case R.id.listType_onhold:
if (af != null)
{
af.getAnimeRecords(3, false);
invalidateOptionsMenu();
}
break;
case R.id.listType_dropped:
if (af != null)
{
af.getAnimeRecords(4, false);
invalidateOptionsMenu();
}
break;
case R.id.listType_plantowatch:
if (af != null)
{
af.getAnimeRecords(5, false);
invalidateOptionsMenu();
}
break;
case R.id.forceSync:
if (af != null)
{
af.getAnimeRecords(af.currentList, true);
Toast.makeText(context, R.string.toast_SyncMessage, Toast.LENGTH_LONG).show();
}
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onResume()
{
super.onResume();
if (instanceExists == true)
{
af.getAnimeRecords(af.currentList, false);
}
}
@Override
public void onPause()
{
super.onPause();
instanceExists = true;
}
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public void fragmentReady() {
//Interface implementation for knowing when the dynamically created fragment is finished loading
//We use instantiateItem to return the fragment. Since the fragment IS instantiated, the method returns it.
af = (AnimuFragment) mSectionsPagerAdapter.instantiateItem(mViewPager, 0);
//Logic to check if we have just signed in. If yes, automatically do a sync
if (getIntent().getBooleanExtra("net.somethingdreadful.MAL.firstSync", false))
{
af.getAnimeRecords(af.currentList, true);
getIntent().removeExtra("net.somethingdreadful.MAL.firstSync");
Toast.makeText(context, R.string.toast_SyncMessage, Toast.LENGTH_LONG).show();
}
//Logic to check if we upgraded from the version before the rewrite
if (upgradeInit == false)
{
af.getAnimeRecords(af.currentList, true);
Toast.makeText(context, R.string.toast_SyncMessage, Toast.LENGTH_LONG).show();
mPrefManager.setUpgradeInit(true);
mPrefManager.commitChanges();
}
}
@Override
public void onSaveInstanceState(Bundle state)
{
//This is telling out future selves that we already have some things and not to do them
state.putBoolean("instanceExists", true);
super.onSaveInstanceState(state);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu)
{
if (af != null)
{
//All this is handling the ticks in the switch list menu
switch (af.currentList)
{
case 0:
menu.findItem(R.id.listType_all).setChecked(true);
break;
case 1:
menu.findItem(R.id.listType_watching).setChecked(true);
break;
case 2:
menu.findItem(R.id.listType_completed).setChecked(true);
break;
case 3:
menu.findItem(R.id.listType_onhold).setChecked(true);
break;
case 4:
menu.findItem(R.id.listType_dropped).setChecked(true);
break;
case 5:
menu.findItem(R.id.listType_plantowatch).setChecked(true);
}
}
return true;
}
}
| src/net/somethingdreadful/MAL/Home.java | package net.somethingdreadful.MAL;
import net.somethingdreadful.MAL.R;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class Home extends FragmentActivity implements ActionBar.TabListener, AnimuFragment.IAnimeFragment {
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide fragments for each of the
* sections. We use a {@link android.support.v4.app.FragmentPagerAdapter} derivative, which will
* keep every loaded fragment in memory. If this becomes too memory intensive, it may be best
* to switch to a {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
HomeSectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
Context context;
PrefManager mPrefManager;
public MALManager mManager;
private boolean init = false;
private boolean upgradeInit = false;
AnimuFragment af;
public boolean instanceExists;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getApplicationContext();
mPrefManager = new PrefManager(context);
init = mPrefManager.getInit();
upgradeInit = mPrefManager.getUpgradeInit();
//The following is state handling code
if (savedInstanceState != null)
{
instanceExists = savedInstanceState.getBoolean("instanceExists", false);
}
else
{
instanceExists = false;
}
if (init == true) {
setContentView(R.layout.activity_home);
// Creates the adapter to return the Animu and Mango fragments
mSectionsPagerAdapter = new HomeSectionsPagerAdapter(
getSupportFragmentManager());
mManager = new MALManager(context);
if (!instanceExists)
{
}
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setPageMargin(32);
// When swiping between different sections, select the corresponding
// tab.
// We can also use ActionBar.Tab#select() to do this if we have a
// reference to the
// Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// Add tabs for the animu and mango lists
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title
// defined by the adapter.
// Also specify this Activity object, which implements the
// TabListener interface, as the
// listener for when this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
else //If the app hasn't been configured, take us to the first run screen to sign in
{
Intent firstRunInit = new Intent(this, FirstTimeInit.class);
firstRunInit.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(firstRunInit);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_home, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch(item.getItemId())
{
case R.id.menu_settings:
startActivity(new Intent (this, Settings.class));
break;
//The following is the code that handles switching the list. It calls the fragment to update, then update the menu by invalidating
case R.id.listType_all:
if (af != null)
{
af.getAnimeRecords(0, false);
invalidateOptionsMenu();
}
break;
case R.id.listType_watching:
if (af != null)
{
af.getAnimeRecords(1, false);
invalidateOptionsMenu();
}
break;
case R.id.listType_completed:
if (af != null)
{
af.getAnimeRecords(2, false);
invalidateOptionsMenu();
}
break;
case R.id.listType_onhold:
if (af != null)
{
af.getAnimeRecords(3, false);
invalidateOptionsMenu();
}
break;
case R.id.listType_dropped:
if (af != null)
{
af.getAnimeRecords(4, false);
invalidateOptionsMenu();
}
break;
case R.id.listType_plantowatch:
if (af != null)
{
af.getAnimeRecords(5, false);
invalidateOptionsMenu();
}
break;
case R.id.forceSync:
if (af != null)
{
af.getAnimeRecords(af.currentList, true);
Toast.makeText(context, R.string.toast_SyncMessage, Toast.LENGTH_LONG).show();
}
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onResume()
{
super.onResume();
if (instanceExists == true)
{
af.getAnimeRecords(af.currentList, false);
}
}
@Override
public void onPause()
{
super.onPause();
instanceExists = true;
}
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public void fragmentReady() {
//Interface implementation for knowing when the dynamically created fragment is finished loading
//We use instantiateItem to return the fragment. Since the fragment IS instantiated, the method returns it.
af = (AnimuFragment) mSectionsPagerAdapter.instantiateItem(mViewPager, 0);
//Logic to check if we have just signed in. If yes, automatically do a sync
if (getIntent().getBooleanExtra("net.somethingdreadful.MAL.firstSync", false))
{
af.getAnimeRecords(af.currentList, true);
getIntent().removeExtra("net.somethingdreadful.MAL.firstSync");
Toast.makeText(context, R.string.toast_SyncMessage, Toast.LENGTH_LONG).show();
}
//Logic to check if we upgraded from the version before the rewrite
if (upgradeInit == false)
{
af.getAnimeRecords(af.currentList, true);
getIntent().removeExtra("net.somethingdreadful.MAL.firstSync");
Toast.makeText(context, R.string.toast_SyncMessage, Toast.LENGTH_LONG).show();
mPrefManager.setUpgradeInit(true);
mPrefManager.commitChanges();
}
}
@Override
public void onSaveInstanceState(Bundle state)
{
//This is telling out future selves that we already have some things and not to do them
state.putBoolean("instanceExists", true);
super.onSaveInstanceState(state);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu)
{
if (af != null)
{
//All this is handling the ticks in the switch list menu
switch (af.currentList)
{
case 0:
menu.findItem(R.id.listType_all).setChecked(true);
break;
case 1:
menu.findItem(R.id.listType_watching).setChecked(true);
break;
case 2:
menu.findItem(R.id.listType_completed).setChecked(true);
break;
case 3:
menu.findItem(R.id.listType_onhold).setChecked(true);
break;
case 4:
menu.findItem(R.id.listType_dropped).setChecked(true);
break;
case 5:
menu.findItem(R.id.listType_plantowatch).setChecked(true);
}
}
return true;
}
}
| cleanup | src/net/somethingdreadful/MAL/Home.java | cleanup |
|
Java | bsd-3-clause | 9cf79a6b21afe7e7a047e2e2ff44c7b66fb16a2b | 0 | bluerover/6lbr,MohamedSeliem/contiki,MohamedSeliem/contiki,bluerover/6lbr,MohamedSeliem/contiki,arurke/contiki,arurke/contiki,bluerover/6lbr,MohamedSeliem/contiki,MohamedSeliem/contiki,arurke/contiki,MohamedSeliem/contiki,bluerover/6lbr,bluerover/6lbr,bluerover/6lbr,arurke/contiki,arurke/contiki,bluerover/6lbr,arurke/contiki,MohamedSeliem/contiki,arurke/contiki | /*
* Copyright (c) 2007, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: MspMoteType.java,v 1.12 2008/10/02 21:23:03 fros4943 Exp $
*/
package se.sics.cooja.mspmote;
import java.awt.*;
import java.awt.Dialog.ModalityType;
import java.awt.event.*;
import java.io.*;
import java.util.Collection;
import java.util.Vector;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.filechooser.FileFilter;
import org.apache.log4j.Logger;
import org.jdom.Element;
import se.sics.cooja.*;
import se.sics.cooja.dialogs.MessageList;
@ClassDescription("Msp Mote Type")
public abstract class MspMoteType implements MoteType {
private static Logger logger = Logger.getLogger(MspMoteType.class);
private static final String firmwareFileExtension = ".firmware";
/* Convenience: Preselecting last used directory */
protected static File lastParentDirectory = null;
private String identifier = null;
private String description = null;
/* If source file is defined, (re)compilation is performed */
private File fileELF = null;
private File fileSource = null;
private String compileCommand = null;
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
/**
* Set ELF file.
*
* @param file
* ELF file
*/
public void setELFFile(File file) {
this.fileELF = file;
}
/**
* Set compile command.
*
* @param command
* Compile command
*/
public void setCompileCommand(String command) {
this.compileCommand = command;
}
/**
* @return ELF file
*/
public File getELFFile() {
return fileELF;
}
/**
* @return Compile command
*/
public String getCompileCommand() {
return compileCommand;
}
/**
* Set source file
*
* @param file Source file
*/
public void setSourceFile(File file) {
fileSource = file;
}
/**
* @return Source file
*/
public File getSourceFile() {
return fileSource;
}
public final Mote generateMote(Simulation simulation) {
MspMote mote = createMote(simulation);
mote.initMote();
return mote;
}
protected abstract MspMote createMote(Simulation simulation);
/**
* Configures and initialized Msp mote types.
*
* @param parentContainer Graphical parent container
* @param simulation Current simulation
* @param visAvailable Enable graphical interfaces and user input
* @param target Contiki target platform name
* @param targetNice Nicer representation of target
* @return True is successful
* @throws MoteTypeCreationException Mote type creation failed
*/
protected boolean configureAndInitMspType(Container parentContainer, Simulation simulation,
boolean visAvailable, String target, String targetNice)
throws MoteTypeCreationException {
boolean compileFromSource = false;
if (getIdentifier() == null && !visAvailable) {
throw new MoteTypeCreationException("No identifier");
}
/* Generate unique identifier */
if (getIdentifier() == null) {
int counter = 0;
boolean identifierOK = false;
while (!identifierOK) {
counter++;
setIdentifier(target + counter);
identifierOK = true;
// Check if identifier is already used by some other type
for (MoteType existingMoteType : simulation.getMoteTypes()) {
if (existingMoteType != this
&& existingMoteType.getIdentifier().equals(getIdentifier())) {
identifierOK = false;
break;
}
}
}
if (getDescription() == null) {
setDescription(targetNice + " Mote Type #" + counter);
}
/* Let user choose whether to compile or load existing binaries */
Object[] options = { "Select", "Compile" };
String question = targetNice + " mote type depends on an ELF file.\n"
+ "If you want to use an already existing file, click 'Select'.\n\n"
+ "To compile this file from source, click 'Compile'";
String title = "Select or compile " + targetNice + " firmware";
if (GUI.isVisualizedInApplet()) {
compileFromSource = false;
} else {
int answer = JOptionPane.showOptionDialog(GUI.getTopParentContainer(),
question, title, JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
if (answer != JOptionPane.YES_OPTION && answer != JOptionPane.NO_OPTION) {
return false;
}
compileFromSource = answer != JOptionPane.YES_OPTION;
}
}
/* Description */
if (getDescription() == null) {
setDescription(targetNice + " Mote Type #" + getIdentifier());
}
if (getSourceFile() != null) {
compileFromSource = true;
}
if (compileFromSource) {
MspELFCompiler compiler = new MspELFCompiler(target);
compiler.setCompileCommand(compileCommand);
if (visAvailable) {
boolean success = compiler.showDialog(GUI.getTopParentContainer(), this);
if (success) {
setSourceFile(compiler.getSourceFile());
setELFFile(compiler.getOutputFile());
setCompileCommand(compiler.getLastCompileCommand());
return true;
} else {
return false;
}
} else {
MessageList compilationOutput = new MessageList();
try {
compiler.compileFirmware(getSourceFile(), null, null, compilationOutput,
true);
} catch (Exception e) {
MoteTypeCreationException newException = new MoteTypeCreationException(
"Mote type creation failed: " + e.getMessage());
newException = (MoteTypeCreationException) newException.initCause(e);
newException.setCompilationOutput(compilationOutput);
if (compilationOutput != null) {
try { Thread.sleep(500); } catch (InterruptedException ignore) { }
ListModel tmp = compilationOutput.getModel();
for (int i=tmp.getSize()-5; i < tmp.getSize(); i++) {
if (i < 0) {
continue;
}
logger.fatal(">> " + tmp.getElementAt(i));
}
}
logger.fatal("Compilation error: " + e.getMessage());
throw newException;
}
setSourceFile(compiler.getSourceFile());
setELFFile(compiler.getOutputFile());
setCompileCommand(compiler.getLastCompileCommand());
return true;
}
}
if (GUI.isVisualizedInApplet()) {
return true;
}
// Check dependency files
if (getELFFile() == null || !getELFFile().exists()) {
if (!visAvailable) {
throw new MoteTypeCreationException("ELF file does not exist: " + getELFFile());
}
JFileChooser fc = new JFileChooser();
// Select previous directory
if (lastParentDirectory != null) {
fc.setCurrentDirectory(lastParentDirectory);
} else {
fc.setCurrentDirectory(new java.io.File(GUI
.getExternalToolsSetting("PATH_CONTIKI")));
}
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.addChoosableFileFilter(new FileFilter() {
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
}
String filename = f.getName();
if (filename != null) {
if (filename.endsWith(firmwareFileExtension)) {
return true;
}
}
return false;
}
public String getDescription() {
return "ELF file";
}
});
fc.setDialogTitle("Select ELF file");
if (fc.showOpenDialog(parentContainer) == JFileChooser.APPROVE_OPTION) {
File selectedFile = fc.getSelectedFile();
if (!selectedFile.exists()) {
logger.fatal("Selected file \"" + selectedFile + "\" does not exist");
return false;
}
if (!selectedFile.getName().endsWith(firmwareFileExtension)) {
logger.fatal("Selected file \"" + selectedFile + "\" does not end with " + firmwareFileExtension);
return false;
}
setELFFile(fc.getSelectedFile());
} else {
return false;
}
}
return true;
}
protected static class MspELFCompiler {
private static int LABEL_WIDTH = 170;
private static int LABEL_HEIGHT = 15;
private JButton cancelButton = new JButton("Cancel");
private JButton compileButton = new JButton("Compile");
private JButton createButton = new JButton("Create");
private JTextField sourceTextField = new JTextField();
private JTextField compileCommandTextField = new JTextField();
// private JFormattedTextField nodeIDTextField;
// private NumberFormat integerFormat = NumberFormat.getIntegerInstance();
private String lastCompileCommand = null;
private File sourceFile = null;
private File ELFFile = null;
private String target;
private JDialog myDialog;
private String customizedCompileCommand = null;
private Process compileProcess;
static enum DialogState {
NO_SOURCE, SELECTED_SOURCE, IS_COMPILING, COMPILED_SOURCE
}
public MspELFCompiler(String target) {
this.target = target;
}
private String getCompileCommand(String filename) {
if (customizedCompileCommand != null) {
return customizedCompileCommand;
}
return GUI.getExternalToolsSetting("PATH_MAKE") + " " + filename + firmwareFileExtension + " TARGET=" + target;
}
private void setCompileCommand(String command) {
if (command == null || command.isEmpty()) {
customizedCompileCommand = null;
return;
}
customizedCompileCommand = command;
}
/**
* @return Compiler output
*/
public File getOutputFile() {
return ELFFile;
}
public File getSourceFile() {
return sourceFile;
}
public String getLastCompileCommand() {
return lastCompileCommand;
}
private void updateDialog(DialogState dialogState) {
switch (dialogState) {
case NO_SOURCE:
compileButton.setEnabled(false);
createButton.setEnabled(false);
compileCommandTextField.setText("");
break;
case IS_COMPILING:
compileButton.setEnabled(false);
createButton.setEnabled(false);
break;
case SELECTED_SOURCE:
File sourceFile = new File(sourceTextField.getText());
if (!sourceFile.exists()) {
updateDialog(DialogState.NO_SOURCE);
break;
}
File parentDirectory = sourceFile.getParentFile();
if (!parentDirectory.exists()) {
updateDialog(DialogState.NO_SOURCE);
break;
}
if (!sourceFile.getName().endsWith(".c")) {
updateDialog(DialogState.NO_SOURCE);
break;
}
String name = sourceFile.getName().substring(0,
sourceFile.getName().length() - 2);
compileButton.setEnabled(true);
createButton.setEnabled(false);
compileCommandTextField.setText(getCompileCommand(name));
compileButton.requestFocusInWindow();
break;
case COMPILED_SOURCE:
compileButton.setEnabled(true);
createButton.setEnabled(true);
createButton.requestFocusInWindow();
myDialog.getRootPane().setDefaultButton(createButton);
break;
default:
break;
}
}
protected void compileFirmware(final File sourceFile,
final Action successAction, final Action failAction,
final MessageList compilationOutput, boolean synchronous) throws Exception {
final File parentDirectory = sourceFile.getParentFile();
final String filenameNoExtension = sourceFile.getName().substring(0,
sourceFile.getName().length() - 2);
final String command = getCompileCommand(filenameNoExtension);
logger.info("-- Compiling MSP430 Firmware --");
logger.info("Compilation command: " + command);
compilationOutput.clearMessages();
try {
String[] cmd = command.split(" ");
compileProcess = Runtime.getRuntime().exec(cmd, null,
parentDirectory);
final BufferedReader processNormal = new BufferedReader(
new InputStreamReader(compileProcess.getInputStream()));
final BufferedReader processError = new BufferedReader(
new InputStreamReader(compileProcess.getErrorStream()));
final File ELFFile = new File(parentDirectory, filenameNoExtension + firmwareFileExtension);
if (ELFFile.exists()) {
ELFFile.delete();
if (ELFFile.exists()) {
compilationOutput.addMessage("Error when deleting old " + ELFFile.getName(), MessageList.ERROR);
if (failAction != null) {
failAction.actionPerformed(null);
}
throw new MoteTypeCreationException("Error when deleting old "
+ ELFFile.getName());
}
}
Thread readInput = new Thread(new Runnable() {
public void run() {
try {
String readLine;
while ((readLine = processNormal.readLine()) != null) {
compilationOutput.addMessage(readLine, MessageList.NORMAL);
}
} catch (IOException e) {
logger.warn("Error while reading from process");
}
}
}, "read input stream thread");
Thread readError = new Thread(new Runnable() {
public void run() {
try {
String readLine;
while ((readLine = processError.readLine()) != null) {
compilationOutput.addMessage(readLine, MessageList.ERROR);
}
} catch (IOException e) {
logger.warn("Error while reading from process");
}
}
}, "read input stream thread");
final MoteTypeCreationException syncException =
new MoteTypeCreationException("");
Thread handleCompilationResultThread = new Thread(new Runnable() {
public void run() {
/* Wait for compilation to end */
try {
compileProcess.waitFor();
} catch (Exception e) {
compilationOutput.addMessage(e.getMessage(), MessageList.ERROR);
syncException.setCompilationOutput(new MessageList());
syncException.fillInStackTrace();
return;
}
/* Check return value */
if (compileProcess.exitValue() != 0) {
compilationOutput.addMessage("Process returned error code " + compileProcess.exitValue(), MessageList.ERROR);
if (failAction != null) {
failAction.actionPerformed(null);
}
syncException.setCompilationOutput(new MessageList());
syncException.fillInStackTrace();
return;
}
if (!ELFFile.exists()) {
compilationOutput.addMessage("Can't locate output file " + ELFFile, MessageList.ERROR);
if (failAction != null) {
failAction.actionPerformed(null);
}
syncException.setCompilationOutput(new MessageList());
syncException.fillInStackTrace();
return;
}
compilationOutput.addMessage("", MessageList.NORMAL);
compilationOutput.addMessage("Compilation succeded", MessageList.NORMAL);
MspELFCompiler.this.lastCompileCommand = command;
MspELFCompiler.this.sourceFile = sourceFile;
MspELFCompiler.this.ELFFile = ELFFile;
if (successAction != null) {
successAction.actionPerformed(null);
}
}
}, "handle compilation results");
readInput.start();
readError.start();
handleCompilationResultThread.start();
if (synchronous) {
try {
handleCompilationResultThread.join();
} catch (Exception e) {
throw (MoteTypeCreationException) new MoteTypeCreationException(
"Compilation error: " + e.getMessage()).initCause(e);
}
/* Detect error manually */
if (syncException.hasCompilationOutput()) {
throw (MoteTypeCreationException) new MoteTypeCreationException(
"Bad return value").initCause(syncException);
}
}
} catch (IOException ex) {
if (failAction != null) {
failAction.actionPerformed(null);
}
throw (MoteTypeCreationException) new MoteTypeCreationException(
"Compilation error: " + ex.getMessage()).initCause(ex);
}
}
public boolean showDialog(Container parentContainer, final MspMoteType moteType) {
if (parentContainer instanceof Window) {
myDialog = new JDialog((Window)parentContainer, "Compile ELF file", ModalityType.APPLICATION_MODAL);
} else if (parentContainer instanceof Dialog) {
myDialog = new JDialog((Dialog)parentContainer, "Compile ELF file", ModalityType.APPLICATION_MODAL);
} else if (parentContainer instanceof Frame) {
myDialog = new JDialog((Frame)parentContainer, "Compile ELF file", ModalityType.APPLICATION_MODAL);
} else {
logger.fatal("Unknown parent container type: " + parentContainer);
return false;
}
final MessageList taskOutput = new MessageList();
// BOTTOM BUTTON PART
Box buttonBox = Box.createHorizontalBox();
buttonBox.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
buttonBox.add(Box.createHorizontalGlue());
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sourceFile = null;
ELFFile = null;
if (compileProcess != null) {
compileProcess.destroy();
}
myDialog.dispose();
}
});
compileButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final File selectedSourceFile = new File(sourceTextField.getText());
/* Strip .c file extension */
final String filenameNoExtension = selectedSourceFile.getName()
.substring(0, selectedSourceFile.getName().length() - 2);
Action successAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
updateDialog(DialogState.COMPILED_SOURCE);
File parentFile = selectedSourceFile.getParentFile();
sourceFile = selectedSourceFile;
ELFFile = new File(parentFile, filenameNoExtension + firmwareFileExtension);
}
};
Action failAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
updateDialog(DialogState.SELECTED_SOURCE);
}
};
updateDialog(DialogState.IS_COMPILING);
try {
compileFirmware(new File(sourceTextField.getText()), successAction,
failAction, taskOutput, false);
} catch (Exception e2) {
}
}
});
createButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
myDialog.dispose();
}
});
buttonBox.add(cancelButton);
buttonBox.add(Box.createHorizontalStrut(5));
buttonBox.add(compileButton);
buttonBox.add(Box.createHorizontalStrut(5));
buttonBox.add(createButton);
// MAIN DIALOG CONTENTS
Box horizBox;
JLabel label;
Box vertBox = Box.createVerticalBox();
// Source
horizBox = Box.createHorizontalBox();
horizBox.setMaximumSize(new Dimension(Integer.MAX_VALUE, LABEL_HEIGHT));
horizBox.setAlignmentX(Component.LEFT_ALIGNMENT);
label = new JLabel("Contiki process sourcefile");
label.setPreferredSize(new Dimension(LABEL_WIDTH, LABEL_HEIGHT));
sourceTextField.setText("");
if (moteType.getSourceFile() != null) {
sourceTextField.setText(moteType.getSourceFile().getAbsolutePath());
}
sourceTextField.setColumns(25);
sourceTextField.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
updateDialog(DialogState.SELECTED_SOURCE);
}
public void changedUpdate(DocumentEvent e) {
updateDialog(DialogState.SELECTED_SOURCE);
}
public void removeUpdate(DocumentEvent e) {
updateDialog(DialogState.SELECTED_SOURCE);
}
});
JButton browseButton = new JButton("Browse");
browseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
updateDialog(DialogState.NO_SOURCE);
JFileChooser fc = new JFileChooser();
if (lastParentDirectory != null) {
fc.setCurrentDirectory(lastParentDirectory);
} else {
fc.setCurrentDirectory(new java.io.File(GUI
.getExternalToolsSetting("PATH_CONTIKI")));
}
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.addChoosableFileFilter(new FileFilter() {
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
}
String filename = f.getName();
if (filename != null) {
if (filename.endsWith(".c")) {
return true;
}
}
return false;
}
public String getDescription() {
return "Contiki process source";
}
});
fc.setDialogTitle("Select Contiki process source");
if (fc.showOpenDialog(myDialog) == JFileChooser.APPROVE_OPTION) {
lastParentDirectory = null;
sourceTextField.setText("");
File selectedFile = fc.getSelectedFile();
if (!selectedFile.exists()) {
return;
}
if (!selectedFile.getName().endsWith(".c")) {
return;
}
lastParentDirectory = fc.getSelectedFile().getParentFile();
sourceTextField.setText(fc.getSelectedFile().getAbsolutePath());
updateDialog(DialogState.SELECTED_SOURCE);
}
}
});
horizBox.add(label);
horizBox.add(Box.createHorizontalStrut(10));
horizBox.add(sourceTextField);
horizBox.add(browseButton);
vertBox.add(horizBox);
vertBox.add(Box.createRigidArea(new Dimension(0, 5)));
// Node ID
/*
* horizBox = Box.createHorizontalBox(); horizBox.setMaximumSize(new
* Dimension(Integer.MAX_VALUE,LABEL_HEIGHT));
* horizBox.setAlignmentX(Component.LEFT_ALIGNMENT); label = new
* JLabel("Node ID (0=EEPROM)"); label.setPreferredSize(new
* Dimension(LABEL_WIDTH,LABEL_HEIGHT));
*
* nodeIDTextField = new JFormattedTextField(integerFormat);
* nodeIDTextField.setValue(new Integer(0));
* nodeIDTextField.setColumns(25);
* nodeIDTextField.addPropertyChangeListener("value", new
* PropertyChangeListener() { public void
* propertyChange(PropertyChangeEvent e) {
* updateDialog(DialogState.SELECTED_SOURCE); } });
*
* horizBox.add(label); horizBox.add(Box.createHorizontalStrut(150));
* horizBox.add(nodeIDTextField);
*
* vertBox.add(horizBox); vertBox.add(Box.createRigidArea(new
* Dimension(0,5)));
*/
// Compile command
horizBox = Box.createHorizontalBox();
horizBox.setMaximumSize(new Dimension(Integer.MAX_VALUE, LABEL_HEIGHT));
horizBox.setAlignmentX(Component.LEFT_ALIGNMENT);
label = new JLabel("Compile command");
label.setPreferredSize(new Dimension(LABEL_WIDTH, LABEL_HEIGHT));
compileCommandTextField.setText("");
compileCommandTextField.setColumns(25);
compileCommandTextField.setEditable(true);
compileCommandTextField.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
setCompileCommand(compileCommandTextField.getText());
}
public void changedUpdate(DocumentEvent e) {
setCompileCommand(compileCommandTextField.getText());
}
public void removeUpdate(DocumentEvent e) {
setCompileCommand(compileCommandTextField.getText());
}
});
horizBox.add(label);
horizBox.add(Box.createHorizontalStrut(10));
horizBox.add(compileCommandTextField);
vertBox.add(horizBox);
vertBox.add(Box.createRigidArea(new Dimension(0, 5)));
vertBox.add(Box.createRigidArea(new Dimension(0, 5)));
vertBox.add(new JLabel("Compilation output:"));
vertBox.add(Box.createRigidArea(new Dimension(0, 5)));
vertBox.add(new JScrollPane(taskOutput));
vertBox.add(Box.createRigidArea(new Dimension(0, 5)));
vertBox.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
Container contentPane = myDialog.getContentPane();
contentPane.add(vertBox, BorderLayout.CENTER);
contentPane.add(buttonBox, BorderLayout.SOUTH);
myDialog.pack();
myDialog.setLocationRelativeTo(parentContainer);
myDialog.getRootPane().setDefaultButton(compileButton);
// Dispose on escape key
InputMap inputMap = myDialog.getRootPane().getInputMap(
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false),
"dispose");
AbstractAction cancelAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
cancelButton.doClick();
}
};
myDialog.getRootPane().getActionMap().put("dispose", cancelAction);
myDialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
myDialog.addWindowListener(new WindowListener() {
public void windowDeactivated(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowOpened(WindowEvent e) {
}
public void windowClosed(WindowEvent e) {
}
public void windowActivated(WindowEvent e) {
}
public void windowClosing(WindowEvent e) {
cancelButton.doClick();
}
});
updateDialog(DialogState.NO_SOURCE);
if (moteType.getSourceFile() != null) {
updateDialog(DialogState.SELECTED_SOURCE);
if (customizedCompileCommand != null && !customizedCompileCommand.equals("")) {
compileCommandTextField.setText(customizedCompileCommand);
}
compileButton.requestFocus();
}
myDialog.setVisible(true);
return sourceFile != null;
}
}
public JPanel getTypeVisualizer() {
JPanel panel = new JPanel();
JLabel label = new JLabel();
JPanel smallPane;
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
// Identifier
smallPane = new JPanel(new BorderLayout());
label = new JLabel("Identifier");
smallPane.add(BorderLayout.WEST, label);
label = new JLabel(getIdentifier());
smallPane.add(BorderLayout.EAST, label);
panel.add(smallPane);
// Description
smallPane = new JPanel(new BorderLayout());
label = new JLabel("Description");
smallPane.add(BorderLayout.WEST, label);
label = new JLabel(getDescription());
smallPane.add(BorderLayout.EAST, label);
panel.add(smallPane);
// ELF Hex file
smallPane = new JPanel(new BorderLayout());
label = new JLabel("ELF file");
smallPane.add(BorderLayout.WEST, label);
label = new JLabel(getELFFile().getName());
label.setToolTipText(getELFFile().getPath());
smallPane.add(BorderLayout.EAST, label);
panel.add(smallPane);
// Source file
smallPane = new JPanel(new BorderLayout());
label = new JLabel("Source file");
smallPane.add(BorderLayout.WEST, label);
logger.debug(">>>> " + getSourceFile());
if (getSourceFile() != null) {
label = new JLabel(getSourceFile().getName());
label.setToolTipText(getSourceFile().getPath());
} else {
label = new JLabel("[not specified]");
}
smallPane.add(BorderLayout.EAST, label);
panel.add(smallPane);
// Icon (if available)
if (!GUI.isVisualizedInApplet()) {
Icon moteTypeIcon = getMoteTypeIcon();
if (moteTypeIcon != null) {
smallPane = new JPanel(new BorderLayout());
label = new JLabel(moteTypeIcon);
smallPane.add(BorderLayout.CENTER, label);
panel.add(smallPane);
}
} else {
smallPane = new JPanel(new BorderLayout());
label = new JLabel("No icon available in applet mode");
smallPane.add(BorderLayout.CENTER, label);
panel.add(smallPane);
}
panel.add(Box.createRigidArea(new Dimension(0, 5)));
return panel;
}
public abstract Icon getMoteTypeIcon();
public ProjectConfig getConfig() {
logger.warn("Msp mote type project config not implemented");
return null;
}
public Collection<Element> getConfigXML() {
Vector<Element> config = new Vector<Element>();
Element element;
// Identifier
element = new Element("identifier");
element.setText(getIdentifier());
config.add(element);
// Description
element = new Element("description");
element.setText(getDescription());
config.add(element);
// Source file
if (fileSource != null) {
element = new Element("source");
fileSource = GUI.stripAbsoluteContikiPath(fileSource);
element.setText(fileSource.getPath().replaceAll("\\\\", "/"));
config.add(element);
element = new Element("command");
element.setText(compileCommand);
config.add(element);
} else {
// ELF file
element = new Element("elf");
fileELF = GUI.stripAbsoluteContikiPath(fileELF);
element.setText(fileELF.getPath().replaceAll("\\\\", "/"));
config.add(element);
}
return config;
}
public boolean setConfigXML(Simulation simulation,
Collection<Element> configXML, boolean visAvailable)
throws MoteTypeCreationException {
for (Element element : configXML) {
String name = element.getName();
if (name.equals("identifier")) {
identifier = element.getText();
} else if (name.equals("description")) {
description = element.getText();
} else if (name.equals("source")) {
fileSource = new File(element.getText());
} else if (name.equals("command")) {
compileCommand = element.getText();
} else if (name.equals("elf")) {
fileELF = new File(element.getText());
} else {
logger.fatal("Unrecognized entry in loaded configuration: " + name);
throw new MoteTypeCreationException(
"Unrecognized entry in loaded configuration: " + name);
}
}
return configureAndInit(GUI.getTopParentContainer(), simulation, visAvailable);
}
}
| tools/cooja/apps/mspsim/src/se/sics/cooja/mspmote/MspMoteType.java | /*
* Copyright (c) 2007, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: MspMoteType.java,v 1.11 2008/09/20 09:16:28 fros4943 Exp $
*/
package se.sics.cooja.mspmote;
import java.awt.*;
import java.awt.Dialog.ModalityType;
import java.awt.event.*;
import java.io.*;
import java.util.Collection;
import java.util.Vector;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.filechooser.FileFilter;
import org.apache.log4j.Logger;
import org.jdom.Element;
import se.sics.cooja.*;
import se.sics.cooja.dialogs.MessageList;
@ClassDescription("Msp Mote Type")
public abstract class MspMoteType implements MoteType {
private static Logger logger = Logger.getLogger(MspMoteType.class);
private static final String firmwareFileExtension = ".firmware";
/* Convenience: Preselecting last used directory */
protected static File lastParentDirectory = null;
private String identifier = null;
private String description = null;
/* If source file is defined, (re)compilation is performed */
private File fileELF = null;
private File fileSource = null;
private String compileCommand = null;
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
/**
* Set ELF file.
*
* @param file
* ELF file
*/
public void setELFFile(File file) {
this.fileELF = file;
}
/**
* Set compile command.
*
* @param command
* Compile command
*/
public void setCompileCommand(String command) {
this.compileCommand = command;
}
/**
* @return ELF file
*/
public File getELFFile() {
return fileELF;
}
/**
* @return Compile command
*/
public String getCompileCommand() {
return compileCommand;
}
/**
* Set source file
*
* @param file Source file
*/
public void setSourceFile(File file) {
fileSource = file;
}
/**
* @return Source file
*/
public File getSourceFile() {
return fileSource;
}
public final Mote generateMote(Simulation simulation) {
MspMote mote = createMote(simulation);
mote.initMote();
return mote;
}
protected abstract MspMote createMote(Simulation simulation);
/**
* Configures and initialized Msp mote types.
*
* @param parentContainer Graphical parent container
* @param simulation Current simulation
* @param visAvailable Enable graphical interfaces and user input
* @param target Contiki target platform name
* @param targetNice Nicer representation of target
* @return True is successful
* @throws MoteTypeCreationException Mote type creation failed
*/
protected boolean configureAndInitMspType(Container parentContainer, Simulation simulation,
boolean visAvailable, String target, String targetNice)
throws MoteTypeCreationException {
boolean compileFromSource = false;
if (getIdentifier() == null && !visAvailable) {
throw new MoteTypeCreationException("No identifier");
}
/* Generate unique identifier */
if (getIdentifier() == null) {
int counter = 0;
boolean identifierOK = false;
while (!identifierOK) {
counter++;
setIdentifier(target + counter);
identifierOK = true;
// Check if identifier is already used by some other type
for (MoteType existingMoteType : simulation.getMoteTypes()) {
if (existingMoteType != this
&& existingMoteType.getIdentifier().equals(getIdentifier())) {
identifierOK = false;
break;
}
}
}
if (getDescription() == null) {
setDescription(targetNice + " Mote Type #" + counter);
}
/* Let user choose whether to compile or load existing binaries */
Object[] options = { "Select", "Compile" };
String question = targetNice + " mote type depends on an ELF file.\n"
+ "If you want to use an already existing file, click 'Select'.\n\n"
+ "To compile this file from source, click 'Compile'";
String title = "Select or compile " + targetNice + " firmware";
if (GUI.isVisualizedInApplet()) {
compileFromSource = false;
} else {
int answer = JOptionPane.showOptionDialog(GUI.getTopParentContainer(),
question, title, JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
if (answer != JOptionPane.YES_OPTION && answer != JOptionPane.NO_OPTION) {
return false;
}
compileFromSource = answer != JOptionPane.YES_OPTION;
}
}
/* Description */
if (getDescription() == null) {
setDescription(targetNice + " Mote Type #" + getIdentifier());
}
if (getSourceFile() != null) {
compileFromSource = true;
}
if (compileFromSource) {
MspELFCompiler compiler = new MspELFCompiler(target);
compiler.setCompileCommand(compileCommand);
if (visAvailable) {
boolean success = compiler.showDialog(GUI.getTopParentContainer(), this);
if (success) {
setSourceFile(compiler.getSourceFile());
setELFFile(compiler.getOutputFile());
setCompileCommand(compiler.getLastCompileCommand());
return true;
} else {
return false;
}
} else {
MessageList compilationOutput = new MessageList();
try {
compiler.compileFirmware(getSourceFile(), null, null, compilationOutput,
true);
} catch (Exception e) {
MoteTypeCreationException newException = new MoteTypeCreationException(
"Mote type creation failed: " + e.getMessage());
newException = (MoteTypeCreationException) newException.initCause(e);
newException.setCompilationOutput(compilationOutput);
if (compilationOutput != null) {
try { Thread.sleep(500); } catch (InterruptedException ignore) { }
ListModel tmp = compilationOutput.getModel();
for (int i=tmp.getSize()-5; i < tmp.getSize(); i++) {
if (i < 0) {
continue;
}
logger.fatal(">> " + tmp.getElementAt(i));
}
}
logger.fatal("Compilation error: " + e.getMessage());
throw newException;
}
setSourceFile(compiler.getSourceFile());
setELFFile(compiler.getOutputFile());
setCompileCommand(compiler.getLastCompileCommand());
return true;
}
}
if (GUI.isVisualizedInApplet()) {
return true;
}
// Check dependency files
if (getELFFile() == null || !getELFFile().exists()) {
if (!visAvailable) {
throw new MoteTypeCreationException("ELF file does not exist: " + getELFFile());
}
JFileChooser fc = new JFileChooser();
// Select previous directory
if (lastParentDirectory != null) {
fc.setCurrentDirectory(lastParentDirectory);
} else {
fc.setCurrentDirectory(new java.io.File(GUI
.getExternalToolsSetting("PATH_CONTIKI")));
}
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.addChoosableFileFilter(new FileFilter() {
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
}
String filename = f.getName();
if (filename != null) {
if (filename.endsWith(firmwareFileExtension)) {
return true;
}
}
return false;
}
public String getDescription() {
return "ELF file";
}
});
fc.setDialogTitle("Select ELF file");
if (fc.showOpenDialog(parentContainer) == JFileChooser.APPROVE_OPTION) {
File selectedFile = fc.getSelectedFile();
if (!selectedFile.exists()) {
logger.fatal("Selected file \"" + selectedFile + "\" does not exist");
return false;
}
if (!selectedFile.getName().endsWith(firmwareFileExtension)) {
logger.fatal("Selected file \"" + selectedFile + "\" does not end with " + firmwareFileExtension);
return false;
}
setELFFile(fc.getSelectedFile());
} else {
return false;
}
}
return true;
}
protected static class MspELFCompiler {
private static int LABEL_WIDTH = 170;
private static int LABEL_HEIGHT = 15;
private JButton cancelButton = new JButton("Cancel");
private JButton compileButton = new JButton("Compile");
private JButton createButton = new JButton("Create");
private JTextField sourceTextField = new JTextField();
private JTextField compileCommandTextField = new JTextField();
// private JFormattedTextField nodeIDTextField;
// private NumberFormat integerFormat = NumberFormat.getIntegerInstance();
private String lastCompileCommand = null;
private File sourceFile = null;
private File ELFFile = null;
private String target;
private JDialog myDialog;
private String customizedCompileCommand = null;
static enum DialogState {
NO_SOURCE, SELECTED_SOURCE, IS_COMPILING, COMPILED_SOURCE
}
public MspELFCompiler(String target) {
this.target = target;
}
private String getCompileCommand(String filename) {
if (customizedCompileCommand != null) {
return customizedCompileCommand;
}
return GUI.getExternalToolsSetting("PATH_MAKE") + " " + filename + firmwareFileExtension + " TARGET=" + target;
}
private void setCompileCommand(String command) {
if (command == null || command.isEmpty()) {
customizedCompileCommand = null;
return;
}
customizedCompileCommand = command;
}
/**
* @return Compiler output
*/
public File getOutputFile() {
return ELFFile;
}
public File getSourceFile() {
return sourceFile;
}
public String getLastCompileCommand() {
return lastCompileCommand;
}
private void updateDialog(DialogState dialogState) {
switch (dialogState) {
case NO_SOURCE:
compileButton.setEnabled(false);
createButton.setEnabled(false);
compileCommandTextField.setText("");
break;
case IS_COMPILING:
compileButton.setEnabled(false);
createButton.setEnabled(false);
break;
case SELECTED_SOURCE:
File sourceFile = new File(sourceTextField.getText());
if (!sourceFile.exists()) {
updateDialog(DialogState.NO_SOURCE);
break;
}
File parentDirectory = sourceFile.getParentFile();
if (!parentDirectory.exists()) {
updateDialog(DialogState.NO_SOURCE);
break;
}
if (!sourceFile.getName().endsWith(".c")) {
updateDialog(DialogState.NO_SOURCE);
break;
}
String name = sourceFile.getName().substring(0,
sourceFile.getName().length() - 2);
compileButton.setEnabled(true);
createButton.setEnabled(false);
compileCommandTextField.setText(getCompileCommand(name));
compileButton.requestFocusInWindow();
break;
case COMPILED_SOURCE:
compileButton.setEnabled(true);
createButton.setEnabled(true);
createButton.requestFocusInWindow();
myDialog.getRootPane().setDefaultButton(createButton);
break;
default:
break;
}
}
protected void compileFirmware(final File sourceFile,
final Action successAction, final Action failAction,
final MessageList compilationOutput, boolean synchronous) throws Exception {
final File parentDirectory = sourceFile.getParentFile();
final String filenameNoExtension = sourceFile.getName().substring(0,
sourceFile.getName().length() - 2);
final String command = getCompileCommand(filenameNoExtension);
logger.info("-- Compiling MSP430 Firmware --");
logger.info("Compilation command: " + command);
compilationOutput.clearMessages();
try {
String[] cmd = command.split(" ");
final Process compileProcess = Runtime.getRuntime().exec(cmd, null,
parentDirectory);
final BufferedReader processNormal = new BufferedReader(
new InputStreamReader(compileProcess.getInputStream()));
final BufferedReader processError = new BufferedReader(
new InputStreamReader(compileProcess.getErrorStream()));
final File ELFFile = new File(parentDirectory, filenameNoExtension + firmwareFileExtension);
if (ELFFile.exists()) {
ELFFile.delete();
if (ELFFile.exists()) {
compilationOutput.addMessage("Error when deleting old " + ELFFile.getName(), MessageList.ERROR);
if (failAction != null) {
failAction.actionPerformed(null);
}
throw new MoteTypeCreationException("Error when deleting old "
+ ELFFile.getName());
}
}
Thread readInput = new Thread(new Runnable() {
public void run() {
try {
String readLine;
while ((readLine = processNormal.readLine()) != null) {
compilationOutput.addMessage(readLine, MessageList.NORMAL);
}
} catch (IOException e) {
logger.warn("Error while reading from process");
}
}
}, "read input stream thread");
Thread readError = new Thread(new Runnable() {
public void run() {
try {
String readLine;
while ((readLine = processError.readLine()) != null) {
compilationOutput.addMessage(readLine, MessageList.ERROR);
}
} catch (IOException e) {
logger.warn("Error while reading from process");
}
}
}, "read input stream thread");
final MoteTypeCreationException syncException =
new MoteTypeCreationException("");
Thread handleCompilationResultThread = new Thread(new Runnable() {
public void run() {
/* Wait for compilation to end */
try {
compileProcess.waitFor();
} catch (Exception e) {
compilationOutput.addMessage(e.getMessage(), MessageList.ERROR);
syncException.setCompilationOutput(new MessageList());
syncException.fillInStackTrace();
return;
}
/* Check return value */
if (compileProcess.exitValue() != 0) {
compilationOutput.addMessage("Process returned error code " + compileProcess.exitValue(), MessageList.ERROR);
if (failAction != null) {
failAction.actionPerformed(null);
}
syncException.setCompilationOutput(new MessageList());
syncException.fillInStackTrace();
return;
}
if (!ELFFile.exists()) {
compilationOutput.addMessage("Can't locate output file " + ELFFile, MessageList.ERROR);
if (failAction != null) {
failAction.actionPerformed(null);
}
syncException.setCompilationOutput(new MessageList());
syncException.fillInStackTrace();
return;
}
compilationOutput.addMessage("", MessageList.NORMAL);
compilationOutput.addMessage("Compilation succeded", MessageList.NORMAL);
MspELFCompiler.this.lastCompileCommand = command;
MspELFCompiler.this.sourceFile = sourceFile;
MspELFCompiler.this.ELFFile = ELFFile;
if (successAction != null) {
successAction.actionPerformed(null);
}
}
}, "handle compilation results");
readInput.start();
readError.start();
handleCompilationResultThread.start();
if (synchronous) {
try {
handleCompilationResultThread.join();
} catch (Exception e) {
throw (MoteTypeCreationException) new MoteTypeCreationException(
"Compilation error: " + e.getMessage()).initCause(e);
}
/* Detect error manually */
if (syncException.hasCompilationOutput()) {
throw (MoteTypeCreationException) new MoteTypeCreationException(
"Bad return value").initCause(syncException);
}
}
} catch (IOException ex) {
if (failAction != null) {
failAction.actionPerformed(null);
}
throw (MoteTypeCreationException) new MoteTypeCreationException(
"Compilation error: " + ex.getMessage()).initCause(ex);
}
}
public boolean showDialog(Container parentContainer, final MspMoteType moteType) {
if (parentContainer instanceof Window) {
myDialog = new JDialog((Window)parentContainer, "Compile ELF file", ModalityType.APPLICATION_MODAL);
} else if (parentContainer instanceof Dialog) {
myDialog = new JDialog((Dialog)parentContainer, "Compile ELF file", ModalityType.APPLICATION_MODAL);
} else if (parentContainer instanceof Frame) {
myDialog = new JDialog((Frame)parentContainer, "Compile ELF file", ModalityType.APPLICATION_MODAL);
} else {
logger.fatal("Unknown parent container type: " + parentContainer);
return false;
}
final MessageList taskOutput = new MessageList();
// BOTTOM BUTTON PART
Box buttonBox = Box.createHorizontalBox();
buttonBox.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
buttonBox.add(Box.createHorizontalGlue());
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sourceFile = null;
ELFFile = null;
myDialog.dispose();
}
});
compileButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final File selectedSourceFile = new File(sourceTextField.getText());
/* Strip .c file extension */
final String filenameNoExtension = selectedSourceFile.getName()
.substring(0, selectedSourceFile.getName().length() - 2);
Action successAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
updateDialog(DialogState.COMPILED_SOURCE);
File parentFile = selectedSourceFile.getParentFile();
sourceFile = selectedSourceFile;
ELFFile = new File(parentFile, filenameNoExtension + firmwareFileExtension);
}
};
Action failAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
updateDialog(DialogState.SELECTED_SOURCE);
}
};
updateDialog(DialogState.IS_COMPILING);
try {
compileFirmware(new File(sourceTextField.getText()), successAction,
failAction, taskOutput, false);
} catch (Exception e2) {
}
}
});
createButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
myDialog.dispose();
}
});
buttonBox.add(cancelButton);
buttonBox.add(Box.createHorizontalStrut(5));
buttonBox.add(compileButton);
buttonBox.add(Box.createHorizontalStrut(5));
buttonBox.add(createButton);
// MAIN DIALOG CONTENTS
Box horizBox;
JLabel label;
Box vertBox = Box.createVerticalBox();
// Source
horizBox = Box.createHorizontalBox();
horizBox.setMaximumSize(new Dimension(Integer.MAX_VALUE, LABEL_HEIGHT));
horizBox.setAlignmentX(Component.LEFT_ALIGNMENT);
label = new JLabel("Contiki process sourcefile");
label.setPreferredSize(new Dimension(LABEL_WIDTH, LABEL_HEIGHT));
sourceTextField.setText("");
if (moteType.getSourceFile() != null) {
sourceTextField.setText(moteType.getSourceFile().getAbsolutePath());
}
sourceTextField.setColumns(25);
sourceTextField.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
updateDialog(DialogState.SELECTED_SOURCE);
}
public void changedUpdate(DocumentEvent e) {
updateDialog(DialogState.SELECTED_SOURCE);
}
public void removeUpdate(DocumentEvent e) {
updateDialog(DialogState.SELECTED_SOURCE);
}
});
JButton browseButton = new JButton("Browse");
browseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
updateDialog(DialogState.NO_SOURCE);
JFileChooser fc = new JFileChooser();
if (lastParentDirectory != null) {
fc.setCurrentDirectory(lastParentDirectory);
} else {
fc.setCurrentDirectory(new java.io.File(GUI
.getExternalToolsSetting("PATH_CONTIKI")));
}
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
fc.addChoosableFileFilter(new FileFilter() {
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
}
String filename = f.getName();
if (filename != null) {
if (filename.endsWith(".c")) {
return true;
}
}
return false;
}
public String getDescription() {
return "Contiki process source";
}
});
fc.setDialogTitle("Select Contiki process source");
if (fc.showOpenDialog(myDialog) == JFileChooser.APPROVE_OPTION) {
lastParentDirectory = null;
sourceTextField.setText("");
File selectedFile = fc.getSelectedFile();
if (!selectedFile.exists()) {
return;
}
if (!selectedFile.getName().endsWith(".c")) {
return;
}
lastParentDirectory = fc.getSelectedFile().getParentFile();
sourceTextField.setText(fc.getSelectedFile().getAbsolutePath());
updateDialog(DialogState.SELECTED_SOURCE);
}
}
});
horizBox.add(label);
horizBox.add(Box.createHorizontalStrut(10));
horizBox.add(sourceTextField);
horizBox.add(browseButton);
vertBox.add(horizBox);
vertBox.add(Box.createRigidArea(new Dimension(0, 5)));
// Node ID
/*
* horizBox = Box.createHorizontalBox(); horizBox.setMaximumSize(new
* Dimension(Integer.MAX_VALUE,LABEL_HEIGHT));
* horizBox.setAlignmentX(Component.LEFT_ALIGNMENT); label = new
* JLabel("Node ID (0=EEPROM)"); label.setPreferredSize(new
* Dimension(LABEL_WIDTH,LABEL_HEIGHT));
*
* nodeIDTextField = new JFormattedTextField(integerFormat);
* nodeIDTextField.setValue(new Integer(0));
* nodeIDTextField.setColumns(25);
* nodeIDTextField.addPropertyChangeListener("value", new
* PropertyChangeListener() { public void
* propertyChange(PropertyChangeEvent e) {
* updateDialog(DialogState.SELECTED_SOURCE); } });
*
* horizBox.add(label); horizBox.add(Box.createHorizontalStrut(150));
* horizBox.add(nodeIDTextField);
*
* vertBox.add(horizBox); vertBox.add(Box.createRigidArea(new
* Dimension(0,5)));
*/
// Compile command
horizBox = Box.createHorizontalBox();
horizBox.setMaximumSize(new Dimension(Integer.MAX_VALUE, LABEL_HEIGHT));
horizBox.setAlignmentX(Component.LEFT_ALIGNMENT);
label = new JLabel("Compile command");
label.setPreferredSize(new Dimension(LABEL_WIDTH, LABEL_HEIGHT));
compileCommandTextField.setText("");
compileCommandTextField.setColumns(25);
compileCommandTextField.setEditable(true);
compileCommandTextField.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
setCompileCommand(compileCommandTextField.getText());
}
public void changedUpdate(DocumentEvent e) {
setCompileCommand(compileCommandTextField.getText());
}
public void removeUpdate(DocumentEvent e) {
setCompileCommand(compileCommandTextField.getText());
}
});
horizBox.add(label);
horizBox.add(Box.createHorizontalStrut(10));
horizBox.add(compileCommandTextField);
vertBox.add(horizBox);
vertBox.add(Box.createRigidArea(new Dimension(0, 5)));
vertBox.add(Box.createRigidArea(new Dimension(0, 5)));
vertBox.add(new JLabel("Compilation output:"));
vertBox.add(Box.createRigidArea(new Dimension(0, 5)));
vertBox.add(new JScrollPane(taskOutput));
vertBox.add(Box.createRigidArea(new Dimension(0, 5)));
vertBox.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
Container contentPane = myDialog.getContentPane();
contentPane.add(vertBox, BorderLayout.CENTER);
contentPane.add(buttonBox, BorderLayout.SOUTH);
myDialog.pack();
myDialog.setLocationRelativeTo(parentContainer);
myDialog.getRootPane().setDefaultButton(compileButton);
// Dispose on escape key
InputMap inputMap = myDialog.getRootPane().getInputMap(
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false),
"dispose");
AbstractAction cancelAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
cancelButton.doClick();
}
};
myDialog.getRootPane().getActionMap().put("dispose", cancelAction);
myDialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
myDialog.addWindowListener(new WindowListener() {
public void windowDeactivated(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowOpened(WindowEvent e) {
}
public void windowClosed(WindowEvent e) {
}
public void windowActivated(WindowEvent e) {
}
public void windowClosing(WindowEvent e) {
cancelButton.doClick();
}
});
updateDialog(DialogState.NO_SOURCE);
if (moteType.getSourceFile() != null) {
updateDialog(DialogState.SELECTED_SOURCE);
if (customizedCompileCommand != null && !customizedCompileCommand.equals("")) {
compileCommandTextField.setText(customizedCompileCommand);
}
compileButton.requestFocus();
}
myDialog.setVisible(true);
return sourceFile != null;
}
}
public JPanel getTypeVisualizer() {
JPanel panel = new JPanel();
JLabel label = new JLabel();
JPanel smallPane;
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
// Identifier
smallPane = new JPanel(new BorderLayout());
label = new JLabel("Identifier");
smallPane.add(BorderLayout.WEST, label);
label = new JLabel(getIdentifier());
smallPane.add(BorderLayout.EAST, label);
panel.add(smallPane);
// Description
smallPane = new JPanel(new BorderLayout());
label = new JLabel("Description");
smallPane.add(BorderLayout.WEST, label);
label = new JLabel(getDescription());
smallPane.add(BorderLayout.EAST, label);
panel.add(smallPane);
// ELF Hex file
smallPane = new JPanel(new BorderLayout());
label = new JLabel("ELF file");
smallPane.add(BorderLayout.WEST, label);
label = new JLabel(getELFFile().getName());
label.setToolTipText(getELFFile().getPath());
smallPane.add(BorderLayout.EAST, label);
panel.add(smallPane);
// Source file
smallPane = new JPanel(new BorderLayout());
label = new JLabel("Source file");
smallPane.add(BorderLayout.WEST, label);
logger.debug(">>>> " + getSourceFile());
if (getSourceFile() != null) {
label = new JLabel(getSourceFile().getName());
label.setToolTipText(getSourceFile().getPath());
} else {
label = new JLabel("[not specified]");
}
smallPane.add(BorderLayout.EAST, label);
panel.add(smallPane);
// Icon (if available)
if (!GUI.isVisualizedInApplet()) {
Icon moteTypeIcon = getMoteTypeIcon();
if (moteTypeIcon != null) {
smallPane = new JPanel(new BorderLayout());
label = new JLabel(moteTypeIcon);
smallPane.add(BorderLayout.CENTER, label);
panel.add(smallPane);
}
} else {
smallPane = new JPanel(new BorderLayout());
label = new JLabel("No icon available in applet mode");
smallPane.add(BorderLayout.CENTER, label);
panel.add(smallPane);
}
panel.add(Box.createRigidArea(new Dimension(0, 5)));
return panel;
}
public abstract Icon getMoteTypeIcon();
public ProjectConfig getConfig() {
logger.warn("Msp mote type project config not implemented");
return null;
}
public Collection<Element> getConfigXML() {
Vector<Element> config = new Vector<Element>();
Element element;
// Identifier
element = new Element("identifier");
element.setText(getIdentifier());
config.add(element);
// Description
element = new Element("description");
element.setText(getDescription());
config.add(element);
// Source file
if (fileSource != null) {
element = new Element("source");
fileSource = GUI.stripAbsoluteContikiPath(fileSource);
element.setText(fileSource.getPath().replaceAll("\\\\", "/"));
config.add(element);
element = new Element("command");
element.setText(compileCommand);
config.add(element);
} else {
// ELF file
element = new Element("elf");
fileELF = GUI.stripAbsoluteContikiPath(fileELF);
element.setText(fileELF.getPath().replaceAll("\\\\", "/"));
config.add(element);
}
return config;
}
public boolean setConfigXML(Simulation simulation,
Collection<Element> configXML, boolean visAvailable)
throws MoteTypeCreationException {
for (Element element : configXML) {
String name = element.getName();
if (name.equals("identifier")) {
identifier = element.getText();
} else if (name.equals("description")) {
description = element.getText();
} else if (name.equals("source")) {
fileSource = new File(element.getText());
} else if (name.equals("command")) {
compileCommand = element.getText();
} else if (name.equals("elf")) {
fileELF = new File(element.getText());
} else {
logger.fatal("Unrecognized entry in loaded configuration: " + name);
throw new MoteTypeCreationException(
"Unrecognized entry in loaded configuration: " + name);
}
}
return configureAndInit(GUI.getTopParentContainer(), simulation, visAvailable);
}
}
| kill potentially unfinished compilation process when dialog is closed
| tools/cooja/apps/mspsim/src/se/sics/cooja/mspmote/MspMoteType.java | kill potentially unfinished compilation process when dialog is closed |
|
Java | bsd-3-clause | 300cfd3a3e606126c7226c6fe0a4e461da7ca1f5 | 0 | stain/alibaba,stain/alibaba,stain/alibaba | /*
* Copyright 2010, Zepheira LLC Some rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the openrdf.org nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
package org.openrdf.http.object.model;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.util.Arrays;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.IOControl;
import org.openrdf.http.object.util.ChannelUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Allows an {@link ReadableByteChannel} to be used as an HttpEntity.
*
* @author James Leigh
*
*/
public class ReadableHttpEntityChannel implements HttpEntityChannel {
private Logger logger = LoggerFactory.getLogger(ReadableHttpEntityChannel.class);
private String contentType;
private long contentLength;
private ByteBuffer buf = ByteBuffer.allocate(1024 * 8);
private ReadableByteChannel cin;
public ReadableHttpEntityChannel(String type, long length,
ReadableByteChannel in) {
this(type, length, in, (List<Runnable>) null);
}
public ReadableHttpEntityChannel(String type, long length,
ReadableByteChannel in, Runnable... onClose) {
this(type, length, in, Arrays.asList(onClose));
}
public ReadableHttpEntityChannel(String type, long length,
final ReadableByteChannel in, final List<Runnable> onClose) {
assert in != null;
this.contentType = type;
this.contentLength = length;
this.cin = new ReadableByteChannel() {
public boolean isOpen() {
return in.isOpen();
}
public void close() throws IOException {
try {
in.close();
} catch (RuntimeException e) {
logger.error(e.toString(), e);
throw e;
} catch (Error e) {
logger.error(e.toString(), e);
throw e;
} catch (IOException e) {
logger.warn(e.toString(), e);
throw e;
} finally {
if (onClose != null) {
for (Runnable task : onClose) {
try {
task.run();
} catch (RuntimeException e) {
} catch (Error e) {
}
}
}
}
}
public int read(ByteBuffer dst) throws IOException {
try {
return in.read(dst);
} catch (RuntimeException e) {
logger.error(e.toString(), e);
throw e;
} catch (Error e) {
logger.error(e.toString(), e);
throw e;
} catch (IOException e) {
logger.warn(e.toString(), e);
throw e;
}
}
@Override
public String toString() {
return in.toString();
}
};
}
@Override
public String toString() {
return cin.toString();
}
public final void consumeContent() throws IOException {
finish();
}
public InputStream getContent() throws IOException {
return ChannelUtil.newInputStream(cin);
}
public ReadableByteChannel getReadableByteChannel() {
return cin;
}
public Header getContentEncoding() {
return new BasicHeader("Content-Encoding", "identity");
}
public long getContentLength() {
return contentLength;
}
public Header getContentType() {
return new BasicHeader("Content-Type", contentType);
}
public boolean isChunked() {
return getContentLength() < 0;
}
public boolean isRepeatable() {
return false;
}
public boolean isStreaming() {
return true;
}
public void writeTo(OutputStream out) throws IOException {
InputStream in = getContent();
try {
byte[] buf = new byte[1024];
int read;
while ((read = in.read(buf)) >= 0) {
out.write(buf, 0, read);
}
} catch (Error e) {
throw e;
} catch (RuntimeException e) {
throw e;
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new IOException(e);
} finally {
in.close();
}
}
public final void finish() throws IOException {
cin.close();
}
public void produceContent(ContentEncoder encoder, IOControl ioctrl)
throws IOException {
buf.clear();
if (cin.read(buf) < 0) {
if (!encoder.isCompleted()) {
encoder.complete();
}
} else {
buf.flip();
encoder.write(buf);
}
}
} | object-server/src/main/java/org/openrdf/http/object/model/ReadableHttpEntityChannel.java | /*
* Copyright 2010, Zepheira LLC Some rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the openrdf.org nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
package org.openrdf.http.object.model;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import org.openrdf.http.object.util.ChannelUtil;
import java.nio.channels.ReadableByteChannel;
import java.util.Arrays;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.apache.http.nio.ContentEncoder;
import org.apache.http.nio.IOControl;
/**
* Allows an {@link ReadableByteChannel} to be used as an HttpEntity.
*
* @author James Leigh
*
*/
public class ReadableHttpEntityChannel implements HttpEntityChannel {
private String contentType;
private long contentLength;
private ByteBuffer buf = ByteBuffer.allocate(1024 * 8);
private ReadableByteChannel cin;
public ReadableHttpEntityChannel(String type, long length,
ReadableByteChannel in) {
this(type, length, in, (List<Runnable>) null);
}
public ReadableHttpEntityChannel(String type, long length,
ReadableByteChannel in, Runnable... onClose) {
this(type, length, in, Arrays.asList(onClose));
}
public ReadableHttpEntityChannel(String type, long length,
final ReadableByteChannel in, final List<Runnable> onClose) {
assert in != null;
this.contentType = type;
this.contentLength = length;
this.cin = new ReadableByteChannel() {
public boolean isOpen() {
return in.isOpen();
}
public void close() throws IOException {
try {
in.close();
} finally {
if (onClose != null) {
for (Runnable task : onClose) {
try {
task.run();
} catch (RuntimeException e) {
} catch (Error e) {
}
}
}
}
}
public int read(ByteBuffer dst) throws IOException {
return in.read(dst);
}
@Override
public String toString() {
return in.toString();
}
};
}
@Override
public String toString() {
return cin.toString();
}
public final void consumeContent() throws IOException {
finish();
}
public InputStream getContent() throws IOException {
return ChannelUtil.newInputStream(cin);
}
public ReadableByteChannel getReadableByteChannel() {
return cin;
}
public Header getContentEncoding() {
return new BasicHeader("Content-Encoding", "identity");
}
public long getContentLength() {
return contentLength;
}
public Header getContentType() {
return new BasicHeader("Content-Type", contentType);
}
public boolean isChunked() {
return getContentLength() < 0;
}
public boolean isRepeatable() {
return false;
}
public boolean isStreaming() {
return true;
}
public void writeTo(OutputStream out) throws IOException {
InputStream in = getContent();
try {
byte[] buf = new byte[1024];
int read;
while ((read = in.read(buf)) >= 0) {
out.write(buf, 0, read);
}
} catch (Error e) {
throw e;
} catch (RuntimeException e) {
throw e;
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new IOException(e);
} finally {
in.close();
}
}
public final void finish() throws IOException {
cin.close();
}
public void produceContent(ContentEncoder encoder, IOControl ioctrl)
throws IOException {
buf.clear();
if (cin.read(buf) < 0) {
if (!encoder.isCompleted()) {
encoder.complete();
}
} else {
buf.flip();
encoder.write(buf);
}
}
} | Log some IOExceptions that occur in I/O dispatch thread
git-svn-id: cd7eace78e14be71dd0d8bb0613a77a632a34638@10355 3fbd4d3e-0f96-47c4-bab7-89622e02a19e
| object-server/src/main/java/org/openrdf/http/object/model/ReadableHttpEntityChannel.java | Log some IOExceptions that occur in I/O dispatch thread |
|
Java | bsd-3-clause | 4f3761394b6157a154ab075b9bcfc9445fa3b1f6 | 0 | NCIP/caaers,CBIIT/caaers,CBIIT/caaers,CBIIT/caaers,NCIP/caaers,CBIIT/caaers,NCIP/caaers,CBIIT/caaers,NCIP/caaers | package gov.nih.nci.cabig.caaers.rules.deploy;
import edu.nwu.bioinformatics.commons.DateUtils;
import gov.nih.nci.cabig.caaers.domain.*;
import gov.nih.nci.cabig.caaers.validation.ValidationErrors;
import java.util.Date;
public class PriorTherapyBusinessRulesTest extends AbstractBusinessRulesExecutionTestCase {
@Override
public String getBindUri() {
return "gov.nih.nci.cabig.caaers.rules.reporting_prior_therapies_section";
}
@Override
public String getRuleFile() {
return "rules_reporting_prior_therapy.xml";
}
/**
* RuleName : PTY_BR1_CHK Logic : "Comments (prior therapy) must be provided if 'Prior therapy'
* is 'No Prior Therapy'" Error Code : PTY_BR1_ERR Error Message : COMMENTS must be provided
* (including appropriate Prior Therapy) if PRIOR_THERAPY is "No Prior Therapy NOS"
*/
public void testCorrectPriorTherapy() throws Exception {
ExpeditedAdverseEventReport aeReport = createAEReport();
ValidationErrors errors = fireRules(aeReport);
assertNoErrors(errors, "When other comments is not provided for a non 'Prior Therapy NOS'");
}
/**
* RuleName : PTY_BR1_CHK Logic : "Comments (prior therapy) must be provided if 'Prior therapy'
* is 'No Prior Therapy'" Error Code : PTY_BR1_ERR Error Message : COMMENTS must be provided
* (including appropriate Prior Therapy) if PRIOR_THERAPY is "No Prior Therapy NOS"
*/
public void testNoPriorTherapy_With_OtherComments() throws Exception {
ExpeditedAdverseEventReport aeReport = createAEReport();
aeReport.getSaeReportPriorTherapies().get(0).getPriorTherapy().setText("Prior Therapy NOS");
aeReport.getSaeReportPriorTherapies().get(0).setOther("Other");
aeReport.getSaeReportPriorTherapies().get(0).setStartDate(new DateValue(org.apache.commons.lang.time.DateUtils.addDays(new Date(), -1)));
aeReport.getSaeReportPriorTherapies().get(0).setEndDate(new DateValue(new Date()));
aeReport.getSaeReportPriorTherapies().get(1).getPriorTherapy().setText("Prior Therapy NOS");
aeReport.getSaeReportPriorTherapies().get(1).setOther("Other1");
ValidationErrors errors = fireRules(aeReport);
assertNoErrors(errors, "When other comments is provided for a non 'Prior Therapy NOS'");
}
/**
* RuleName : PTY_BR1_CHK Logic : "Comments (prior therapy) must be provided if 'Prior therapy'
* is 'No Prior Therapy'" Error Code : PTY_BR1_ERR Error Message : COMMENTS must be provided
* (including appropriate Prior Therapy) if PRIOR_THERAPY is "No Prior Therapy NOS"
*/
public void testNoPriorTherapy_Without_OtherComments() throws Exception {
ExpeditedAdverseEventReport aeReport = createAEReport();
aeReport.getSaeReportPriorTherapies().get(0).getPriorTherapy().setText("Prior Therapy NOS");
aeReport.getSaeReportPriorTherapies().get(0).setStartDate(new DateValue(org.apache.commons.lang.time.DateUtils.addDays(new Date(), -1)));
aeReport.getSaeReportPriorTherapies().get(0).setEndDate(new DateValue(new Date()));
System.out.println(aeReport.getSaeReportPriorTherapies().get(0).getName());
aeReport.getSaeReportPriorTherapies().get(0).setOther(null);
aeReport.getSaeReportPriorTherapies().get(1).getPriorTherapy().setText("Prior Therapy NOS");
aeReport.getSaeReportPriorTherapies().get(1).setOther(null);
ValidationErrors errors = fireRules(aeReport);
assertCorrectErrorCode(errors, "PTY_BR1_ERR");
assertSameErrorCount(errors, 2);
assertEquals("Correct replacement variable value", 2, errors.getErrorAt(1).getReplacementVariables()[0]);
}
/**
* RuleName : PTY_BR1_CHK Logic : "Comments (prior therapy) must be provided if 'Prior therapy'
* is 'No Prior Therapy'" Error Code : PTY_BR1_ERR Error Message : COMMENTS must be provided
* (including appropriate Prior Therapy) if PRIOR_THERAPY is "No Prior Therapy NOS"
*/
public void testOneOutOfTwoPriorTherapy_IsWithout_OtherComments() throws Exception {
ExpeditedAdverseEventReport aeReport = createAEReport();
aeReport.getSaeReportPriorTherapies().get(0).getPriorTherapy().setText("Prior Therapy NOS");
aeReport.getSaeReportPriorTherapies().get(0).setStartDate(new DateValue(org.apache.commons.lang.time.DateUtils.addDays(new Date(), -1)));
aeReport.getSaeReportPriorTherapies().get(0).setEndDate(new DateValue(new Date()));
aeReport.getSaeReportPriorTherapies().get(0).setOther("Other");
aeReport.getSaeReportPriorTherapies().get(1).getPriorTherapy().setText("Prior Therapy NOS");
aeReport.getSaeReportPriorTherapies().get(1).setOther(null);
ValidationErrors errors = fireRules(aeReport);
assertCorrectErrorCode(errors, "PTY_BR1_ERR");
assertSameErrorCount(errors, 1);
assertEquals("Correct replacement variable value", 2, errors.getErrorAt(0).getReplacementVariables()[0]);
}
/**
* RuleName : PTY_UK_CHK Logic : Prior Therapy must be unique Error Code : PTY_UK_ERR Error
* Message : PRIOR_THERAPY must be unique
*/
public void testUniquePriorTherapy() throws Exception {
ExpeditedAdverseEventReport aeReport = createAEReport();
ValidationErrors errors = fireRules(aeReport);
assertNoErrors(errors, "When prior therapy is unique");
}
/**
* RuleName : PTY_UK_CHK Logic : Prior Therapy must be unique Error Code : PTY_UK_ERR Error
* Message : PRIOR_THERAPY must be unique
*/
public void testDuplicatePriorTherapy() throws Exception {
ExpeditedAdverseEventReport aeReport = createAEReport();
aeReport.getSaeReportPriorTherapies().get(0).getPriorTherapy().setText("ll");
aeReport.getSaeReportPriorTherapies().get(0).getStartDate().setYear(2009);
aeReport.getSaeReportPriorTherapies().get(0).getStartDate().setMonth(01);
aeReport.getSaeReportPriorTherapies().get(1).getPriorTherapy().setText("ll");
aeReport.getSaeReportPriorTherapies().get(1).getStartDate().setYear(2009);
aeReport.getSaeReportPriorTherapies().get(1).getStartDate().setMonth(01);
ValidationErrors errors = fireRules(aeReport);
assertCorrectErrorCode(errors, "PTY_UK_ERR");
}
/**
* RuleName : PTY_UK_CHK Logic : Prior Therapy must be unique Error Code : PTY_UK_ERR Error
* Message : PRIOR_THERAPY must be unique
*/
public void testTwoOutOfThreeSamePriorTherapy() throws Exception {
ExpeditedAdverseEventReport aeReport = createAEReport();
aeReport.addSaeReportPriorTherapies(aeReport.getSaeReportPriorTherapies().get(1));
ValidationErrors errors = fireRules(aeReport);
assertCorrectErrorCode(errors, "PTY_UK_ERR");
assertSameErrorCount(errors, 1);
assertEquals("Replacement variable incorrect", 3, errors.getErrorAt(0).getReplacementVariables()[0]);
}
/**
* RuleName : PTY_BR4A_CHK Logic : ?Prior Therapy Agents? must be provided if "Prior_Therapy" is
* ?Bone Marrow Transplant? ?Chemotherapy (NOS)? ?Chemotherapy multiple agents systemic?
* ?Chemotherapy single agent systemic? ?Immunotherapy? ?Hormonal Therapy? Error Code :
* PTY_BR4A_ERR Error Message : CHEMO_AGENTS must be provided for the provided PRIOR_THERAPY
* value.
*/
public void testBMTPriorTherapy_With_PriorTherapyAgents() throws Exception {
ExpeditedAdverseEventReport aeReport = createAEReport();
int i = 0;
for (SAEReportPriorTherapy aet : aeReport.getSaeReportPriorTherapies()) {
aet.getPriorTherapy().setId(3);
PriorTherapyAgent pta = new PriorTherapyAgent();
ChemoAgent ca = new ChemoAgent();
ca.setId(2 + i);
ca.setName("chemoagent " + i++);
pta.setChemoAgent(ca);
aet.getPriorTherapyAgents().add(pta);
}
ValidationErrors errors = fireRules(aeReport);
assertNoErrors(errors,"when bone marrow transplant has priortherapy agents with chemo agents");
}
/**
* RuleName : PTY_BR4A_CHK Logic : ?Prior Therapy Agents? must be provided if "Prior_Therapy" is
* ?Bone Marrow Transplant? ?Chemotherapy (NOS)? ?Chemotherapy multiple agents systemic?
* ?Chemotherapy single agent systemic? ?Immunotherapy? ?Hormonal Therapy? Error Code :
* PTY_BR4A_ERR Error Message : CHEMO_AGENTS must be provided for the provided PRIOR_THERAPY
* value.
*/
/*
public void testBMTPriorTherapy_Without_PriorTherapyAgents() throws Exception {
ExpeditedAdverseEventReport aeReport = createAEReport();
int i = 0;
for (SAEReportPriorTherapy aet : aeReport.getSaeReportPriorTherapies()) {
aet.getPriorTherapy().setId(3);
}
ValidationErrors errors = fireRules(aeReport);
assertCorrectErrorCode(errors, "PTY_BR4A_ERR");
assertSameErrorCount(errors, 2);
}
*/
/**
* RuleName : PTY_BR4B_CHK Logic : ?Prior Therapy Agents? must not be provided if
* "Prior_Therapy" is not ?Bone Marrow Transplant? ?Chemotherapy (NOS)? ?Chemotherapy multiple
* agents systemic? ?Chemotherapy single agent systemic? ?Immunotherapy? ?Hormonal Therapy?
* Error Code : PTY_BR4B_ERR Error Message : CHEMO_AGENTS must be provided for the provided
* PRIOR_THERAPY value.
*/
public void testXYZPriorTherapy_With_PriorTherapyAgents() throws Exception {
ExpeditedAdverseEventReport aeReport = createAEReport();
int i = 0;
for (SAEReportPriorTherapy aet : aeReport.getSaeReportPriorTherapies()) {
aet.getPriorTherapy().setId(23);
PriorTherapyAgent pta = new PriorTherapyAgent();
ChemoAgent ca = new ChemoAgent();
ca.setId(2 + i);
ca.setName("chemoagent " + i++);
pta.setChemoAgent(ca);
aet.getPriorTherapyAgents().add(pta);
}
ValidationErrors errors = fireRules(aeReport);
assertCorrectErrorCode(errors, "PTY_BR4B_ERR");
assertSameErrorCount(errors, 2);
}
/**
* RuleName : PTY_BR3_CHK Logic : ?Therapy End Date? must not be provided if ?Therapy Start
* Date? is not provided Error Code : PTY_BR3_ERR Error Message : THERAPY_END_DATE must be not
* be provided if THERAPY_START_DATE is not provided.
* <p/>
* <p/>
* RuleName : PTY_BR2_CHK Logic : 'Therapy End Date' must not be later than 'Therapy Start Date'
* Error Code : PTY_BR2_ERR Error Message : THERAPY_END_DATE must be later than or equal
* THERAPY_START_DATE
*/
public void testPriorTherapyNoStartDate_NoEndDate() throws Exception {
ExpeditedAdverseEventReport aeReport = createAEReport();
for (SAEReportPriorTherapy aet : aeReport.getSaeReportPriorTherapies()) {
aet.getPriorTherapy().setId(83);
}
ValidationErrors errors = fireRules(aeReport);
assertNoErrors(errors, "No errors when no startdate and enddate");
}
/**
* RuleName : PTY_BR3_CHK Logic : ?Therapy End Date? must not be provided if ?Therapy Start
* Date? is not provided Error Code : PTY_BR3_ERR Error Message : THERAPY_END_DATE must be not
* be provided if THERAPY_START_DATE is not provided.
*
* @throws Exception
*/
public void testPriorTherapyNoStartDate_ButEndDate() throws Exception {
ExpeditedAdverseEventReport aeReport = createAEReport();
for (SAEReportPriorTherapy aet : aeReport.getSaeReportPriorTherapies()) {
aet.getPriorTherapy().setId(83);
aet.setEndDate(new DateValue(new Date()));
}
ValidationErrors errors = fireRules(aeReport);
assertCorrectErrorCode(errors, "PTY_BR3_ERR");
assertSameErrorCount(errors, 2);
}
/**
* RuleName : PTY_BR2_CHK Logic : 'Therapy End Date' must not be later than 'Therapy Start Date'
* Error Code : PTY_BR2_ERR Error Message : THERAPY_END_DATE must be later than or equal
* THERAPY_START_DATE
*/
public void testPriorTherapyStartOnly() throws Exception {
ExpeditedAdverseEventReport aeReport = createAEReport();
for (SAEReportPriorTherapy aet : aeReport.getSaeReportPriorTherapies()) {
aet.getPriorTherapy().setId(83);
aet.setStartDate(new DateValue(new Date()));
}
ValidationErrors errors = fireRules(aeReport);
assertNoErrors(errors, "No errors when only startdate ");
}
/**
* RuleName : PTY_BR2_CHK Logic : 'Therapy End Date' must not be later than 'Therapy Start Date'
* Error Code : PTY_BR2_ERR Error Message : THERAPY_END_DATE must be later than or equal
* THERAPY_START_DATE
*/
public void testPriorTherapyStartOnlyAndEndDateIsNull() throws Exception {
ExpeditedAdverseEventReport aeReport = createAEReport();
for (SAEReportPriorTherapy aet : aeReport.getSaeReportPriorTherapies()) {
aet.getPriorTherapy().setId(83);
aet.setStartDate(new DateValue(new Date()));
aet.setEndDate(null);
}
ValidationErrors errors = fireRules(aeReport);
assertNoErrors(errors, "No errors when only startdate ");
}
/**
* RuleName : PTY_BR2_CHK Logic : 'Therapy End Date' must not be later than 'Therapy Start Date'
* Error Code : PTY_BR2_ERR Error Message : THERAPY_END_DATE must be later than or equal
* THERAPY_START_DATE
*/
public void testPriorTherapyStart_LT_EndDate() throws Exception {
ExpeditedAdverseEventReport aeReport = createAEReport();
for (SAEReportPriorTherapy aet : aeReport.getSaeReportPriorTherapies()) {
aet.getPriorTherapy().setId(83);
aet.setStartDate(new DateValue(DateUtils.createDate(2007, 11, 9)));
aet.setEndDate(new DateValue(DateUtils.createDate(2007, 11, 11)));
}
ValidationErrors errors = fireRules(aeReport);
assertNoErrors(errors, "No errors when only startdate is less than end date ");
}
/**
* RuleName : PTY_BR2_CHK Logic : 'Therapy End Date' must not be later than 'Therapy Start Date'
* Error Code : PTY_BR2_ERR Error Message : THERAPY_END_DATE must be later than or equal
* THERAPY_START_DATE
*/
public void testPriorTherapyStartDate_GT_EndDate() throws Exception {
ExpeditedAdverseEventReport aeReport = createAEReport();
for (SAEReportPriorTherapy aet : aeReport.getSaeReportPriorTherapies()) {
aet.getPriorTherapy().setId(83);
aet.setStartDate(new DateValue(DateUtils.createDate(2007, 11, 19)));
aet.setEndDate(new DateValue(DateUtils.createDate(2007, 11, 11)));
}
ValidationErrors errors = fireRules(aeReport);
assertSameErrorCount(errors, 2);
assertCorrectErrorCode(errors, "PTY_BR2_ERR");
}
/**
* RuleName : PTY_BR2_CHK Logic : 'Therapy End Date' must not be later than 'Therapy Start Date'
* Error Code : PTY_BR2_ERR Error Message : THERAPY_END_DATE must be later than or equal
* THERAPY_START_DATE
*/
public void testOneOutOfTwoPriorTherapyStartDate_GT_EndDate() throws Exception {
ExpeditedAdverseEventReport aeReport = createAEReport();
int i = 0;
for (SAEReportPriorTherapy aet : aeReport.getSaeReportPriorTherapies()) {
aet.getPriorTherapy().setId(83);
aet.setStartDate(new DateValue(DateUtils.createDate(2007, 11, 9)));
if (i < 1) {
aet.setEndDate(new DateValue(DateUtils.createDate(2007, 11, 11)));
} else {
aet.setEndDate(new DateValue(DateUtils.createDate(2007, 10, 1)));
}
i++;
}
ValidationErrors errors = fireRules(aeReport);
assertSameErrorCount(errors, 1);
assertCorrectErrorCode(errors, "PTY_BR2_ERR");
assertEquals("Incorrect replacement variable", 2, errors.getErrorAt(0)
.getReplacementVariables()[0]);
}
/**
* RuleName : PTA_UK_CHK Logic : Prior Therapy Agents must be unique Error Code : PTA_UK_ERR
* Error Message : CHEMO_AGENT_NAME must be unique
*/
public void testUniqueChemoAgents() throws Exception {
ExpeditedAdverseEventReport aeReport = createAEReport();
int i = 0;
for (SAEReportPriorTherapy aet : aeReport.getSaeReportPriorTherapies()) {
aet.getPriorTherapy().setId(3);
PriorTherapyAgent pta = new PriorTherapyAgent();
ChemoAgent ca = new ChemoAgent();
ca.setId(2 + i);
ca.setName("chemoagent " + i++);
pta.setChemoAgent(ca);
aet.getPriorTherapyAgents().add(pta);
}
ValidationErrors errors = fireRules(aeReport);
assertNoErrors(errors, "when all has priortherapy agents with unique chemo agents");
}
/**
* RuleName : PTA_UK_CHK Logic : Prior Therapy Agents must be unique Error Code : PTA_UK_ERR
* Error Message : CHEMO_AGENT_NAME must be unique
*/
public void testDuplicateChemoAgents() throws Exception {
ExpeditedAdverseEventReport aeReport = createAEReport();
int i = 0;
for (SAEReportPriorTherapy aet : aeReport.getSaeReportPriorTherapies()) {
aet.getPriorTherapy().setId(3);
PriorTherapyAgent pta = new PriorTherapyAgent();
ChemoAgent ca = new ChemoAgent();
ca.setId(2 + i);
ca.setName("chemoagent");
pta.setChemoAgent(ca);
aet.getPriorTherapyAgents().add(pta);
}
ValidationErrors errors = fireRules(aeReport);
assertSameErrorCount(errors, 0);
}
}
| projects/rules/src/test/java/gov/nih/nci/cabig/caaers/rules/deploy/PriorTherapyBusinessRulesTest.java | package gov.nih.nci.cabig.caaers.rules.deploy;
import edu.nwu.bioinformatics.commons.DateUtils;
import gov.nih.nci.cabig.caaers.domain.*;
import gov.nih.nci.cabig.caaers.validation.ValidationErrors;
import java.util.Date;
public class PriorTherapyBusinessRulesTest extends AbstractBusinessRulesExecutionTestCase {
@Override
public String getBindUri() {
return "gov.nih.nci.cabig.caaers.rules.reporting_prior_therapies_section";
}
@Override
public String getRuleFile() {
return "rules_reporting_prior_therapy.xml";
}
/**
* RuleName : PTY_BR1_CHK Logic : "Comments (prior therapy) must be provided if 'Prior therapy'
* is 'No Prior Therapy'" Error Code : PTY_BR1_ERR Error Message : COMMENTS must be provided
* (including appropriate Prior Therapy) if PRIOR_THERAPY is "No Prior Therapy NOS"
*/
public void testCorrectPriorTherapy() throws Exception {
ExpeditedAdverseEventReport aeReport = createAEReport();
ValidationErrors errors = fireRules(aeReport);
assertNoErrors(errors, "When other comments is not provided for a non 'Prior Therapy NOS'");
}
/**
* RuleName : PTY_BR1_CHK Logic : "Comments (prior therapy) must be provided if 'Prior therapy'
* is 'No Prior Therapy'" Error Code : PTY_BR1_ERR Error Message : COMMENTS must be provided
* (including appropriate Prior Therapy) if PRIOR_THERAPY is "No Prior Therapy NOS"
*/
public void testNoPriorTherapy_With_OtherComments() throws Exception {
ExpeditedAdverseEventReport aeReport = createAEReport();
aeReport.getSaeReportPriorTherapies().get(0).getPriorTherapy().setText("Prior Therapy NOS");
aeReport.getSaeReportPriorTherapies().get(0).setOther("Other");
aeReport.getSaeReportPriorTherapies().get(0).setStartDate(new DateValue(org.apache.commons.lang.time.DateUtils.addDays(new Date(), -1)));
aeReport.getSaeReportPriorTherapies().get(0).setEndDate(new DateValue(new Date()));
aeReport.getSaeReportPriorTherapies().get(1).getPriorTherapy().setText("Prior Therapy NOS");
aeReport.getSaeReportPriorTherapies().get(1).setOther("Other1");
ValidationErrors errors = fireRules(aeReport);
assertNoErrors(errors, "When other comments is provided for a non 'Prior Therapy NOS'");
}
/**
* RuleName : PTY_BR1_CHK Logic : "Comments (prior therapy) must be provided if 'Prior therapy'
* is 'No Prior Therapy'" Error Code : PTY_BR1_ERR Error Message : COMMENTS must be provided
* (including appropriate Prior Therapy) if PRIOR_THERAPY is "No Prior Therapy NOS"
*/
public void testNoPriorTherapy_Without_OtherComments() throws Exception {
ExpeditedAdverseEventReport aeReport = createAEReport();
aeReport.getSaeReportPriorTherapies().get(0).getPriorTherapy().setText("Prior Therapy NOS");
aeReport.getSaeReportPriorTherapies().get(0).setStartDate(new DateValue(org.apache.commons.lang.time.DateUtils.addDays(new Date(), -1)));
aeReport.getSaeReportPriorTherapies().get(0).setEndDate(new DateValue(new Date()));
System.out.println(aeReport.getSaeReportPriorTherapies().get(0).getName());
aeReport.getSaeReportPriorTherapies().get(0).setOther(null);
aeReport.getSaeReportPriorTherapies().get(1).getPriorTherapy().setText("Prior Therapy NOS");
aeReport.getSaeReportPriorTherapies().get(1).setOther(null);
ValidationErrors errors = fireRules(aeReport);
assertCorrectErrorCode(errors, "PTY_BR1_ERR");
assertSameErrorCount(errors, 2);
assertEquals("Correct replacement variable value", 2, errors.getErrorAt(1).getReplacementVariables()[0]);
}
/**
* RuleName : PTY_BR1_CHK Logic : "Comments (prior therapy) must be provided if 'Prior therapy'
* is 'No Prior Therapy'" Error Code : PTY_BR1_ERR Error Message : COMMENTS must be provided
* (including appropriate Prior Therapy) if PRIOR_THERAPY is "No Prior Therapy NOS"
*/
public void testOneOutOfTwoPriorTherapy_IsWithout_OtherComments() throws Exception {
ExpeditedAdverseEventReport aeReport = createAEReport();
aeReport.getSaeReportPriorTherapies().get(0).getPriorTherapy().setText("Prior Therapy NOS");
aeReport.getSaeReportPriorTherapies().get(0).setStartDate(new DateValue(org.apache.commons.lang.time.DateUtils.addDays(new Date(), -1)));
aeReport.getSaeReportPriorTherapies().get(0).setEndDate(new DateValue(new Date()));
aeReport.getSaeReportPriorTherapies().get(0).setOther("Other");
aeReport.getSaeReportPriorTherapies().get(1).getPriorTherapy().setText("Prior Therapy NOS");
aeReport.getSaeReportPriorTherapies().get(1).setOther(null);
ValidationErrors errors = fireRules(aeReport);
assertCorrectErrorCode(errors, "PTY_BR1_ERR");
assertSameErrorCount(errors, 1);
assertEquals("Correct replacement variable value", 2, errors.getErrorAt(0).getReplacementVariables()[0]);
}
/**
* RuleName : PTY_UK_CHK Logic : Prior Therapy must be unique Error Code : PTY_UK_ERR Error
* Message : PRIOR_THERAPY must be unique
*/
public void testUniquePriorTherapy() throws Exception {
ExpeditedAdverseEventReport aeReport = createAEReport();
ValidationErrors errors = fireRules(aeReport);
assertNoErrors(errors, "When prior therapy is unique");
}
/**
* RuleName : PTY_UK_CHK Logic : Prior Therapy must be unique Error Code : PTY_UK_ERR Error
* Message : PRIOR_THERAPY must be unique
*/
public void testDuplicatePriorTherapy() throws Exception {
ExpeditedAdverseEventReport aeReport = createAEReport();
aeReport.getSaeReportPriorTherapies().get(0).getPriorTherapy().setText("ll");
aeReport.getSaeReportPriorTherapies().get(0).getStartDate().setYear(2009);
aeReport.getSaeReportPriorTherapies().get(0).getStartDate().setMonth(01);
aeReport.getSaeReportPriorTherapies().get(1).getPriorTherapy().setText("ll");
aeReport.getSaeReportPriorTherapies().get(1).getStartDate().setYear(2009);
aeReport.getSaeReportPriorTherapies().get(1).getStartDate().setMonth(01);
ValidationErrors errors = fireRules(aeReport);
assertCorrectErrorCode(errors, "PTY_UK_ERR");
}
/**
* RuleName : PTY_UK_CHK Logic : Prior Therapy must be unique Error Code : PTY_UK_ERR Error
* Message : PRIOR_THERAPY must be unique
*/
public void testTwoOutOfThreeSamePriorTherapy() throws Exception {
ExpeditedAdverseEventReport aeReport = createAEReport();
aeReport.addSaeReportPriorTherapies(aeReport.getSaeReportPriorTherapies().get(1));
ValidationErrors errors = fireRules(aeReport);
assertCorrectErrorCode(errors, "PTY_UK_ERR");
assertSameErrorCount(errors, 1);
assertEquals("Replacement variable incorrect", 3, errors.getErrorAt(0).getReplacementVariables()[0]);
}
/**
* RuleName : PTY_BR4A_CHK Logic : ?Prior Therapy Agents? must be provided if "Prior_Therapy" is
* ?Bone Marrow Transplant? ?Chemotherapy (NOS)? ?Chemotherapy multiple agents systemic?
* ?Chemotherapy single agent systemic? ?Immunotherapy? ?Hormonal Therapy? Error Code :
* PTY_BR4A_ERR Error Message : CHEMO_AGENTS must be provided for the provided PRIOR_THERAPY
* value.
*/
public void testBMTPriorTherapy_With_PriorTherapyAgents() throws Exception {
ExpeditedAdverseEventReport aeReport = createAEReport();
int i = 0;
for (SAEReportPriorTherapy aet : aeReport.getSaeReportPriorTherapies()) {
aet.getPriorTherapy().setId(3);
PriorTherapyAgent pta = new PriorTherapyAgent();
ChemoAgent ca = new ChemoAgent();
ca.setId(2 + i);
ca.setName("chemoagent " + i++);
pta.setChemoAgent(ca);
aet.getPriorTherapyAgents().add(pta);
}
ValidationErrors errors = fireRules(aeReport);
assertNoErrors(errors,"when bone marrow transplant has priortherapy agents with chemo agents");
}
/**
* RuleName : PTY_BR4A_CHK Logic : ?Prior Therapy Agents? must be provided if "Prior_Therapy" is
* ?Bone Marrow Transplant? ?Chemotherapy (NOS)? ?Chemotherapy multiple agents systemic?
* ?Chemotherapy single agent systemic? ?Immunotherapy? ?Hormonal Therapy? Error Code :
* PTY_BR4A_ERR Error Message : CHEMO_AGENTS must be provided for the provided PRIOR_THERAPY
* value.
*/
/*
public void testBMTPriorTherapy_Without_PriorTherapyAgents() throws Exception {
ExpeditedAdverseEventReport aeReport = createAEReport();
int i = 0;
for (SAEReportPriorTherapy aet : aeReport.getSaeReportPriorTherapies()) {
aet.getPriorTherapy().setId(3);
}
ValidationErrors errors = fireRules(aeReport);
assertCorrectErrorCode(errors, "PTY_BR4A_ERR");
assertSameErrorCount(errors, 2);
}
*/
/**
* RuleName : PTY_BR4B_CHK Logic : ?Prior Therapy Agents? must not be provided if
* "Prior_Therapy" is not ?Bone Marrow Transplant? ?Chemotherapy (NOS)? ?Chemotherapy multiple
* agents systemic? ?Chemotherapy single agent systemic? ?Immunotherapy? ?Hormonal Therapy?
* Error Code : PTY_BR4B_ERR Error Message : CHEMO_AGENTS must be provided for the provided
* PRIOR_THERAPY value.
*/
public void testXYZPriorTherapy_With_PriorTherapyAgents() throws Exception {
ExpeditedAdverseEventReport aeReport = createAEReport();
int i = 0;
for (SAEReportPriorTherapy aet : aeReport.getSaeReportPriorTherapies()) {
aet.getPriorTherapy().setId(23);
PriorTherapyAgent pta = new PriorTherapyAgent();
ChemoAgent ca = new ChemoAgent();
ca.setId(2 + i);
ca.setName("chemoagent " + i++);
pta.setChemoAgent(ca);
aet.getPriorTherapyAgents().add(pta);
}
ValidationErrors errors = fireRules(aeReport);
assertCorrectErrorCode(errors, "PTY_BR4B_ERR");
assertSameErrorCount(errors, 2);
}
/**
* RuleName : PTY_BR3_CHK Logic : ?Therapy End Date? must not be provided if ?Therapy Start
* Date? is not provided Error Code : PTY_BR3_ERR Error Message : THERAPY_END_DATE must be not
* be provided if THERAPY_START_DATE is not provided.
* <p/>
* <p/>
* RuleName : PTY_BR2_CHK Logic : 'Therapy End Date' must not be later than 'Therapy Start Date'
* Error Code : PTY_BR2_ERR Error Message : THERAPY_END_DATE must be later than or equal
* THERAPY_START_DATE
*/
public void testPriorTherapyNoStartDate_NoEndDate() throws Exception {
ExpeditedAdverseEventReport aeReport = createAEReport();
for (SAEReportPriorTherapy aet : aeReport.getSaeReportPriorTherapies()) {
aet.getPriorTherapy().setId(83);
}
ValidationErrors errors = fireRules(aeReport);
assertNoErrors(errors, "No errors when no startdate and enddate");
}
/**
* RuleName : PTY_BR3_CHK Logic : ?Therapy End Date? must not be provided if ?Therapy Start
* Date? is not provided Error Code : PTY_BR3_ERR Error Message : THERAPY_END_DATE must be not
* be provided if THERAPY_START_DATE is not provided.
*
* @throws Exception
*/
public void testPriorTherapyNoStartDate_ButEndDate() throws Exception {
ExpeditedAdverseEventReport aeReport = createAEReport();
for (SAEReportPriorTherapy aet : aeReport.getSaeReportPriorTherapies()) {
aet.getPriorTherapy().setId(83);
aet.setEndDate(new DateValue(new Date()));
}
ValidationErrors errors = fireRules(aeReport);
assertCorrectErrorCode(errors, "PTY_BR3_ERR");
assertSameErrorCount(errors, 2);
}
/**
* RuleName : PTY_BR2_CHK Logic : 'Therapy End Date' must not be later than 'Therapy Start Date'
* Error Code : PTY_BR2_ERR Error Message : THERAPY_END_DATE must be later than or equal
* THERAPY_START_DATE
*/
public void testPriorTherapyStartOnly() throws Exception {
ExpeditedAdverseEventReport aeReport = createAEReport();
for (SAEReportPriorTherapy aet : aeReport.getSaeReportPriorTherapies()) {
aet.getPriorTherapy().setId(83);
aet.setStartDate(new DateValue(new Date()));
}
ValidationErrors errors = fireRules(aeReport);
assertNoErrors(errors, "No errors when only startdate ");
}
/**
* RuleName : PTY_BR2_CHK Logic : 'Therapy End Date' must not be later than 'Therapy Start Date'
* Error Code : PTY_BR2_ERR Error Message : THERAPY_END_DATE must be later than or equal
* THERAPY_START_DATE
*/
public void testPriorTherapyStartOnlyAndEndDateIsNull() throws Exception {
ExpeditedAdverseEventReport aeReport = createAEReport();
for (SAEReportPriorTherapy aet : aeReport.getSaeReportPriorTherapies()) {
aet.getPriorTherapy().setId(83);
aet.setStartDate(new DateValue(new Date()));
aet.setEndDate(null);
}
ValidationErrors errors = fireRules(aeReport);
assertNoErrors(errors, "No errors when only startdate ");
}
/**
* RuleName : PTY_BR2_CHK Logic : 'Therapy End Date' must not be later than 'Therapy Start Date'
* Error Code : PTY_BR2_ERR Error Message : THERAPY_END_DATE must be later than or equal
* THERAPY_START_DATE
*/
public void testPriorTherapyStart_LT_EndDate() throws Exception {
ExpeditedAdverseEventReport aeReport = createAEReport();
for (SAEReportPriorTherapy aet : aeReport.getSaeReportPriorTherapies()) {
aet.getPriorTherapy().setId(83);
aet.setStartDate(new DateValue(DateUtils.createDate(2007, 11, 9)));
aet.setEndDate(new DateValue(DateUtils.createDate(2007, 11, 11)));
}
ValidationErrors errors = fireRules(aeReport);
assertNoErrors(errors, "No errors when only startdate is less than end date ");
}
/**
* RuleName : PTY_BR2_CHK Logic : 'Therapy End Date' must not be later than 'Therapy Start Date'
* Error Code : PTY_BR2_ERR Error Message : THERAPY_END_DATE must be later than or equal
* THERAPY_START_DATE
*/
public void testPriorTherapyStartDate_GT_EndDate() throws Exception {
ExpeditedAdverseEventReport aeReport = createAEReport();
for (SAEReportPriorTherapy aet : aeReport.getSaeReportPriorTherapies()) {
aet.getPriorTherapy().setId(83);
aet.setStartDate(new DateValue(DateUtils.createDate(2007, 11, 19)));
aet.setEndDate(new DateValue(DateUtils.createDate(2007, 11, 11)));
}
ValidationErrors errors = fireRules(aeReport);
assertSameErrorCount(errors, 2);
assertCorrectErrorCode(errors, "PTY_BR2_ERR");
}
/**
* RuleName : PTY_BR2_CHK Logic : 'Therapy End Date' must not be later than 'Therapy Start Date'
* Error Code : PTY_BR2_ERR Error Message : THERAPY_END_DATE must be later than or equal
* THERAPY_START_DATE
*/
public void testOneOutOfTwoPriorTherapyStartDate_GT_EndDate() throws Exception {
ExpeditedAdverseEventReport aeReport = createAEReport();
int i = 0;
for (SAEReportPriorTherapy aet : aeReport.getSaeReportPriorTherapies()) {
aet.getPriorTherapy().setId(83);
aet.setStartDate(new DateValue(DateUtils.createDate(2007, 11, 9)));
if (i < 1) {
aet.setEndDate(new DateValue(DateUtils.createDate(2007, 11, 11)));
} else {
aet.setEndDate(new DateValue(DateUtils.createDate(2007, 10, 1)));
}
i++;
}
ValidationErrors errors = fireRules(aeReport);
assertSameErrorCount(errors, 1);
assertCorrectErrorCode(errors, "PTY_BR2_ERR");
assertEquals("Incorrect replacement variable", 2, errors.getErrorAt(0)
.getReplacementVariables()[0]);
}
/**
* RuleName : PTA_UK_CHK Logic : Prior Therapy Agents must be unique Error Code : PTA_UK_ERR
* Error Message : CHEMO_AGENT_NAME must be unique
*/
public void testUniqueChemoAgents() throws Exception {
ExpeditedAdverseEventReport aeReport = createAEReport();
int i = 0;
for (SAEReportPriorTherapy aet : aeReport.getSaeReportPriorTherapies()) {
aet.getPriorTherapy().setId(3);
PriorTherapyAgent pta = new PriorTherapyAgent();
ChemoAgent ca = new ChemoAgent();
ca.setId(2 + i);
ca.setName("chemoagent " + i++);
pta.setChemoAgent(ca);
aet.getPriorTherapyAgents().add(pta);
}
ValidationErrors errors = fireRules(aeReport);
assertNoErrors(errors, "when all has priortherapy agents with unique chemo agents");
}
/**
* RuleName : PTA_UK_CHK Logic : Prior Therapy Agents must be unique Error Code : PTA_UK_ERR
* Error Message : CHEMO_AGENT_NAME must be unique
*/
public void testDuplicateChemoAgents() throws Exception {
ExpeditedAdverseEventReport aeReport = createAEReport();
int i = 0;
for (SAEReportPriorTherapy aet : aeReport.getSaeReportPriorTherapies()) {
aet.getPriorTherapy().setId(3);
PriorTherapyAgent pta = new PriorTherapyAgent();
ChemoAgent ca = new ChemoAgent();
ca.setId(2 + i);
ca.setName("chemoagent");
pta.setChemoAgent(ca);
aet.getPriorTherapyAgents().add(pta);
}
ValidationErrors errors = fireRules(aeReport);
assertSameErrorCount(errors, 0);
assertCorrectErrorCode(errors, "PTA_UK_ERR");
}
}
|
SVN-Revision: 8369
| projects/rules/src/test/java/gov/nih/nci/cabig/caaers/rules/deploy/PriorTherapyBusinessRulesTest.java | ||
Java | mit | 7d7dfd6507c93c52a6c18657aa651ecabac32cf1 | 0 | rinrinne/gerrit-events,sonyxperiadev/gerrit-events | /*
* The MIT License
*
* Copyright 2013 Jyrki Puttonen. All rights reserved.
* Copyright 2013 Sony Mobile Communications AB. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.sonymobile.tools.gerrit.gerritevents.dto.rest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//CS IGNORE LineLength FOR NEXT 6 LINES. REASON: JavaDoc.
/**
* What to send as input to the actual review.
*
* @see Gerrit Documentation <a href="https://gerrit-documentation.storage.googleapis.com/Documentation/2.13/rest-api-changes.html#set-review">1</a>, <a href="https://gerrit-documentation.storage.googleapis.com/Documentation/2.13/rest-api-changes.html#review-input">2</a>
*/
public class ReviewInput {
final String message;
final Map<String, Integer> labels = new HashMap<String, Integer>();
final Map<String, List<LineComment>> comments = new HashMap<String, List<LineComment>>();
Notify notify;
String tag;
/**
* Standard Constructor.
*
* @param message message
* @param labelName label
* @param labelValue value
*/
public ReviewInput(String message, String labelName, int labelValue) {
this(message, Collections.singleton(new ReviewLabel(labelName, labelValue)));
}
/**
* Standard Constructor.
*
* @param message message
* @param labels labels
*/
public ReviewInput(String message, ReviewLabel... labels) {
this(message, Arrays.asList(labels));
}
/**
* Standard Constructor.
*
* @param message message
* @param labels labels
*/
public ReviewInput(String message, Collection<ReviewLabel> labels) {
this(message, labels, Collections.<CommentedFile>emptyList());
}
/**
* Standard Constructor.
*
* @param message message
* @param commentedFiles file comments
* @param labels label
*/
public ReviewInput(String message, Collection<CommentedFile> commentedFiles, ReviewLabel... labels) {
this(message, Arrays.asList(labels), commentedFiles);
}
/**
* Standard Constructor.
*
* @param message message
* @param labels labels
* @param commentedFiles file comments
*/
public ReviewInput(String message, Collection<ReviewLabel> labels, Collection<CommentedFile> commentedFiles) {
this.message = message;
for (ReviewLabel label : labels) {
this.labels.put(label.getName(), label.getValue());
}
for (CommentedFile file : commentedFiles) {
if (!comments.containsKey(file.getFileName())) {
comments.put(file.getFileName(), new ArrayList<LineComment>());
}
comments.get(file.getFileName()).addAll(file.getLineComments());
}
}
/**
* Sets the 'notify' value. Defines to whom email notifications should be sent after the review is stored.
*
* @param value the value to set.
* @return this instance for convenience
*/
public ReviewInput setNotify(Notify value) {
this.notify = value;
return this;
}
/**
* Sets the 'tag' value. Defines an optional tag to the review. This enables filtering out automatic comments.
*
* @param value the value to set.
* @return this instance for convenience
*/
public ReviewInput setTag(String value) {
this.tag = value;
return this;
}
}
| src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/rest/ReviewInput.java | /*
* The MIT License
*
* Copyright 2013 Jyrki Puttonen. All rights reserved.
* Copyright 2013 Sony Mobile Communications AB. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.sonymobile.tools.gerrit.gerritevents.dto.rest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//CS IGNORE LineLength FOR NEXT 6 LINES. REASON: JavaDoc.
/**
* What to send as input to the actual review.
*
* @see Gerrit Documentation <a href="https://gerrit-documentation.storage.googleapis.com/Documentation/2.13/rest-api-changes.html#set-review">1</a>, <a href="https://gerrit-documentation.storage.googleapis.com/Documentation/2.13/rest-api-changes.html#review-input">2</a>
*/
public class ReviewInput {
final String message;
final Map<String, Integer> labels = new HashMap<String, Integer>();
final Map<String, List<LineComment>> comments = new HashMap<String, List<LineComment>>();
Notify notify;
String tag;
/**
* Standard Constructor.
*
* @param message message
* @param labelName label
* @param labelValue value
*/
public ReviewInput(String message, String labelName, int labelValue) {
this(message, Collections.singleton(new ReviewLabel(labelName, labelValue)));
}
/**
* Standard Constructor.
*
* @param message message
* @param labels labels
*/
public ReviewInput(String message, ReviewLabel... labels) {
this(message, Arrays.asList(labels));
}
/**
* Standard Constructor.
*
* @param message message
* @param labels labels
*/
public ReviewInput(String message, Collection<ReviewLabel> labels) {
this(message, labels, Collections.<CommentedFile>emptyList());
}
/**
* Standard Constructor.
*
* @param message message
* @param commentedFiles file comments
* @param labels label
*/
public ReviewInput(String message, Collection<CommentedFile> commentedFiles, ReviewLabel... labels) {
this(message, Arrays.asList(labels), commentedFiles);
}
/**
* Standard Constructor.
*
* @param message message
* @param labels labels
* @param commentedFiles file comments
*/
public ReviewInput(String message, Collection<ReviewLabel> labels, Collection<CommentedFile> commentedFiles) {
this.message = message;
for (ReviewLabel label : labels) {
this.labels.put(label.getName(), label.getValue());
}
for (CommentedFile file : commentedFiles) {
if (!comments.containsKey(file.getFileName())) {
comments.put(file.getFileName(), new ArrayList<LineComment>());
}
comments.get(file.getFileName()).addAll(file.getLineComments());
}
}
/**
* Sets the 'notify' value. Defines to whom email notifications should be sent after the review is stored.
*
* @param value the value to set.
* @return this instance for convenience
*/
public ReviewInput setNotify(Notify value) {
this.notify = value;
return this;
}
/**
* Sets the 'tag' value. Defines an optional tag to the review. This enables filtering out automatic comments.
*
* @param value the value to set.
* @return this instance for convenience
*/
public ReviewInput setTag(String value) {
this.tag = value;
return this;
}
}
| Update ReviewInput.java
trailing space fix | src/main/java/com/sonymobile/tools/gerrit/gerritevents/dto/rest/ReviewInput.java | Update ReviewInput.java |
|
Java | mit | 9dbb0b7e386bb0ff25cae3dd1288b70acedba01d | 0 | NucleusPowered/Nucleus,NucleusPowered/Nucleus,NucleusPowered/Nucleus,NucleusPowered/Nucleus | /*
* This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file
* at the root of this project for more details.
*/
package io.github.nucleuspowered.nucleus.modules.teleport.commands;
import io.github.nucleuspowered.nucleus.api.teleport.data.TeleportResult;
import io.github.nucleuspowered.nucleus.modules.teleport.TeleportPermissions;
import io.github.nucleuspowered.nucleus.modules.teleport.config.TeleportConfig;
import io.github.nucleuspowered.nucleus.modules.teleport.services.PlayerTeleporterService;
import io.github.nucleuspowered.nucleus.scaffold.command.ICommandContext;
import io.github.nucleuspowered.nucleus.scaffold.command.ICommandExecutor;
import io.github.nucleuspowered.nucleus.scaffold.command.ICommandResult;
import io.github.nucleuspowered.nucleus.scaffold.command.NucleusParameters;
import io.github.nucleuspowered.nucleus.scaffold.command.annotation.Command;
import io.github.nucleuspowered.nucleus.scaffold.command.annotation.EssentialsEquivalent;
import io.github.nucleuspowered.nucleus.services.INucleusServiceCollection;
import io.github.nucleuspowered.nucleus.services.interfaces.IReloadableService;
import org.spongepowered.api.command.exception.CommandException;;
import org.spongepowered.api.command.args.CommandElement;
import org.spongepowered.api.command.args.GenericArguments;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.entity.living.player.User;
/**
* NOTE: TeleportHere is considered an admin command, as there is a potential
* for abuse for non-admin players trying to pull players. No cost or warmups
* will be applied. /tpahere should be used instead in these circumstances.
*/
@EssentialsEquivalent(value = {"tphere", "s", "tpohere"}, isExact = false,
notes = "If you have permission, this will override '/tptoggle' automatically.")
@Command(
aliases = {"tphere", "tph"},
basePermission = TeleportPermissions.BASE_TPHERE,
commandDescriptionKey = "tphere",
associatedPermissions = {
TeleportPermissions.TPHERE_OFFLINE,
TeleportPermissions.TPTOGGLE_EXEMPT
}
)
public class TeleportHereCommand implements ICommandExecutor, IReloadableService.Reloadable {
private boolean isDefaultQuiet = false;
@Override public void onReload(final INucleusServiceCollection serviceCollection) {
this.isDefaultQuiet =
serviceCollection.configProvider()
.getModuleConfig(TeleportConfig.class)
.isDefaultQuiet();
}
@Override
public CommandElement[] parameters(final INucleusServiceCollection serviceCollection) {
return new CommandElement[] {
GenericArguments.flags().flag("q", "-quiet").buildWith(
IfConditionElseArgument.permission(
serviceCollection.permissionService(),
TeleportPermissions.TPHERE_OFFLINE,
NucleusParameters.ONE_USER_PLAYER_KEY.get(serviceCollection),
NucleusParameters.ONE_PLAYER.get(serviceCollection)))
};
}
@Override public ICommandResult execute(final ICommandContext context) throws CommandException {
final boolean beQuiet = context.getOne("q", Boolean.class).orElse(this.isDefaultQuiet);
final User target = context.requireOne(NucleusParameters.Keys.PLAYER, User.class);
final PlayerTeleporterService sts = context.getServiceCollection().getServiceUnchecked(PlayerTeleporterService.class);
if (target.getPlayer().isPresent()) {
final Player to = target.getPlayer().get();
final TeleportResult result = sts.teleportWithMessage(
context.getIfPlayer(),
to,
context.getIfPlayer(),
false,
beQuiet,
false
);
return result.isSuccessful() ? context.successResult() : context.failResult();
} else {
if (!context.testPermission(TeleportPermissions.TPHERE_OFFLINE)) {
return context.errorResult("command.tphere.noofflineperms");
}
final Player src = context.getIfPlayer();
// Update the offline player's next location
target.setLocation(src.getPosition(), src.getWorld().getUniqueId());
context.sendMessage("command.tphere.offlinesuccess", target.getName());
}
return context.successResult();
}
}
| nucleus-modules/src/main/java/io/github/nucleuspowered/nucleus/modules/teleport/commands/TeleportHereCommand.java | /*
* This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file
* at the root of this project for more details.
*/
package io.github.nucleuspowered.nucleus.modules.teleport.commands;
import io.github.nucleuspowered.nucleus.api.teleport.data.TeleportResult;
import io.github.nucleuspowered.nucleus.modules.teleport.TeleportPermissions;
import io.github.nucleuspowered.nucleus.modules.teleport.config.TeleportConfig;
import io.github.nucleuspowered.nucleus.modules.teleport.services.PlayerTeleporterService;
import io.github.nucleuspowered.nucleus.scaffold.command.ICommandContext;
import io.github.nucleuspowered.nucleus.scaffold.command.ICommandExecutor;
import io.github.nucleuspowered.nucleus.scaffold.command.ICommandResult;
import io.github.nucleuspowered.nucleus.scaffold.command.NucleusParameters;
import io.github.nucleuspowered.nucleus.scaffold.command.annotation.Command;
import io.github.nucleuspowered.nucleus.scaffold.command.annotation.EssentialsEquivalent;
import io.github.nucleuspowered.nucleus.services.INucleusServiceCollection;
import io.github.nucleuspowered.nucleus.services.interfaces.IReloadableService;
import org.spongepowered.api.command.exception.CommandException;;
import org.spongepowered.api.command.args.CommandElement;
import org.spongepowered.api.command.args.GenericArguments;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.entity.living.player.User;
/**
* NOTE: TeleportHere is considered an admin command, as there is a potential
* for abuse for non-admin players trying to pull players. No cost or warmups
* will be applied. /tpahere should be used instead in these circumstances.
*/
@EssentialsEquivalent(value = {"tphere", "s", "tpohere"}, isExact = false,
notes = "If you have permission, this will override '/tptoggle' automatically.")
@Command(
aliases = {"tphere", "tph"},
basePermission = TeleportPermissions.BASE_TPHERE,
commandDescriptionKey = "tphere",
associatedPermissions = {
TeleportPermissions.TPHERE_OFFLINE,
TeleportPermissions.TPTOGGLE_EXEMPT
}
)
public class TeleportHereCommand implements ICommandExecutor, IReloadableService.Reloadable {
private boolean isDefaultQuiet = false;
@Override public void onReload(final INucleusServiceCollection serviceCollection) {
this.isDefaultQuiet =
serviceCollection.configProvider()
.getModuleConfig(TeleportConfig.class)
.isDefaultQuiet();
}
@Override
public CommandElement[] parameters(final INucleusServiceCollection serviceCollection) {
return new CommandElement[] {
GenericArguments.flags().flag("q", "-quiet").buildWith(
IfConditionElseArgument.permission(
serviceCollection.permissionService(),
TeleportPermissions.TPHERE_OFFLINE,
NucleusParameters.ONE_USER_PLAYER_KEY.get(serviceCollection),
NucleusParameters.ONE_PLAYER.get(serviceCollection)))
};
}
@Override public ICommandResult execute(final ICommandContext context) throws CommandException {
final boolean beQuiet = context.getOne("q", Boolean.class).orElse(this.isDefaultQuiet);
final User target = context.requireOne(NucleusParameters.Keys.PLAYER, User.class);
final PlayerTeleporterService sts = context.getServiceCollection().getServiceUnchecked(PlayerTeleporterService.class);
if (target.getPlayer().isPresent()) {
final Player to = target.getPlayer().get();
final TeleportResult result = sts.teleportWithMessage(
context.getIfPlayer(),
to,
context.getIfPlayer(),
false,
beQuiet,
false
);
return result.isSuccessful() ? context.successResult() : context.failResult();
} else {
if (context.testPermission(TeleportPermissions.TPHERE_OFFLINE)) {
return context.errorResult("command.tphere.noofflineperms");
}
final Player src = context.getIfPlayer();
// Update the offline player's next location
target.setLocation(src.getPosition(), src.getWorld().getUniqueId());
context.sendMessage("command.tphere.offlinesuccess", target.getName());
}
return context.successResult();
}
}
| Fix TP here permission failing
| nucleus-modules/src/main/java/io/github/nucleuspowered/nucleus/modules/teleport/commands/TeleportHereCommand.java | Fix TP here permission failing |
|
Java | mit | 634b826b1f5b7bd15dd10048069ed18b8bfc3564 | 0 | InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service,InnovateUKGitHub/innovation-funding-service | package org.innovateuk.ifs.application.security;
import org.innovateuk.ifs.application.resource.ApplicationResource;
import org.innovateuk.ifs.commons.security.PermissionRule;
import org.innovateuk.ifs.commons.security.PermissionRules;
import org.innovateuk.ifs.competition.resource.CompetitionResource;
import org.innovateuk.ifs.competition.resource.CompetitionStatus;
import org.innovateuk.ifs.project.domain.Project;
import org.innovateuk.ifs.project.repository.ProjectRepository;
import org.innovateuk.ifs.security.BasePermissionRules;
import org.innovateuk.ifs.user.domain.ProcessRole;
import org.innovateuk.ifs.user.domain.Role;
import org.innovateuk.ifs.user.repository.RoleRepository;
import org.innovateuk.ifs.user.resource.UserResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.innovateuk.ifs.competition.resource.CompetitionStatus.PROJECT_SETUP;
import static org.innovateuk.ifs.security.SecurityRuleUtil.*;
import static org.innovateuk.ifs.user.resource.UserRoleType.*;
@PermissionRules
@Component
public class ApplicationPermissionRules extends BasePermissionRules {
public static final List<CompetitionStatus> ASSESSOR_FEEDBACK_PUBLISHED_STATES = singletonList(PROJECT_SETUP);
@Autowired
private RoleRepository roleRepository;
@Autowired
private ProjectRepository projectRepository;
@PermissionRule(value = "READ_RESEARCH_PARTICIPATION_PERCENTAGE", description = "The consortium can see the participation percentage for their applications")
public boolean consortiumCanSeeTheResearchParticipantPercentage(final ApplicationResource applicationResource, UserResource user) {
final boolean isLeadApplicant = isLeadApplicant(applicationResource.getId(), user);
final boolean isCollaborator = isCollaborator(applicationResource.getId(), user);
return isLeadApplicant || isCollaborator;
}
@PermissionRule(value = "READ_RESEARCH_PARTICIPATION_PERCENTAGE", description = "The assessor can see the participation percentage for applications they assess")
public boolean assessorCanSeeTheResearchParticipantPercentageInApplicationsTheyAssess(final ApplicationResource applicationResource, UserResource user) {
return isAssessor(applicationResource.getId(), user);
}
@PermissionRule(value = "READ_RESEARCH_PARTICIPATION_PERCENTAGE", description = "The internal users can see the participation percentage for applications they assess")
public boolean internalUsersCanSeeTheResearchParticipantPercentageInApplications(final ApplicationResource applicationResource, UserResource user) {
return isInternal(user);
}
@PermissionRule(value = "READ_FINANCE_TOTALS",
description = "The consortium can see the application finance totals",
additionalComments = "This rule secures ApplicationResource which can contain more information than this rule should allow. Consider a new cut down object based on ApplicationResource")
public boolean consortiumCanSeeTheApplicationFinanceTotals(final ApplicationResource applicationResource, final UserResource user) {
final boolean isLeadApplicant = isLeadApplicant(applicationResource.getId(), user);
final boolean isCollaborator = isCollaborator(applicationResource.getId(), user);
return isLeadApplicant || isCollaborator;
}
@PermissionRule(value = "READ_FINANCE_DETAILS",
description = "The consortium can see the application finance details",
additionalComments = "This rule secures ApplicationResource which can contain more information than this rule should allow. Consider a new cut down object based on ApplicationResource")
public boolean leadApplicantCanSeeTheApplicationFinanceDetails(final ApplicationResource applicationResource, final UserResource user) {
return isLeadApplicant(applicationResource.getId(), user);
}
@PermissionRule(value = "READ_FINANCE_TOTALS",
description = "The assessor can see the application finance totals in the applications they assess",
additionalComments = "This rule secures ApplicationResource which can contain more information than this rule should allow. Consider a new cut down object based on ApplicationResource")
public boolean assessorCanSeeTheApplicationFinancesTotals(final ApplicationResource applicationResource, final UserResource user) {
return isAssessor(applicationResource.getId(), user);
}
@PermissionRule(value = "READ_FINANCE_TOTALS",
description = "A project finance user can see application finances for organisations",
additionalComments = "This rule secures ApplicationResource which can contain more information than this rule should allow. Consider a new cut down object based on ApplicationResource")
public boolean projectFinanceUserCanSeeApplicationFinancesTotals(final ApplicationResource applicationResource, final UserResource user) {
return isProjectFinanceUser(user);
}
@PermissionRule(value = "READ_FINANCE_TOTALS",
description = "A CSS user can see application finances for organisations",
additionalComments = "This rule secures ApplicationResource which can contain more information than this rule should allow. Consider a new cut down object based on ApplicationResource")
public boolean supportUserCanSeeApplicationFinancesTotals(final ApplicationResource applicationResource, final UserResource user) {
return isSupport(user);
}
@PermissionRule(value = "READ_FINANCE_TOTALS",
description = "An innovation lead user can see application finances for organisations",
additionalComments = "This rule secures ApplicationResource which can contain more information than this rule should allow. Consider a new cut down object based on ApplicationResource")
public boolean innovationLeadCanSeeApplicationFinancesTotals(final ApplicationResource applicationResource, final UserResource user) {
return isInnovationLead(user);
}
@PermissionRule(value = "APPLICATION_SUBMITTED_NOTIFICATION", description = "A lead applicant can send the notification of a submitted application")
public boolean aLeadApplicantCanSendApplicationSubmittedNotification(final ApplicationResource applicationResource, final UserResource user) {
return isLeadApplicant(applicationResource.getId(), user);
}
@PermissionRule(value = "READ_FINANCE_TOTALS",
description = "A comp admin can see application finances for organisations",
additionalComments = "This rule secures ApplicationResource which can contain more information than this rule should allow. Consider a new cut down object based on ApplicationResource")
public boolean compAdminCanSeeApplicationFinancesTotals(final ApplicationResource applicationResource, final UserResource user) {
return isCompAdmin(user);
}
@PermissionRule(value = "READ", description = "A user can see an application resource which they are connected to")
public boolean usersConnectedToTheApplicationCanView(ApplicationResource application, UserResource user) {
return userIsConnectedToApplicationResource(application, user);
}
@PermissionRule(value = "READ", description = "Internal users can see application resources")
public boolean internalUsersCanViewApplications(final ApplicationResource application, final UserResource user) {
return !isInnovationLead(user) && isInternal(user);
}
@PermissionRule(value = "READ", description = "Internal users can see application resources")
public boolean innovationLeadAssginedToCompetitionCanViewApplications(final ApplicationResource application, final UserResource user) {
return application != null && application.getCompetition() != null && userIsInnovationLeadOnCompetition(application.getCompetition(), user.getId());
}
@PermissionRule(value = "READ", description = "Project Partners can see applications that are linked to their Projects")
public boolean projectPartnerCanViewApplicationsLinkedToTheirProjects(final ApplicationResource application, final UserResource user) {
Project linkedProject = projectRepository.findOneByApplicationId(application.getId());
if (linkedProject == null) {
return false;
}
return isPartner(linkedProject.getId(), user.getId());
}
@PermissionRule(value = "UPDATE", description = "A user can update their own application if they are a lead applicant or collaborator of the application")
public boolean applicantCanUpdateApplicationResource(ApplicationResource application, UserResource user) {
List<Role> allApplicantRoles = roleRepository.findByNameIn(asList(LEADAPPLICANT.getName(), COLLABORATOR.getName()));
List<ProcessRole> applicantProcessRoles = processRoleRepository.findByUserIdAndRoleInAndApplicationId(user.getId(), allApplicantRoles, application.getId());
return !applicantProcessRoles.isEmpty();
}
@PermissionRule(value = "READ_AVAILABLE_INNOVATION_AREAS", description = "A user can view the Innovation Areas that are available to their applications")
public boolean usersConnectedToTheApplicationCanViewInnovationAreas(ApplicationResource applicationResource, final UserResource user) {
return usersConnectedToTheApplicationCanView(applicationResource, user);
}
@PermissionRule(value = "UPDATE_INNOVATION_AREA", description = "A lead applicant can update their application's Innovation Area")
public boolean leadApplicantCanUpdateApplicationResource(ApplicationResource applicationResource, UserResource user) {
return isLeadApplicant(applicationResource.getId(), user);
}
@PermissionRule(value = "UPDATE_RESEARCH_CATEGORY", description = "A lead applicant can update their application's Research Category")
public boolean leadApplicantCanUpdateResearchCategory(ApplicationResource applicationResource, UserResource user) {
return isLeadApplicant(applicationResource.getId(), user);
}
@PermissionRule(value = "UPDATE_APPLICATION_STATE", description = "A lead applicant can update the state of their own application")
public boolean leadApplicantCanUpdateApplicationState(final ApplicationResource applicationResource, final UserResource user) {
return isLeadApplicant(applicationResource.getId(), user);
}
@PermissionRule(value = "UPDATE_APPLICATION_STATE", description = "A comp admin can update the state of an application")
public boolean compAdminCanUpdateApplicationState(final ApplicationResource applicationResource, final UserResource user) {
return isCompAdmin(user);
}
@PermissionRule(
value = "UPLOAD_ASSESSOR_FEEDBACK",
description = "An Internal user can upload Assessor Feedback documentation for an Application whilst " +
"the Application's Competition is in Funders' Panel or Assessor Feedback state",
particularBusinessState = "Application's Competition Status = 'Funders Panel' or 'Assessor Feedback'")
public boolean internalUserCanUploadAssessorFeedbackToApplicationInFundersPanelOrAssessorFeedbackState(ApplicationResource application, UserResource user) {
return isInternal(user) && application.isInEditableAssessorFeedbackCompetitionState();
}
@PermissionRule(
value = "REMOVE_ASSESSOR_FEEDBACK",
description = "A Comp Admin user can remove Assessor Feedback documentation so long as the Feedback has not yet been published",
particularBusinessState = "Application's Competition Status != 'Project Setup' or beyond")
public boolean compAdminCanRemoveAssessorFeedbackThatHasNotYetBeenPublished(ApplicationResource application, UserResource user) {
return isCompAdmin(user) && !application.isInPublishedAssessorFeedbackCompetitionState();
}
@PermissionRule(
value = "REMOVE_ASSESSOR_FEEDBACK",
description = "A Project Finance user can remove Assessor Feedback documentation so long as the Feedback has not yet been published",
particularBusinessState = "Application's Competition Status != 'Project Setup' or beyond")
public boolean projectFinanceUserCanRemoveAssessorFeedbackThatHasNotYetBeenPublished(ApplicationResource application, UserResource user) {
return isProjectFinanceUser(user) && !application.isInPublishedAssessorFeedbackCompetitionState();
}
@PermissionRule(
value = "DOWNLOAD_ASSESSOR_FEEDBACK",
description = "An Internal user can see and download Assessor Feedback at any time for any Application")
public boolean internalUserCanSeeAndDownloadAllAssessorFeedbackAtAnyTime(ApplicationResource application, UserResource user) {
return isInternal(user);
}
@PermissionRule(
value = "DOWNLOAD_ASSESSOR_FEEDBACK",
description = "A member of the Application Team can see and download Assessor Feedback attached to their Application when it has been published",
particularBusinessState = "Application's Competition Status = 'Project Setup' or beyond")
public boolean applicationTeamCanSeeAndDownloadPublishedAssessorFeedbackForTheirApplications(ApplicationResource application, UserResource user) {
return application.isInPublishedAssessorFeedbackCompetitionState() && isMemberOfProjectTeam(application.getId(), user);
}
boolean userIsConnectedToApplicationResource(ApplicationResource application, UserResource user) {
ProcessRole processRole = processRoleRepository.findByUserIdAndApplicationId(user.getId(), application.getId());
return processRole != null;
}
@PermissionRule(value = "CREATE",
description = "Any logged in user with global roles or user with system registrar role can create an application but only for open competitions",
particularBusinessState = "Competition is in Open state")
public boolean userCanCreateNewApplication(CompetitionResource competition, UserResource user) {
return competition.isOpen() && (user.hasRole(APPLICANT) || user.hasRole(SYSTEM_REGISTRATION_USER));
}
}
| ifs-data-layer/ifs-data-service/src/main/java/org/innovateuk/ifs/application/security/ApplicationPermissionRules.java | package org.innovateuk.ifs.application.security;
import org.innovateuk.ifs.application.resource.ApplicationResource;
import org.innovateuk.ifs.commons.security.PermissionRule;
import org.innovateuk.ifs.commons.security.PermissionRules;
import org.innovateuk.ifs.competition.resource.CompetitionResource;
import org.innovateuk.ifs.competition.resource.CompetitionStatus;
import org.innovateuk.ifs.project.domain.Project;
import org.innovateuk.ifs.project.repository.ProjectRepository;
import org.innovateuk.ifs.security.BasePermissionRules;
import org.innovateuk.ifs.user.domain.ProcessRole;
import org.innovateuk.ifs.user.domain.Role;
import org.innovateuk.ifs.user.repository.RoleRepository;
import org.innovateuk.ifs.user.resource.UserResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.innovateuk.ifs.competition.resource.CompetitionStatus.PROJECT_SETUP;
import static org.innovateuk.ifs.security.SecurityRuleUtil.*;
import static org.innovateuk.ifs.user.resource.UserRoleType.*;
@PermissionRules
@Component
public class ApplicationPermissionRules extends BasePermissionRules {
public static final List<CompetitionStatus> ASSESSOR_FEEDBACK_PUBLISHED_STATES = singletonList(PROJECT_SETUP);
@Autowired
private RoleRepository roleRepository;
@Autowired
private ProjectRepository projectRepository;
@PermissionRule(value = "READ_RESEARCH_PARTICIPATION_PERCENTAGE", description = "The consortium can see the participation percentage for their applications")
public boolean consortiumCanSeeTheResearchParticipantPercentage(final ApplicationResource applicationResource, UserResource user) {
final boolean isLeadApplicant = isLeadApplicant(applicationResource.getId(), user);
final boolean isCollaborator = isCollaborator(applicationResource.getId(), user);
return isLeadApplicant || isCollaborator;
}
@PermissionRule(value = "READ_RESEARCH_PARTICIPATION_PERCENTAGE", description = "The assessor can see the participation percentage for applications they assess")
public boolean assessorCanSeeTheResearchParticipantPercentageInApplicationsTheyAssess(final ApplicationResource applicationResource, UserResource user) {
return isAssessor(applicationResource.getId(), user);
}
@PermissionRule(value = "READ_RESEARCH_PARTICIPATION_PERCENTAGE", description = "The internal users can see the participation percentage for applications they assess")
public boolean internalUsersCanSeeTheResearchParticipantPercentageInApplications(final ApplicationResource applicationResource, UserResource user) {
return isInternal(user);
}
@PermissionRule(value = "READ_FINANCE_TOTALS",
description = "The consortium can see the application finance totals",
additionalComments = "This rule secures ApplicationResource which can contain more information than this rule should allow. Consider a new cut down object based on ApplicationResource")
public boolean consortiumCanSeeTheApplicationFinanceTotals(final ApplicationResource applicationResource, final UserResource user) {
final boolean isLeadApplicant = isLeadApplicant(applicationResource.getId(), user);
final boolean isCollaborator = isCollaborator(applicationResource.getId(), user);
return isLeadApplicant || isCollaborator;
}
@PermissionRule(value = "READ_FINANCE_DETAILS",
description = "The consortium can see the application finance details",
additionalComments = "This rule secures ApplicationResource which can contain more information than this rule should allow. Consider a new cut down object based on ApplicationResource")
public boolean leadApplicantCanSeeTheApplicationFinanceDetails(final ApplicationResource applicationResource, final UserResource user) {
return isLeadApplicant(applicationResource.getId(), user);
}
@PermissionRule(value = "READ_FINANCE_TOTALS",
description = "The assessor can see the application finance totals in the applications they assess",
additionalComments = "This rule secures ApplicationResource which can contain more information than this rule should allow. Consider a new cut down object based on ApplicationResource")
public boolean assessorCanSeeTheApplicationFinancesTotals(final ApplicationResource applicationResource, final UserResource user) {
return isAssessor(applicationResource.getId(), user);
}
@PermissionRule(value = "READ_FINANCE_TOTALS",
description = "A project finance user can see application finances for organisations",
additionalComments = "This rule secures ApplicationResource which can contain more information than this rule should allow. Consider a new cut down object based on ApplicationResource")
public boolean projectFinanceUserCanSeeApplicationFinancesTotals(final ApplicationResource applicationResource, final UserResource user) {
return isProjectFinanceUser(user);
}
@PermissionRule(value = "READ_FINANCE_TOTALS",
description = "A CSS user can see application finances for organisations",
additionalComments = "This rule secures ApplicationResource which can contain more information than this rule should allow. Consider a new cut down object based on ApplicationResource")
public boolean supportUserCanSeeApplicationFinancesTotals(final ApplicationResource applicationResource, final UserResource user) {
return isSupport(user);
}
@PermissionRule(value = "READ_FINANCE_TOTALS",
description = "An innovation lead user can see application finances for organisations",
additionalComments = "This rule secures ApplicationResource which can contain more information than this rule should allow. Consider a new cut down object based on ApplicationResource")
public boolean innovationLeadCanSeeApplicationFinancesTotals(final ApplicationResource applicationResource, final UserResource user) {
return isInnovationLead(user);
}
@PermissionRule(value = "APPLICATION_SUBMITTED_NOTIFICATION", description = "A lead applicant can send the notification of a submitted application")
public boolean aLeadApplicantCanSendApplicationSubmittedNotification(final ApplicationResource applicationResource, final UserResource user) {
return isLeadApplicant(applicationResource.getId(), user);
}
@PermissionRule(value = "READ_FINANCE_TOTALS",
description = "A comp admin can see application finances for organisations",
additionalComments = "This rule secures ApplicationResource which can contain more information than this rule should allow. Consider a new cut down object based on ApplicationResource")
public boolean compAdminCanSeeApplicationFinancesTotals(final ApplicationResource applicationResource, final UserResource user) {
return isCompAdmin(user);
}
@PermissionRule(value = "READ", description = "A user can see an application resource which they are connected to")
public boolean usersConnectedToTheApplicationCanView(ApplicationResource application, UserResource user) {
return userIsConnectedToApplicationResource(application, user);
}
@PermissionRule(value = "READ", description = "Internal users can see application resources")
public boolean internalUsersCanViewApplications(final ApplicationResource application, final UserResource user) {
return !isInnovationLead(user) && isInternal(user);
}
@PermissionRule(value = "READ", description = "Internal users can see application resources")
public boolean innovationLeadAssginedToCompetitionCanViewApplications(final ApplicationResource application, final UserResource user) {
return userIsInnovationLeadOnCompetition(application.getCompetition(), user.getId());
}
@PermissionRule(value = "READ", description = "Project Partners can see applications that are linked to their Projects")
public boolean projectPartnerCanViewApplicationsLinkedToTheirProjects(final ApplicationResource application, final UserResource user) {
Project linkedProject = projectRepository.findOneByApplicationId(application.getId());
if (linkedProject == null) {
return false;
}
return isPartner(linkedProject.getId(), user.getId());
}
@PermissionRule(value = "UPDATE", description = "A user can update their own application if they are a lead applicant or collaborator of the application")
public boolean applicantCanUpdateApplicationResource(ApplicationResource application, UserResource user) {
List<Role> allApplicantRoles = roleRepository.findByNameIn(asList(LEADAPPLICANT.getName(), COLLABORATOR.getName()));
List<ProcessRole> applicantProcessRoles = processRoleRepository.findByUserIdAndRoleInAndApplicationId(user.getId(), allApplicantRoles, application.getId());
return !applicantProcessRoles.isEmpty();
}
@PermissionRule(value = "READ_AVAILABLE_INNOVATION_AREAS", description = "A user can view the Innovation Areas that are available to their applications")
public boolean usersConnectedToTheApplicationCanViewInnovationAreas(ApplicationResource applicationResource, final UserResource user) {
return usersConnectedToTheApplicationCanView(applicationResource, user);
}
@PermissionRule(value = "UPDATE_INNOVATION_AREA", description = "A lead applicant can update their application's Innovation Area")
public boolean leadApplicantCanUpdateApplicationResource(ApplicationResource applicationResource, UserResource user) {
return isLeadApplicant(applicationResource.getId(), user);
}
@PermissionRule(value = "UPDATE_RESEARCH_CATEGORY", description = "A lead applicant can update their application's Research Category")
public boolean leadApplicantCanUpdateResearchCategory(ApplicationResource applicationResource, UserResource user) {
return isLeadApplicant(applicationResource.getId(), user);
}
@PermissionRule(value = "UPDATE_APPLICATION_STATE", description = "A lead applicant can update the state of their own application")
public boolean leadApplicantCanUpdateApplicationState(final ApplicationResource applicationResource, final UserResource user) {
return isLeadApplicant(applicationResource.getId(), user);
}
@PermissionRule(value = "UPDATE_APPLICATION_STATE", description = "A comp admin can update the state of an application")
public boolean compAdminCanUpdateApplicationState(final ApplicationResource applicationResource, final UserResource user) {
return isCompAdmin(user);
}
@PermissionRule(
value = "UPLOAD_ASSESSOR_FEEDBACK",
description = "An Internal user can upload Assessor Feedback documentation for an Application whilst " +
"the Application's Competition is in Funders' Panel or Assessor Feedback state",
particularBusinessState = "Application's Competition Status = 'Funders Panel' or 'Assessor Feedback'")
public boolean internalUserCanUploadAssessorFeedbackToApplicationInFundersPanelOrAssessorFeedbackState(ApplicationResource application, UserResource user) {
return isInternal(user) && application.isInEditableAssessorFeedbackCompetitionState();
}
@PermissionRule(
value = "REMOVE_ASSESSOR_FEEDBACK",
description = "A Comp Admin user can remove Assessor Feedback documentation so long as the Feedback has not yet been published",
particularBusinessState = "Application's Competition Status != 'Project Setup' or beyond")
public boolean compAdminCanRemoveAssessorFeedbackThatHasNotYetBeenPublished(ApplicationResource application, UserResource user) {
return isCompAdmin(user) && !application.isInPublishedAssessorFeedbackCompetitionState();
}
@PermissionRule(
value = "REMOVE_ASSESSOR_FEEDBACK",
description = "A Project Finance user can remove Assessor Feedback documentation so long as the Feedback has not yet been published",
particularBusinessState = "Application's Competition Status != 'Project Setup' or beyond")
public boolean projectFinanceUserCanRemoveAssessorFeedbackThatHasNotYetBeenPublished(ApplicationResource application, UserResource user) {
return isProjectFinanceUser(user) && !application.isInPublishedAssessorFeedbackCompetitionState();
}
@PermissionRule(
value = "DOWNLOAD_ASSESSOR_FEEDBACK",
description = "An Internal user can see and download Assessor Feedback at any time for any Application")
public boolean internalUserCanSeeAndDownloadAllAssessorFeedbackAtAnyTime(ApplicationResource application, UserResource user) {
return isInternal(user);
}
@PermissionRule(
value = "DOWNLOAD_ASSESSOR_FEEDBACK",
description = "A member of the Application Team can see and download Assessor Feedback attached to their Application when it has been published",
particularBusinessState = "Application's Competition Status = 'Project Setup' or beyond")
public boolean applicationTeamCanSeeAndDownloadPublishedAssessorFeedbackForTheirApplications(ApplicationResource application, UserResource user) {
return application.isInPublishedAssessorFeedbackCompetitionState() && isMemberOfProjectTeam(application.getId(), user);
}
boolean userIsConnectedToApplicationResource(ApplicationResource application, UserResource user) {
ProcessRole processRole = processRoleRepository.findByUserIdAndApplicationId(user.getId(), application.getId());
return processRole != null;
}
@PermissionRule(value = "CREATE",
description = "Any logged in user with global roles or user with system registrar role can create an application but only for open competitions",
particularBusinessState = "Competition is in Open state")
public boolean userCanCreateNewApplication(CompetitionResource competition, UserResource user) {
return competition.isOpen() && (user.hasRole(APPLICANT) || user.hasRole(SYSTEM_REGISTRATION_USER));
}
}
| IFS-191 adding null checking to permission rules
| ifs-data-layer/ifs-data-service/src/main/java/org/innovateuk/ifs/application/security/ApplicationPermissionRules.java | IFS-191 adding null checking to permission rules |
|
Java | mit | 9075702f170e13e1ff1a00e4e75365990c7ec8f7 | 0 | Mangopay/mangopay2-java-sdk,Mangopay/mangopay2-java-sdk | package com.mangopay.core;
import com.mangopay.core.enumerations.*;
import com.mangopay.entities.*;
import com.mangopay.entities.subentities.*;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import java.io.File;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Calendar;
import java.util.List;
import static org.junit.Assert.*;
/**
* UserApiImpl test methods
*/
public class UserApiImplTest extends BaseTest {
@Test
public void createNatural() throws Exception {
UserNatural john = this.getJohn();
assertTrue(john.getId().length() > 0);
assertTrue(john.getPersonType().equals(PersonType.NATURAL));
}
@Test
public void createLegal() throws Exception {
UserLegal matrix = this.getMatrix();
assertTrue(matrix.getId().length() > 0);
assertEquals(matrix.getPersonType(), PersonType.LEGAL);
assertEquals("LU12345678", matrix.getCompanyNumber());
}
@Test
public void createLegalFailsIfRequiredPropsNotProvided() throws Exception {
UserLegal user = new UserLegal();
User ret = null;
try {
ret = this.api.getUserApi().create(user);
Assert.fail("CreateLegal() should throw an exception when required props are not provided");
} catch (ResponseException ex) {
assertNull(ret);
}
}
@Test
public void createLegalPassesIfRequiredPropsProvided() throws Exception {
UserLegal user = new UserLegal();
user.setHeadquartersAddress(new Address());
user.getHeadquartersAddress().setAddressLine1("AddressLine1");
user.getHeadquartersAddress().setAddressLine2("AddressLine2");
user.getHeadquartersAddress().setCity("City");
user.getHeadquartersAddress().setCountry(CountryIso.FR);
user.getHeadquartersAddress().setPostalCode("11222");
user.getHeadquartersAddress().setRegion("Region");
user.setName("SomeOtherSampleOrg");
user.setLegalPersonType(LegalPersonType.BUSINESS);
user.setLegalRepresentativeFirstName("RepFName");
user.setLegalRepresentativeLastName("RepLName");
Calendar c = Calendar.getInstance();
c.set(1975, 12, 21, 0, 0, 0);
user.setLegalRepresentativeBirthday(c.getTimeInMillis() / 1000);
user.setLegalRepresentativeNationality(CountryIso.FR);
user.setLegalRepresentativeCountryOfResidence(CountryIso.FR);
user.setEmail("[email protected]");
user.setCompanyNumber("LU12345678");
User ret = null;
ret = this.api.getUserApi().create(user);
assertTrue("Created successfully after required props set", ret.getId().length() > 0);
assertEqualInputProps(user, ret);
}
@Test
public void getAllUsers() throws Exception {
Sorting sort = new Sorting();
sort.addField("CreationDate", SortDirection.desc);
List<User> users = this.api.getUserApi().getAll(null, sort);
assertTrue(users.get(0).getCreationDate() > users.get(users.size() - 1).getCreationDate());
sort = new Sorting();
sort.addField("CreationDate", SortDirection.asc);
users = this.api.getUserApi().getAll(null, sort);
assertTrue(users.get(0).getCreationDate() < users.get(users.size() - 1).getCreationDate());
}
@Test
public void getNatural() throws Exception {
UserNatural john = this.getJohn();
User user1 = this.api.getUserApi().get(john.getId());
UserNatural user2 = this.api.getUserApi().getNatural(john.getId());
assertTrue(user1.getPersonType().equals(PersonType.NATURAL));
assertTrue(user1.getId().equals(john.getId()));
assertTrue(user2.getPersonType().equals(PersonType.NATURAL));
assertTrue(user2.getId().equals(john.getId()));
assertEqualInputProps(user1, john);
}
@Test
public void getNaturalFailsForLegalUser() throws Exception {
UserLegal matrix = this.getMatrix();
UserNatural user = null;
try {
user = this.api.getUserApi().getNatural(matrix.getId());
Assert.fail("GetUser() should throw an exception when called with legal user id");
} catch (ResponseException ex) {
assertNull(user);
}
}
@Test
public void getLegalFailsForNaturalUser() throws Exception {
UserNatural john = this.getJohn();
User user = null;
try {
user = this.api.getUserApi().getLegal(john.getId());
Assert.fail("GetLegal() should throw an exception when called with natural user id");
} catch (ResponseException ex) {
assertNull(user);
}
}
@Test
public void getLegal() throws Exception {
UserLegal matrix = this.getMatrix();
User user1 = this.api.getUserApi().get(matrix.getId());
User user2 = this.api.getUserApi().getLegal(matrix.getId());
assertEqualInputProps(user1, matrix);
assertEqualInputProps(user2, matrix);
}
@Test
public void updateNatural() throws Exception {
UserNatural john = this.getJohn();
john.setLastName(john.getLastName() + " - CHANGED");
User userSaved = this.api.getUserApi().update(john);
User userFetched = this.api.getUserApi().get(john.getId());
assertEqualInputProps(john, userSaved);
assertEqualInputProps(john, userFetched);
}
@Test
public void updateNaturalNonASCII() throws Exception {
UserNatural john = this.getJohn();
john.setLastName(john.getLastName() + " - CHANGED");
User userSaved = this.api.getUserApi().update(john);
User userFetched = this.api.getUserApi().get(john.getId());
assertEqualInputProps(john, userSaved);
assertEqualInputProps(john, userFetched);
}
@Test
public void updateLegal() throws Exception {
UserLegal matrix = this.getMatrix();
matrix.setLegalRepresentativeLastName(matrix.getLegalRepresentativeLastName() + " - CHANGED");
User userSaved = this.api.getUserApi().update(matrix);
User userFetched = this.api.getUserApi().get(matrix.getId());
assertEqualInputProps(userSaved, matrix);
assertEqualInputProps(userFetched, matrix);
}
@Test
public void updateLegalWithoutAddresses() throws Exception {
UserLegal matrix = this.getMatrixWithoutOptionalFields();
matrix.setLegalRepresentativeLastName(matrix.getLegalRepresentativeLastName() + " - CHANGED");
User userSaved = this.api.getUserApi().update(matrix);
User userFetched = this.api.getUserApi().get(matrix.getId());
assertEqualInputProps(userSaved, matrix);
assertEqualInputProps(userFetched, matrix);
}
@Test
public void createBankAccountIBAN() {
try {
UserNatural john = this.getJohn();
BankAccount account = this.getJohnsAccount();
assertTrue(account.getId().length() > 0);
assertEquals(account.getUserId(), john.getId());
} catch (Exception ex) {
Assert.fail(ex.getMessage());
}
}
@Test
public void createBankAccountGB() throws Exception {
UserNatural john = this.getJohn();
BankAccount account = new BankAccount();
account.setType(BankAccountType.GB);
account.setOwnerName(john.getFirstName() + " " + john.getLastName());
account.setOwnerAddress(john.getAddress());
account.setDetails(new BankAccountDetailsGB());
((BankAccountDetailsGB) account.getDetails()).setAccountNumber("63956474");
((BankAccountDetailsGB) account.getDetails()).setSortCode("200000");
account.setType(BankAccountType.GB);
BankAccount createAccount = this.api.getUserApi().createBankAccount(john.getId(), account);
assertTrue(createAccount.getId().length() > 0);
assertEquals(createAccount.getUserId(), john.getId());
assertSame(createAccount.getType(), BankAccountType.GB);
assertEquals("63956474", ((BankAccountDetailsGB) createAccount.getDetails()).getAccountNumber());
assertEquals("200000", ((BankAccountDetailsGB) createAccount.getDetails()).getSortCode());
}
@Test
public void createBankAccountUS() throws Exception {
UserNatural john = this.getJohn();
BankAccount account = new BankAccount();
account.setType(BankAccountType.US);
account.setOwnerName(john.getFirstName() + " " + john.getLastName());
account.setOwnerAddress(john.getAddress());
account.setDetails(new BankAccountDetailsUS());
((BankAccountDetailsUS) account.getDetails()).setAccountNumber("234234234234");
((BankAccountDetailsUS) account.getDetails()).setAba("234334789");
BankAccount createAccount = this.api.getUserApi().createBankAccount(john.getId(), account);
assertTrue(createAccount.getId().length() > 0);
assertEquals(createAccount.getUserId(), john.getId());
assertSame(createAccount.getType(), BankAccountType.US);
assertEquals("234234234234", ((BankAccountDetailsUS) createAccount.getDetails()).getAccountNumber());
assertEquals("234334789", ((BankAccountDetailsUS) createAccount.getDetails()).getAba());
assertEquals(((BankAccountDetailsUS) createAccount.getDetails()).getDepositAccountType(), DepositAccountType.CHECKING);
((BankAccountDetailsUS) account.getDetails()).setDepositAccountType(DepositAccountType.SAVINGS);
BankAccount createAccountSavings = this.api.getUserApi().createBankAccount(john.getId(), account);
assertTrue(createAccountSavings.getId().length() > 0);
assertEquals(createAccountSavings.getUserId(), john.getId());
assertSame(createAccountSavings.getType(), BankAccountType.US);
assertEquals("234234234234", ((BankAccountDetailsUS) createAccountSavings.getDetails()).getAccountNumber());
assertEquals("234334789", ((BankAccountDetailsUS) createAccountSavings.getDetails()).getAba());
assertEquals(((BankAccountDetailsUS) createAccountSavings.getDetails()).getDepositAccountType(), DepositAccountType.SAVINGS);
}
@Test
public void createBankAccountCA() throws Exception {
UserNatural john = this.getJohn();
BankAccount account = new BankAccount();
account.setType(BankAccountType.CA);
account.setOwnerName(john.getFirstName() + " " + john.getLastName());
account.setOwnerAddress(john.getAddress());
account.setDetails(new BankAccountDetailsCA());
((BankAccountDetailsCA) account.getDetails()).setBankName("TestBankName");
((BankAccountDetailsCA) account.getDetails()).setBranchCode("12345");
((BankAccountDetailsCA) account.getDetails()).setAccountNumber("234234234234");
((BankAccountDetailsCA) account.getDetails()).setInstitutionNumber("123");
BankAccount createAccount = this.api.getUserApi().createBankAccount(john.getId(), account);
assertTrue(createAccount.getId().length() > 0);
assertEquals(createAccount.getUserId(), john.getId());
assertSame(createAccount.getType(), BankAccountType.CA);
assertEquals("234234234234", ((BankAccountDetailsCA) createAccount.getDetails()).getAccountNumber());
assertEquals("TestBankName", ((BankAccountDetailsCA) createAccount.getDetails()).getBankName());
assertEquals("12345", ((BankAccountDetailsCA) createAccount.getDetails()).getBranchCode());
assertEquals("123", ((BankAccountDetailsCA) createAccount.getDetails()).getInstitutionNumber());
}
@Test
public void createBankAccountOTHER() {
try {
UserNatural john = this.getJohn();
BankAccount account = new BankAccount();
account.setOwnerName(john.getFirstName() + " " + john.getLastName());
account.setOwnerAddress(john.getAddress());
account.setDetails(new BankAccountDetailsOTHER());
account.setType(BankAccountType.OTHER);
((BankAccountDetailsOTHER) account.getDetails()).setCountry(CountryIso.FR);
((BankAccountDetailsOTHER) account.getDetails()).setAccountNumber("234234234234");
((BankAccountDetailsOTHER) account.getDetails()).setBic("BINAADADXXX");
BankAccount createAccount = this.api.getUserApi().createBankAccount(john.getId(), account);
assertTrue(createAccount.getId().length() > 0);
assertTrue(createAccount.getUserId().equals(john.getId()));
assertTrue(createAccount.getType() == BankAccountType.OTHER);
assertTrue(((BankAccountDetailsOTHER) createAccount.getDetails()).getCountry().equals(CountryIso.FR));
assertTrue(((BankAccountDetailsOTHER) createAccount.getDetails()).getAccountNumber().equals("234234234234"));
assertTrue(((BankAccountDetailsOTHER) createAccount.getDetails()).getBic().equals("BINAADADXXX"));
} catch (Exception ex) {
Assert.fail(ex.getMessage());
}
}
@Test
public void createBankAccount() throws Exception {
UserNatural john = this.getJohn();
BankAccount account = this.getJohnsAccount();
assertTrue(account.getId().length() > 0);
assertTrue(account.getUserId().equals(john.getId()));
}
@Test
public void updateBankAccount() throws Exception {
UserNatural john = this.getJohn();
BankAccount account = this.getJohnsAccount();
assertTrue(account.getId().length() > 0);
assertTrue(account.getUserId().equals(john.getId()));
// disactivate bank account
BankAccount disactivateBankAccount = new BankAccount();
disactivateBankAccount.setActive(false);
disactivateBankAccount.setType(BankAccountType.IBAN);
BankAccountDetailsIBAN bankAccountDetails = new BankAccountDetailsIBAN();
bankAccountDetails.setIban("FR7618829754160173622224154");
bankAccountDetails.setBic("CMBRFR2BCME");
disactivateBankAccount.setDetails(bankAccountDetails);
BankAccount result = this.api.getUserApi().updateBankAccount(john.getId(), disactivateBankAccount, account.getId());
assertNotNull(result);
assertEquals(account.getId(), result.getId());
assertFalse(result.isActive());
}
@Test
public void getBankAccount() throws Exception {
UserNatural john = this.getJohn();
BankAccount account = this.getJohnsAccount();
BankAccount accountFetched = this.api.getUserApi().getBankAccount(john.getId(), account.getId());
assertEqualInputProps(account, accountFetched);
}
@Test
public void getBankAccounts() throws Exception {
UserNatural john = this.getJohn();
BankAccount account = this.getJohnsAccount();
Pagination pagination = new Pagination(1, 12);
List<BankAccount> list = this.api.getUserApi().getBankAccounts(john.getId(), pagination, null);
int index = -1;
for (int i = 0; i < list.size(); i++) {
if (account.getId().equals(list.get(i).getId())) {
index = i;
break;
}
}
assertTrue(list.get(0) instanceof BankAccount);
assertTrue(index > -1);
assertEqualInputProps(account, list.get(index));
assertTrue(pagination.getPage() == 1);
assertTrue(pagination.getItemsPerPage() == 12);
}
@Test
public void getActiveBankAccounts() {
try {
UserNatural john = this.getJohn();
BankAccount account = this.getJohnsAccount();
List<BankAccount> list = this.api.getUserApi().getActiveBankAccounts(john.getId(), true, null, null);
} catch (Exception e) {
Assert.fail(e.getMessage());
}
}
@Test
public void getBankAccountsAndSortByCreationDate() throws Exception {
UserNatural john = this.getJohn();
this.getJohnsAccount();
this.holdOn(2);
this.getNewBankAccount();
Pagination pagination = new Pagination(1, 12);
Sorting sorting = new Sorting();
sorting.addField("CreationDate", SortDirection.desc);
List<BankAccount> list = this.api.getUserApi().getBankAccounts(john.getId(), pagination, sorting);
assertNotNull(list);
assertTrue(list.get(0) instanceof BankAccount);
assertTrue(list.size() > 1);
assertTrue(list.get(0).getCreationDate() > list.get(1).getCreationDate());
}
@Test
public void createKycDocument() throws Exception {
KycDocument kycDocument = this.getJohnsKycDocument();
assertNotNull(kycDocument);
assertTrue(kycDocument.getStatus() == KycStatus.CREATED);
}
@Test
public void updateKycDocument() throws Exception {
UserNatural john = this.getJohn();
KycDocument kycDocument = this.getJohnsKycDocument();
URL url = getClass().getResource("/com/mangopay/core/TestKycPageFile.png");
String filePath = new File(url.toURI()).getAbsolutePath();
this.api.getUserApi().createKycPage(john.getId(), kycDocument.getId(), filePath);
kycDocument.setStatus(KycStatus.VALIDATION_ASKED);
KycDocument result = this.api.getUserApi().updateKycDocument(john.getId(), kycDocument);
assertNotNull(result);
assertTrue(kycDocument.getType().equals(result.getType()));
assertTrue(kycDocument.getStatus() == KycStatus.VALIDATION_ASKED);
}
@Test
public void getKycDocument() throws Exception {
UserNatural john = this.getJohn();
KycDocument kycDocument = this.getJohnsKycDocument();
KycDocument result = this.api.getUserApi().getKycDocument(john.getId(), kycDocument.getId());
assertNotNull(result);
assertTrue(kycDocument.getId().equals(result.getId()));
assertTrue(kycDocument.getType().equals(result.getType()));
assertTrue(kycDocument.getStatus().equals(result.getStatus()));
assertTrue(kycDocument.getCreationDate() == result.getCreationDate());
}
@Test
public void createKycPage() throws Exception {
UserNatural john = this.getJohn();
KycDocument kycDocument = this.getNewKycDocument();
URL url = getClass().getResource("/com/mangopay/core/TestKycPageFile.png");
String filePath = new File(url.toURI()).getAbsolutePath();
this.api.getUserApi().createKycPage(john.getId(), kycDocument.getId(), filePath);
kycDocument = this.getNewKycDocument();
this.api.getUserApi().createKycPage(john.getId(), kycDocument.getId(), Files.readAllBytes(Paths.get(filePath)));
}
@Test
public void getCards() throws Exception {
UserNatural john = this.getJohn();
Pagination pagination = new Pagination(1, 20);
List<Card> cardsBefore = this.api.getUserApi().getCards(john.getId(), pagination, null);
PayIn payIn = this.getNewPayInCardDirect();
Card card = this.api.getCardApi().get(((PayInPaymentDetailsCard) payIn.getPaymentDetails()).getCardId());
List<Card> cardsAfter = this.api.getUserApi().getCards(john.getId(), pagination, null);
assertNotNull(cardsBefore);
assertTrue(cardsAfter.size() > cardsBefore.size());
}
@Test
public void getCardsAndSortByCreationDate() throws Exception {
UserNatural john = this.getJohn();
this.getNewPayInCardDirect();
this.holdOn(2);
this.getNewPayInCardDirect();
Pagination pagination = new Pagination(1, 20);
Sorting sorting = new Sorting();
sorting.addField("CreationDate", SortDirection.desc);
List<Card> cards = this.api.getUserApi().getCards(john.getId(), pagination, sorting);
assertNotNull(cards);
assertTrue(cards.size() > 1);
assertTrue(cards.get(0).getCreationDate() > cards.get(1).getCreationDate());
}
@Test
public void getTransactions() throws Exception {
UserNatural john = this.getJohn();
Transfer transfer = this.getNewTransfer();
Pagination pagination = new Pagination(1, 20);
List<Transaction> transactions = this.api.getUserApi().getTransactions(john.getId(), pagination, new FilterTransactions(), null);
assertTrue(transactions.size() > 0);
assertTrue(transactions.get(0).getType() != null);
assertTrue(transactions.get(0).getStatus() != null);
}
@Test
public void getTransactionsAndSortByCreationDate() throws Exception {
UserNatural john = this.getJohn();
this.getNewTransfer();
this.holdOn(2);
this.getNewTransfer();
Pagination pagination = new Pagination(1, 20);
Sorting sorting = new Sorting();
sorting.addField("CreationDate", SortDirection.desc);
List<Transaction> transactions = this.api.getUserApi().getTransactions(john.getId(), pagination, new FilterTransactions(), sorting);
assertNotNull(transactions);
assertTrue(transactions.size() > 1);
assertTrue(transactions.get(0).getCreationDate() > transactions.get(1).getCreationDate());
}
@Test
public void getKycDocuments() throws Exception {
KycDocument kycDocument = this.getJohnsKycDocument();
UserNatural user = this.getJohn();
Pagination pagination = new Pagination(1, 20);
List<KycDocument> getKycDocuments = this.api.getUserApi().getKycDocuments(user.getId(), pagination, null);
assertTrue(getKycDocuments.get(0) instanceof KycDocument);
KycDocument kycFromList = null;
for (KycDocument item : getKycDocuments) {
if (item.getId().equals(kycDocument.getId())) {
kycFromList = item;
break;
}
}
assertNotNull(kycFromList);
assertEquals(kycDocument.getId(), kycFromList.getId());
assertEqualInputProps(kycDocument, kycFromList);
}
@Test
public void getKycDocumentsAndSortByCreationDate() throws Exception {
this.getJohnsKycDocument();
this.holdOn(2);
this.getNewKycDocument();
UserNatural user = this.getJohn();
Pagination pagination = new Pagination(1, 20);
Sorting sorting = new Sorting();
sorting.addField("CreationDate", SortDirection.desc);
List<KycDocument> getKycDocuments = this.api.getUserApi().getKycDocuments(user.getId(), pagination, sorting);
assertNotNull(getKycDocuments);
assertTrue(getKycDocuments.get(0) instanceof KycDocument);
assertTrue(getKycDocuments.size() > 1);
assertTrue(getKycDocuments.get(0).getCreationDate() > getKycDocuments.get(1).getCreationDate());
}
@Test
public void getUserEMoney() throws Exception {
User john = getJohn();
String year = "2019";
String month = "04";
EMoney eMoney = this.api.getUserApi().getEMoney(john.getId(), year);
assertNotNull(eMoney);
assertEquals(eMoney.getUserId(), john.getId());
eMoney = this.api.getUserApi().getEMoney(john.getId(), year, month);
assertNotNull(eMoney);
assertEquals(eMoney.getUserId(), john.getId());
}
@Test
public void getUserEMoneyChf() throws Exception {
getUserEMoney(CurrencyIso.CHF);
}
@Test
public void getUserEMoneyUsd() throws Exception {
getUserEMoney(CurrencyIso.USD);
}
@Test
public void testUserEMoneyNullCurrency() throws Exception {
getUserEMoney(null, CurrencyIso.EUR);
}
private void getUserEMoney(CurrencyIso currencySentInRequest) throws Exception {
getUserEMoney(currencySentInRequest, currencySentInRequest);
}
private void getUserEMoney(CurrencyIso currencySentInRequest, CurrencyIso currencyExpected) throws Exception {
User john = getJohn();
String year = "2019";
String month = "04";
EMoney eMoney = this.api.getUserApi().getEMoney(john.getId(), year, currencySentInRequest);
assertNotNull(eMoney);
assertEquals(john.getId(), eMoney.getUserId());
assertEquals(currencyExpected, eMoney.getCreditedEMoney().getCurrency());
eMoney = this.api.getUserApi().getEMoney(john.getId(), year, month, currencySentInRequest);
assertNotNull(eMoney);
assertEquals(john.getId(), eMoney.getUserId());
assertEquals(currencyExpected, eMoney.getCreditedEMoney().getCurrency());
}
@Test
public void getBankAccountTransactions() throws Exception {
BankAccount johnsAccount = getJohnsAccount();
PayOut johnsPayOutBankWire = getJohnsPayOutBankWire();
Pagination pagination = new Pagination(1, 1);
List<Transaction> bankAccountTransactions = this.api.getUserApi().getBankAccountTransactions(johnsAccount.getId(), pagination, null);
assertNotNull("List of bank account transactions is null", bankAccountTransactions);
assertFalse("List of bank account transactions is empty", bankAccountTransactions.isEmpty());
assertTrue("List of bank account transactions size does not match pagination", bankAccountTransactions.size() == 1);
assertEquals("Returned transaction is not the expected one", bankAccountTransactions.get(0).getId(), johnsPayOutBankWire.getId());
}
@Test
public void getUserPreAuthorizations() throws Exception {
CardPreAuthorization johnsCardPreAuthorization = getJohnsCardPreAuthorization();
assertNotNull(johnsCardPreAuthorization);
List<CardPreAuthorization> preAuthorizations = this.api.getUserApi().getPreAuthorizations(johnsCardPreAuthorization.getAuthorId());
assertNotNull(preAuthorizations);
assertFalse(preAuthorizations.isEmpty());
assertNotNull(preAuthorizations.get(0));
assertTrue(preAuthorizations.get(0).getAuthorId().equals(johnsCardPreAuthorization.getAuthorId()));
}
@Test
@Ignore
// this endpoind isn't on the api just yet
public void getBlockStatus() throws Exception{
UserNatural user = this.getJohn();
UserBlockStatus blockStatus = this.api.getUserApi().getBlockStatus(user.getId());
assertNotNull(blockStatus);
}
}
| src/test/java/com/mangopay/core/UserApiImplTest.java | package com.mangopay.core;
import com.mangopay.core.enumerations.*;
import com.mangopay.entities.*;
import com.mangopay.entities.subentities.*;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import java.io.File;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Calendar;
import java.util.List;
import static org.junit.Assert.*;
/**
* UserApiImpl test methods
*/
public class UserApiImplTest extends BaseTest {
@Test
public void createNatural() throws Exception {
UserNatural john = this.getJohn();
assertTrue(john.getId().length() > 0);
assertTrue(john.getPersonType().equals(PersonType.NATURAL));
}
@Test
public void createLegal() throws Exception {
UserLegal matrix = this.getMatrix();
assertTrue(matrix.getId().length() > 0);
assertEquals(matrix.getPersonType(), PersonType.LEGAL);
assertEquals("LU12345678", matrix.getCompanyNumber());
}
@Test
public void createLegalFailsIfRequiredPropsNotProvided() throws Exception {
UserLegal user = new UserLegal();
User ret = null;
try {
ret = this.api.getUserApi().create(user);
Assert.fail("CreateLegal() should throw an exception when required props are not provided");
} catch (ResponseException ex) {
assertNull(ret);
}
}
@Test
public void createLegalPassesIfRequiredPropsProvided() throws Exception {
UserLegal user = new UserLegal();
user.setHeadquartersAddress(new Address());
user.getHeadquartersAddress().setAddressLine1("AddressLine1");
user.getHeadquartersAddress().setAddressLine2("AddressLine2");
user.getHeadquartersAddress().setCity("City");
user.getHeadquartersAddress().setCountry(CountryIso.FR);
user.getHeadquartersAddress().setPostalCode("11222");
user.getHeadquartersAddress().setRegion("Region");
user.setName("SomeOtherSampleOrg");
user.setLegalPersonType(LegalPersonType.BUSINESS);
user.setLegalRepresentativeFirstName("RepFName");
user.setLegalRepresentativeLastName("RepLName");
Calendar c = Calendar.getInstance();
c.set(1975, 12, 21, 0, 0, 0);
user.setLegalRepresentativeBirthday(c.getTimeInMillis() / 1000);
user.setLegalRepresentativeNationality(CountryIso.FR);
user.setLegalRepresentativeCountryOfResidence(CountryIso.FR);
user.setEmail("[email protected]");
user.setCompanyNumber("LU12345678");
User ret = null;
ret = this.api.getUserApi().create(user);
assertTrue("Created successfully after required props set", ret.getId().length() > 0);
assertEqualInputProps(user, ret);
}
@Test
public void getAllUsers() throws Exception {
Sorting sort = new Sorting();
sort.addField("CreationDate", SortDirection.desc);
List<User> users = this.api.getUserApi().getAll(null, sort);
assertTrue(users.get(0).getCreationDate() > users.get(users.size() - 1).getCreationDate());
sort = new Sorting();
sort.addField("CreationDate", SortDirection.asc);
users = this.api.getUserApi().getAll(null, sort);
assertTrue(users.get(0).getCreationDate() < users.get(users.size() - 1).getCreationDate());
}
@Test
public void getNatural() throws Exception {
UserNatural john = this.getJohn();
User user1 = this.api.getUserApi().get(john.getId());
UserNatural user2 = this.api.getUserApi().getNatural(john.getId());
assertTrue(user1.getPersonType().equals(PersonType.NATURAL));
assertTrue(user1.getId().equals(john.getId()));
assertTrue(user2.getPersonType().equals(PersonType.NATURAL));
assertTrue(user2.getId().equals(john.getId()));
assertEqualInputProps(user1, john);
}
@Test
public void getNaturalFailsForLegalUser() throws Exception {
UserLegal matrix = this.getMatrix();
UserNatural user = null;
try {
user = this.api.getUserApi().getNatural(matrix.getId());
Assert.fail("GetUser() should throw an exception when called with legal user id");
} catch (ResponseException ex) {
assertNull(user);
}
}
@Test
public void getLegalFailsForNaturalUser() throws Exception {
UserNatural john = this.getJohn();
User user = null;
try {
user = this.api.getUserApi().getLegal(john.getId());
Assert.fail("GetLegal() should throw an exception when called with natural user id");
} catch (ResponseException ex) {
assertNull(user);
}
}
@Test
public void getLegal() throws Exception {
UserLegal matrix = this.getMatrix();
User user1 = this.api.getUserApi().get(matrix.getId());
User user2 = this.api.getUserApi().getLegal(matrix.getId());
assertEqualInputProps(user1, matrix);
assertEqualInputProps(user2, matrix);
}
@Test
public void updateNatural() throws Exception {
UserNatural john = this.getJohn();
john.setLastName(john.getLastName() + " - CHANGED");
User userSaved = this.api.getUserApi().update(john);
User userFetched = this.api.getUserApi().get(john.getId());
assertEqualInputProps(john, userSaved);
assertEqualInputProps(john, userFetched);
}
@Test
public void updateNaturalNonASCII() throws Exception {
UserNatural john = this.getJohn();
john.setLastName(john.getLastName() + " - CHANGED");
User userSaved = this.api.getUserApi().update(john);
User userFetched = this.api.getUserApi().get(john.getId());
assertEqualInputProps(john, userSaved);
assertEqualInputProps(john, userFetched);
}
@Test
public void updateLegal() throws Exception {
UserLegal matrix = this.getMatrix();
matrix.setLegalRepresentativeLastName(matrix.getLegalRepresentativeLastName() + " - CHANGED");
User userSaved = this.api.getUserApi().update(matrix);
User userFetched = this.api.getUserApi().get(matrix.getId());
assertEqualInputProps(userSaved, matrix);
assertEqualInputProps(userFetched, matrix);
}
@Test
public void updateLegalWithoutAddresses() throws Exception {
UserLegal matrix = this.getMatrixWithoutOptionalFields();
matrix.setLegalRepresentativeLastName(matrix.getLegalRepresentativeLastName() + " - CHANGED");
User userSaved = this.api.getUserApi().update(matrix);
User userFetched = this.api.getUserApi().get(matrix.getId());
assertEqualInputProps(userSaved, matrix);
assertEqualInputProps(userFetched, matrix);
}
@Test
public void createBankAccountIBAN() {
try {
UserNatural john = this.getJohn();
BankAccount account = this.getJohnsAccount();
assertTrue(account.getId().length() > 0);
assertEquals(account.getUserId(), john.getId());
} catch (Exception ex) {
Assert.fail(ex.getMessage());
}
}
@Test
public void createBankAccountGB() throws Exception {
UserNatural john = this.getJohn();
BankAccount account = new BankAccount();
account.setType(BankAccountType.GB);
account.setOwnerName(john.getFirstName() + " " + john.getLastName());
account.setOwnerAddress(john.getAddress());
account.setDetails(new BankAccountDetailsGB());
((BankAccountDetailsGB) account.getDetails()).setAccountNumber("63956474");
((BankAccountDetailsGB) account.getDetails()).setSortCode("200000");
account.setType(BankAccountType.GB);
BankAccount createAccount = this.api.getUserApi().createBankAccount(john.getId(), account);
assertTrue(createAccount.getId().length() > 0);
assertEquals(createAccount.getUserId(), john.getId());
assertSame(createAccount.getType(), BankAccountType.GB);
assertEquals("63956474", ((BankAccountDetailsGB) createAccount.getDetails()).getAccountNumber());
assertEquals("200000", ((BankAccountDetailsGB) createAccount.getDetails()).getSortCode());
}
@Test
public void createBankAccountUS() throws Exception {
UserNatural john = this.getJohn();
BankAccount account = new BankAccount();
account.setType(BankAccountType.US);
account.setOwnerName(john.getFirstName() + " " + john.getLastName());
account.setOwnerAddress(john.getAddress());
account.setDetails(new BankAccountDetailsUS());
((BankAccountDetailsUS) account.getDetails()).setAccountNumber("234234234234");
((BankAccountDetailsUS) account.getDetails()).setAba("234334789");
BankAccount createAccount = this.api.getUserApi().createBankAccount(john.getId(), account);
assertTrue(createAccount.getId().length() > 0);
assertEquals(createAccount.getUserId(), john.getId());
assertSame(createAccount.getType(), BankAccountType.US);
assertEquals("234234234234", ((BankAccountDetailsUS) createAccount.getDetails()).getAccountNumber());
assertEquals("234334789", ((BankAccountDetailsUS) createAccount.getDetails()).getAba());
assertEquals(((BankAccountDetailsUS) createAccount.getDetails()).getDepositAccountType(), DepositAccountType.CHECKING);
((BankAccountDetailsUS) account.getDetails()).setDepositAccountType(DepositAccountType.SAVINGS);
BankAccount createAccountSavings = this.api.getUserApi().createBankAccount(john.getId(), account);
assertTrue(createAccountSavings.getId().length() > 0);
assertEquals(createAccountSavings.getUserId(), john.getId());
assertSame(createAccountSavings.getType(), BankAccountType.US);
assertEquals("234234234234", ((BankAccountDetailsUS) createAccountSavings.getDetails()).getAccountNumber());
assertEquals("234334789", ((BankAccountDetailsUS) createAccountSavings.getDetails()).getAba());
assertEquals(((BankAccountDetailsUS) createAccountSavings.getDetails()).getDepositAccountType(), DepositAccountType.SAVINGS);
}
@Test
public void createBankAccountCA() throws Exception {
UserNatural john = this.getJohn();
BankAccount account = new BankAccount();
account.setType(BankAccountType.CA);
account.setOwnerName(john.getFirstName() + " " + john.getLastName());
account.setOwnerAddress(john.getAddress());
account.setDetails(new BankAccountDetailsCA());
((BankAccountDetailsCA) account.getDetails()).setBankName("TestBankName");
((BankAccountDetailsCA) account.getDetails()).setBranchCode("12345");
((BankAccountDetailsCA) account.getDetails()).setAccountNumber("234234234234");
((BankAccountDetailsCA) account.getDetails()).setInstitutionNumber("123");
BankAccount createAccount = this.api.getUserApi().createBankAccount(john.getId(), account);
assertTrue(createAccount.getId().length() > 0);
assertEquals(createAccount.getUserId(), john.getId());
assertSame(createAccount.getType(), BankAccountType.CA);
assertEquals("234234234234", ((BankAccountDetailsCA) createAccount.getDetails()).getAccountNumber());
assertEquals("TestBankName", ((BankAccountDetailsCA) createAccount.getDetails()).getBankName());
assertEquals("12345", ((BankAccountDetailsCA) createAccount.getDetails()).getBranchCode());
assertEquals("123", ((BankAccountDetailsCA) createAccount.getDetails()).getInstitutionNumber());
}
@Test
public void createBankAccountOTHER() {
try {
UserNatural john = this.getJohn();
BankAccount account = new BankAccount();
account.setOwnerName(john.getFirstName() + " " + john.getLastName());
account.setOwnerAddress(john.getAddress());
account.setDetails(new BankAccountDetailsOTHER());
account.setType(BankAccountType.OTHER);
((BankAccountDetailsOTHER) account.getDetails()).setCountry(CountryIso.FR);
((BankAccountDetailsOTHER) account.getDetails()).setAccountNumber("234234234234");
((BankAccountDetailsOTHER) account.getDetails()).setBic("BINAADADXXX");
BankAccount createAccount = this.api.getUserApi().createBankAccount(john.getId(), account);
assertTrue(createAccount.getId().length() > 0);
assertTrue(createAccount.getUserId().equals(john.getId()));
assertTrue(createAccount.getType() == BankAccountType.OTHER);
assertTrue(((BankAccountDetailsOTHER) createAccount.getDetails()).getCountry().equals(CountryIso.FR));
assertTrue(((BankAccountDetailsOTHER) createAccount.getDetails()).getAccountNumber().equals("234234234234"));
assertTrue(((BankAccountDetailsOTHER) createAccount.getDetails()).getBic().equals("BINAADADXXX"));
} catch (Exception ex) {
Assert.fail(ex.getMessage());
}
}
@Test
public void createBankAccount() throws Exception {
UserNatural john = this.getJohn();
BankAccount account = this.getJohnsAccount();
assertTrue(account.getId().length() > 0);
assertTrue(account.getUserId().equals(john.getId()));
}
@Test
public void updateBankAccount() throws Exception {
UserNatural john = this.getJohn();
BankAccount account = this.getJohnsAccount();
assertTrue(account.getId().length() > 0);
assertTrue(account.getUserId().equals(john.getId()));
// disactivate bank account
BankAccount disactivateBankAccount = new BankAccount();
disactivateBankAccount.setActive(false);
disactivateBankAccount.setType(BankAccountType.IBAN);
BankAccountDetailsIBAN bankAccountDetails = new BankAccountDetailsIBAN();
bankAccountDetails.setIban("FR7618829754160173622224154");
bankAccountDetails.setBic("CMBRFR2BCME");
disactivateBankAccount.setDetails(bankAccountDetails);
BankAccount result = this.api.getUserApi().updateBankAccount(john.getId(), disactivateBankAccount, account.getId());
assertNotNull(result);
assertEquals(account.getId(), result.getId());
assertFalse(result.isActive());
}
@Test
public void getBankAccount() throws Exception {
UserNatural john = this.getJohn();
BankAccount account = this.getJohnsAccount();
BankAccount accountFetched = this.api.getUserApi().getBankAccount(john.getId(), account.getId());
assertEqualInputProps(account, accountFetched);
}
@Test
public void getBankAccounts() throws Exception {
UserNatural john = this.getJohn();
BankAccount account = this.getJohnsAccount();
Pagination pagination = new Pagination(1, 12);
List<BankAccount> list = this.api.getUserApi().getBankAccounts(john.getId(), pagination, null);
int index = -1;
for (int i = 0; i < list.size(); i++) {
if (account.getId().equals(list.get(i).getId())) {
index = i;
break;
}
}
assertTrue(list.get(0) instanceof BankAccount);
assertTrue(index > -1);
assertEqualInputProps(account, list.get(index));
assertTrue(pagination.getPage() == 1);
assertTrue(pagination.getItemsPerPage() == 12);
}
@Test
public void getActiveBankAccounts() {
try {
UserNatural john = this.getJohn();
BankAccount account = this.getJohnsAccount();
List<BankAccount> list = this.api.getUserApi().getActiveBankAccounts(john.getId(), true, null, null);
} catch (Exception e) {
Assert.fail(e.getMessage());
}
}
@Test
public void getBankAccountsAndSortByCreationDate() throws Exception {
UserNatural john = this.getJohn();
this.getJohnsAccount();
this.holdOn(2);
this.getNewBankAccount();
Pagination pagination = new Pagination(1, 12);
Sorting sorting = new Sorting();
sorting.addField("CreationDate", SortDirection.desc);
List<BankAccount> list = this.api.getUserApi().getBankAccounts(john.getId(), pagination, sorting);
assertNotNull(list);
assertTrue(list.get(0) instanceof BankAccount);
assertTrue(list.size() > 1);
assertTrue(list.get(0).getCreationDate() > list.get(1).getCreationDate());
}
@Test
public void createKycDocument() throws Exception {
KycDocument kycDocument = this.getJohnsKycDocument();
assertNotNull(kycDocument);
assertTrue(kycDocument.getStatus() == KycStatus.CREATED);
}
@Test
public void updateKycDocument() throws Exception {
UserNatural john = this.getJohn();
KycDocument kycDocument = this.getJohnsKycDocument();
URL url = getClass().getResource("/com/mangopay/core/TestKycPageFile.png");
String filePath = new File(url.toURI()).getAbsolutePath();
this.api.getUserApi().createKycPage(john.getId(), kycDocument.getId(), filePath);
kycDocument.setStatus(KycStatus.VALIDATION_ASKED);
KycDocument result = this.api.getUserApi().updateKycDocument(john.getId(), kycDocument);
assertNotNull(result);
assertTrue(kycDocument.getType().equals(result.getType()));
assertTrue(kycDocument.getStatus() == KycStatus.VALIDATION_ASKED);
}
@Test
public void getKycDocument() throws Exception {
UserNatural john = this.getJohn();
KycDocument kycDocument = this.getJohnsKycDocument();
KycDocument result = this.api.getUserApi().getKycDocument(john.getId(), kycDocument.getId());
assertNotNull(result);
assertTrue(kycDocument.getId().equals(result.getId()));
assertTrue(kycDocument.getType().equals(result.getType()));
assertTrue(kycDocument.getStatus().equals(result.getStatus()));
assertTrue(kycDocument.getCreationDate() == result.getCreationDate());
}
@Test
public void createKycPage() throws Exception {
UserNatural john = this.getJohn();
KycDocument kycDocument = this.getNewKycDocument();
URL url = getClass().getResource("/com/mangopay/core/TestKycPageFile.png");
String filePath = new File(url.toURI()).getAbsolutePath();
this.api.getUserApi().createKycPage(john.getId(), kycDocument.getId(), filePath);
kycDocument = this.getNewKycDocument();
this.api.getUserApi().createKycPage(john.getId(), kycDocument.getId(), Files.readAllBytes(Paths.get(filePath)));
}
@Test
public void getCards() throws Exception {
UserNatural john = this.getJohn();
Pagination pagination = new Pagination(1, 20);
List<Card> cardsBefore = this.api.getUserApi().getCards(john.getId(), pagination, null);
PayIn payIn = this.getNewPayInCardDirect();
Card card = this.api.getCardApi().get(((PayInPaymentDetailsCard) payIn.getPaymentDetails()).getCardId());
List<Card> cardsAfter = this.api.getUserApi().getCards(john.getId(), pagination, null);
assertNotNull(cardsBefore);
assertTrue(cardsAfter.size() > cardsBefore.size());
}
@Test
public void getCardsAndSortByCreationDate() throws Exception {
UserNatural john = this.getJohn();
this.getNewPayInCardDirect();
this.holdOn(2);
this.getNewPayInCardDirect();
Pagination pagination = new Pagination(1, 20);
Sorting sorting = new Sorting();
sorting.addField("CreationDate", SortDirection.desc);
List<Card> cards = this.api.getUserApi().getCards(john.getId(), pagination, sorting);
assertNotNull(cards);
assertTrue(cards.size() > 1);
assertTrue(cards.get(0).getCreationDate() > cards.get(1).getCreationDate());
}
@Test
public void getTransactions() throws Exception {
UserNatural john = this.getJohn();
Transfer transfer = this.getNewTransfer();
Pagination pagination = new Pagination(1, 20);
List<Transaction> transactions = this.api.getUserApi().getTransactions(john.getId(), pagination, new FilterTransactions(), null);
assertTrue(transactions.size() > 0);
assertTrue(transactions.get(0).getType() != null);
assertTrue(transactions.get(0).getStatus() != null);
}
@Test
public void getTransactionsAndSortByCreationDate() throws Exception {
UserNatural john = this.getJohn();
this.getNewTransfer();
this.holdOn(2);
this.getNewTransfer();
Pagination pagination = new Pagination(1, 20);
Sorting sorting = new Sorting();
sorting.addField("CreationDate", SortDirection.desc);
List<Transaction> transactions = this.api.getUserApi().getTransactions(john.getId(), pagination, new FilterTransactions(), sorting);
assertNotNull(transactions);
assertTrue(transactions.size() > 1);
assertTrue(transactions.get(0).getCreationDate() > transactions.get(1).getCreationDate());
}
@Test
public void getKycDocuments() throws Exception {
KycDocument kycDocument = this.getJohnsKycDocument();
UserNatural user = this.getJohn();
Pagination pagination = new Pagination(1, 20);
List<KycDocument> getKycDocuments = this.api.getUserApi().getKycDocuments(user.getId(), pagination, null);
assertTrue(getKycDocuments.get(0) instanceof KycDocument);
KycDocument kycFromList = null;
for (KycDocument item : getKycDocuments) {
if (item.getId().equals(kycDocument.getId())) {
kycFromList = item;
break;
}
}
assertNotNull(kycFromList);
assertEquals(kycDocument.getId(), kycFromList.getId());
assertEqualInputProps(kycDocument, kycFromList);
}
@Test
public void getKycDocumentsAndSortByCreationDate() throws Exception {
this.getJohnsKycDocument();
this.holdOn(2);
this.getNewKycDocument();
UserNatural user = this.getJohn();
Pagination pagination = new Pagination(1, 20);
Sorting sorting = new Sorting();
sorting.addField("CreationDate", SortDirection.desc);
List<KycDocument> getKycDocuments = this.api.getUserApi().getKycDocuments(user.getId(), pagination, sorting);
assertNotNull(getKycDocuments);
assertTrue(getKycDocuments.get(0) instanceof KycDocument);
assertTrue(getKycDocuments.size() > 1);
assertTrue(getKycDocuments.get(0).getCreationDate() > getKycDocuments.get(1).getCreationDate());
}
@Test
public void getUserEMoney() throws Exception {
User john = getJohn();
String year = "2019";
String month = "04";
EMoney eMoney = this.api.getUserApi().getEMoney(john.getId(), year);
assertNotNull(eMoney);
assertEquals(eMoney.getUserId(), john.getId());
eMoney = this.api.getUserApi().getEMoney(john.getId(), year, month);
assertNotNull(eMoney);
assertEquals(eMoney.getUserId(), john.getId());
}
@Test
public void getUserEMoneyChf() throws Exception {
getUserEMoney(CurrencyIso.CHF);
}
@Test
public void getUserEMoneyUsd() throws Exception {
getUserEMoney(CurrencyIso.USD);
}
@Test
public void testUserEMoneyNullCurrency() throws Exception {
getUserEMoney(null, CurrencyIso.EUR);
}
private void getUserEMoney(CurrencyIso currencySentInRequest) throws Exception {
getUserEMoney(currencySentInRequest, currencySentInRequest);
}
private void getUserEMoney(CurrencyIso currencySentInRequest, CurrencyIso currencyExpected) throws Exception {
User john = getJohn();
String year = "2019";
String month = "04";
EMoney eMoney = this.api.getUserApi().getEMoney(john.getId(), year, currencySentInRequest);
assertNotNull(eMoney);
assertEquals(john.getId(), eMoney.getUserId());
assertEquals(currencyExpected, eMoney.getCreditedEMoney().getCurrency());
eMoney = this.api.getUserApi().getEMoney(john.getId(), year, month, currencySentInRequest);
assertNotNull(eMoney);
assertEquals(john.getId(), eMoney.getUserId());
assertEquals(currencyExpected, eMoney.getCreditedEMoney().getCurrency());
}
@Test
public void getBankAccountTransactions() throws Exception {
BankAccount johnsAccount = getJohnsAccount();
PayOut johnsPayOutBankWire = getJohnsPayOutBankWire();
Pagination pagination = new Pagination(1, 1);
List<Transaction> bankAccountTransactions = this.api.getUserApi().getBankAccountTransactions(johnsAccount.getId(), pagination, null);
assertNotNull("List of bank account transactions is null", bankAccountTransactions);
assertFalse("List of bank account transactions is empty", bankAccountTransactions.isEmpty());
assertTrue("List of bank account transactions size does not match pagination", bankAccountTransactions.size() == 1);
assertEquals("Returned transaction is not the expected one", bankAccountTransactions.get(0).getId(), johnsPayOutBankWire.getId());
}
@Test
public void getUserPreAuthorizations() throws Exception {
CardPreAuthorization johnsCardPreAuthorization = getJohnsCardPreAuthorization();
assertNotNull(johnsCardPreAuthorization);
List<CardPreAuthorization> preAuthorizations = this.api.getUserApi().getPreAuthorizations(johnsCardPreAuthorization.getAuthorId());
assertNotNull(preAuthorizations);
assertFalse(preAuthorizations.isEmpty());
assertNotNull(preAuthorizations.get(0));
assertTrue(preAuthorizations.get(0).getAuthorId().equals(johnsCardPreAuthorization.getAuthorId()));
}
@Test
public void getBlockStatus() throws Exception{
UserNatural user = this.getJohn();
UserBlockStatus blockStatus = this.api.getUserApi().getBlockStatus(user.getId());
assertNotNull(blockStatus);
}
}
| ignored getBlockStatus test as it is not on the api yet
| src/test/java/com/mangopay/core/UserApiImplTest.java | ignored getBlockStatus test as it is not on the api yet |
|
Java | mit | 482257788adfcf4fe05215cc617a3d071ba06ab0 | 0 | ProfAmesBC/Game2013 | package buildings;
import game.Building;
import javax.media.opengl.GL2;
import javax.media.opengl.glu.GLU;
import javax.media.opengl.glu.GLUquadric;
import java.awt.Font;
import com.jogamp.opengl.util.awt.TextRenderer;
import com.jogamp.opengl.util.texture.Texture;
public class ShippBuilding extends Building {
private GLUquadric quadric;
private Texture sidewalk, bruins, wood, tree, garden, bruinsWalls, ceiling,
sideWalls, black, red, blue, net, jumbo1, jumbo2, water, white;
private TextRenderer renderer;
private int fontSize = 88;
private int frames;
public ShippBuilding(GL2 gl, GLU glu) {
quadric = glu.gluNewQuadric();
glu.gluQuadricDrawStyle(quadric, GLU.GLU_FILL); // GLU_POINT, GLU_LINE, GLU_FILL, GLU_SILHOUETTE
glu.gluQuadricNormals (quadric, GLU.GLU_NONE); // GLU_NONE, GLU_FLAT, or GLU_SMOOTH
glu.gluQuadricTexture (quadric, true); // false, or true to generate texture coordinates
net = setupTexture(gl, "ShippNet.png");
sidewalk = setupTexture(gl, "ShippSidewalk.jpg");
bruins = setupTexture(gl, "ShippSpokedB.png");
bruinsWalls = setupTexture(gl, "ShippBruins.gif");
wood = setupTexture(gl, "ShippWood.jpg");
tree = setupTexture(gl, "ShippTree.jpg");
garden = setupTexture(gl, "ShippGardenExterior.jpg");
ceiling = setupTexture(gl, "ShippCeiling.png");
sideWalls = setupTexture(gl, "ShippWallGradient.png");
black = setupTexture(gl, "ShippBlack.png");
red = setupTexture(gl, "ShippRed.png");
blue = setupTexture(gl, "ShippBlue.png");
jumbo1 = setupTexture(gl, "ShippJumbotron1.png");
jumbo2 = setupTexture(gl, "ShippJumbotron2.jpg");
water = setupTexture(gl, "ShippWater.jpg");
white = setupTexture(gl, "ShippWhite.png");
frames = 0;
renderer = new TextRenderer(new Font("SansSerif", Font.BOLD, fontSize));
}
@Override
public void drawMoving(GL2 gl, GLU glu, float eyeX, float eyeY, float eyeZ) {
drawJumbotron(gl, glu);
}
public void draw(GL2 gl, GLU glu) {
drawSidewalkAndTrees(gl, glu);
drawWalls(gl, glu);
drawSign(gl, glu);
drawRink(gl, glu);
drawPool(gl, glu);
}
public void drawSidewalkAndTrees(GL2 gl, GLU glu) {
gl.glEnable(GL2.GL_TEXTURE_2D);
sidewalk.bind(gl); // Sidewalk surrounding the garden
gl.glBegin(GL2.GL_QUADS);
gl.glTexCoord2f(0f, 4f); gl.glVertex3f(0, 0, 40);
gl.glTexCoord2f(10f,4f); gl.glVertex3f(100, 0, 40);
gl.glTexCoord2f(10f,0f); gl.glVertex3f(100, 0, 0);
gl.glTexCoord2f(0f, 0f); gl.glVertex3f(0, 0, 0);
gl.glTexCoord2f(0f, 5f); gl.glVertex3f(0, 0, 100);
gl.glTexCoord2f(1f, 5f); gl.glVertex3f(10, 0, 100);
gl.glTexCoord2f(1f, 0f); gl.glVertex3f(10, 0, 40);
gl.glTexCoord2f(0f, 0f); gl.glVertex3f(0, 0, 40);
gl.glTexCoord2f(0f, 5f); gl.glVertex3f(90, 0, 100);
gl.glTexCoord2f(1f, 5f); gl.glVertex3f(100, 0, 100);
gl.glTexCoord2f(1f, 0f); gl.glVertex3f(100, 0, 40);
gl.glTexCoord2f(0f, 0f); gl.glVertex3f(90, 0, 40);
gl.glTexCoord2f(0f, 1f); gl.glVertex3f(10, 0, 100);
gl.glTexCoord2f(8f, 1f); gl.glVertex3f(90, 0, 100);
gl.glTexCoord2f(8f, 0f); gl.glVertex3f(90, 0, 90);
gl.glTexCoord2f(0f, 0f); gl.glVertex3f(10, 0, 90);
gl.glEnd();
ceiling.bind(gl); // Where the garden will go
gl.glBegin(GL2.GL_QUADS);
gl.glTexCoord2f(0f,0f); gl.glVertex3f(10, 30, 40);
gl.glTexCoord2f(1f,0f); gl.glVertex3f(90, 30, 40);
gl.glTexCoord2f(1f,1f); gl.glVertex3f(90, 30, 90);
gl.glTexCoord2f(0f,1f); gl.glVertex3f(10, 30, 90);
gl.glEnd();
bruins.bind(gl);
gl.glBegin(GL2.GL_QUADS);
gl.glTexCoord2f(0f,0f); gl.glVertex3f(45, .2f, 60);
gl.glTexCoord2f(1f,0f); gl.glVertex3f(55, .2f, 60);
gl.glTexCoord2f(1f,1f); gl.glVertex3f(55, .2f, 70);
gl.glTexCoord2f(0f,1f); gl.glVertex3f(45, .2f, 70);
gl.glEnd();
gl.glPushMatrix();
gl.glRotatef(90, 1, 0, 0);
gl.glTranslatef(5f, 5f, -4f);
drawTree(gl, glu);
gl.glTranslatef(90f, 0f, 0f);
drawTree(gl, glu);
gl.glTranslatef(0f, 90f, 0f);
drawTree(gl, glu);
gl.glTranslatef(-90f, 0f, 0f);
drawTree(gl, glu);
gl.glPopMatrix();
gl.glDisable(GL2.GL_TEXTURE_2D);
}
public void drawTree(GL2 gl, GLU glu) {
wood.bind(gl);
glu.gluCylinder(quadric, .75, .75, 4, 10, 10);
gl.glTranslatef(0f, 0f, -15f);
tree.bind(gl);
glu.gluCylinder(quadric, 0, 3, 15, 10, 10);
gl.glTranslatef(0f, 0f, 15f);
}
public void drawWalls(GL2 gl, GLU glu) {
gl.glEnable(GL2.GL_CULL_FACE);
gl.glEnable(GL2.GL_TEXTURE_2D);
// Inside of the big walls
bruinsWalls.bind(gl);
gl.glBegin(GL2.GL_QUADS);
// Inside of front wall (front face)
gl.glTexCoord2f(0f,0f); gl.glVertex3f(10, 0, 40);
gl.glTexCoord2f(0f,1f); gl.glVertex3f(90, 0, 40);
gl.glTexCoord2f(1f,1f); gl.glVertex3f(90, 30, 40);
gl.glTexCoord2f(1f,0f); gl.glVertex3f(10, 30, 40);
// Inside of back wall (back face)
gl.glTexCoord2f(1f,1f); gl.glVertex3f(10, 30, 90);
gl.glTexCoord2f(1f,0f); gl.glVertex3f(90, 30, 90);
gl.glTexCoord2f(0f,0f); gl.glVertex3f(90, 0, 90);
gl.glTexCoord2f(0f,1f); gl.glVertex3f(10, 0, 90);
gl.glEnd();
// Inside of the side walls
sideWalls.bind(gl);
gl.glBegin(GL2.GL_QUADS);
// Inside of right wall (back face)
gl.glTexCoord2f(1f,1f); gl.glVertex3f(10, 30, 40);
gl.glTexCoord2f(1f,0f); gl.glVertex3f(10, 30, 62);
gl.glTexCoord2f(0f,0f); gl.glVertex3f(10, 0, 62);
gl.glTexCoord2f(0f,1f); gl.glVertex3f(10, 0, 40);
gl.glTexCoord2f(1f,1f); gl.glVertex3f(10, 30, 68);
gl.glTexCoord2f(1f,0f); gl.glVertex3f(10, 30, 90);
gl.glTexCoord2f(0f,0f); gl.glVertex3f(10, 0, 90);
gl.glTexCoord2f(0f,1f); gl.glVertex3f(10, 0, 68);
// Inside of left wall (front face)
gl.glTexCoord2f(1f,1f); gl.glVertex3f(90, 30, 62);
gl.glTexCoord2f(1f,0f); gl.glVertex3f(90, 30, 40);
gl.glTexCoord2f(0f,0f); gl.glVertex3f(90, 0, 40);
gl.glTexCoord2f(0f,1f); gl.glVertex3f(90, 0, 62);
gl.glTexCoord2f(1f,1f); gl.glVertex3f(90, 30, 90);
gl.glTexCoord2f(1f,0f); gl.glVertex3f(90, 30, 68);
gl.glTexCoord2f(0f,0f); gl.glVertex3f(90, 0, 68);
gl.glTexCoord2f(0f,1f); gl.glVertex3f(90, 0, 90);
gl.glEnd();
black.bind(gl);
gl.glBegin(GL2.GL_QUADS);
gl.glTexCoord2f(1f,1f); gl.glVertex3f(10, 30, 62);
gl.glTexCoord2f(1f,0f); gl.glVertex3f(10, 30, 68);
gl.glTexCoord2f(0f,0f); gl.glVertex3f(10, 10, 68);
gl.glTexCoord2f(0f,1f); gl.glVertex3f(10, 10, 62);
gl.glTexCoord2f(1f,1f); gl.glVertex3f(90, 30, 68);
gl.glTexCoord2f(1f,0f); gl.glVertex3f(90, 30, 62);
gl.glTexCoord2f(0f,0f); gl.glVertex3f(90, 10, 62);
gl.glTexCoord2f(0f,1f); gl.glVertex3f(90, 10, 68);
gl.glEnd();
// Outside walls
garden.bind(gl);
gl.glBegin(GL2.GL_QUADS);
// Outside of front wall (back face)
gl.glTexCoord2f(0f,1f); gl.glVertex3f(10, 0, 40);
gl.glTexCoord2f(0f,0f); gl.glVertex3f(10, 30, 40);
gl.glTexCoord2f(1f,0f); gl.glVertex3f(90, 30, 40);
gl.glTexCoord2f(1f,1f); gl.glVertex3f(90, 0, 40);
// Outside of back wall (front face)
gl.glTexCoord2f(0f,1f); gl.glVertex3f(10, 0, 90);
gl.glTexCoord2f(0f,0f); gl.glVertex3f(90, 0, 90);
gl.glTexCoord2f(1f,0f); gl.glVertex3f(90, 30, 90);
gl.glTexCoord2f(1f,1f); gl.glVertex3f(10, 30, 90);
// Outside of right wall (front face)
gl.glTexCoord2f(1f,1f); gl.glVertex3f(10, 0, 40);
gl.glTexCoord2f(1f,0f); gl.glVertex3f(10, 0, 62);
gl.glTexCoord2f(0f,0f); gl.glVertex3f(10, 30, 62);
gl.glTexCoord2f(0f,1f); gl.glVertex3f(10, 30, 40);
gl.glTexCoord2f(1f,1f); gl.glVertex3f(10, 10, 62);
gl.glTexCoord2f(1f,0f); gl.glVertex3f(10, 10, 68);
gl.glTexCoord2f(0f,0f); gl.glVertex3f(10, 30, 68);
gl.glTexCoord2f(0f,1f); gl.glVertex3f(10, 30, 62);
gl.glTexCoord2f(1f,1f); gl.glVertex3f(10, 0, 68);
gl.glTexCoord2f(1f,0f); gl.glVertex3f(10, 0, 90);
gl.glTexCoord2f(0f,0f); gl.glVertex3f(10, 30, 90);
gl.glTexCoord2f(0f,1f); gl.glVertex3f(10, 30, 68);
// Outside of left wall (back face)
gl.glTexCoord2f(1f,1f); gl.glVertex3f(90, 0, 62);
gl.glTexCoord2f(1f,0f); gl.glVertex3f(90, 0, 40);
gl.glTexCoord2f(0f,0f); gl.glVertex3f(90, 30, 40);
gl.glTexCoord2f(0f,1f); gl.glVertex3f(90, 30, 62);
gl.glTexCoord2f(1f,1f); gl.glVertex3f(90, 10, 68);
gl.glTexCoord2f(1f,0f); gl.glVertex3f(90, 10, 62);
gl.glTexCoord2f(0f,0f); gl.glVertex3f(90, 30, 62);
gl.glTexCoord2f(0f,1f); gl.glVertex3f(90, 30, 68);
gl.glTexCoord2f(1f,1f); gl.glVertex3f(90, 0, 90);
gl.glTexCoord2f(1f,0f); gl.glVertex3f(90, 0, 68);
gl.glTexCoord2f(0f,0f); gl.glVertex3f(90, 30, 68);
gl.glTexCoord2f(0f,1f); gl.glVertex3f(90, 30, 90);
gl.glEnd();
// Cones on the corners
black.bind(gl);
gl.glPushMatrix();
gl.glTranslated(12, 30, 42);
gl.glRotated(-90, 1, 0, 0);
glu.gluCylinder(quadric, .5f, 0, 20, 10, 10);
gl.glPopMatrix();
gl.glPushMatrix();
gl.glTranslated(12, 30, 88);
gl.glRotated(-90, 1, 0, 0);
glu.gluCylinder(quadric, .5f, 0, 20, 10, 10);
gl.glPopMatrix();
gl.glPushMatrix();
gl.glTranslated(88, 30, 42);
gl.glRotated(-90, 1, 0, 0);
glu.gluCylinder(quadric, .5f, 0, 20, 10, 10);
gl.glPopMatrix();
gl.glPushMatrix();
gl.glTranslated(88, 30, 88);
gl.glRotated(-90, 1, 0, 0);
glu.gluCylinder(quadric, .5f, 0, 20, 10, 10);
gl.glPopMatrix();
gl.glDisable(GL2.GL_TEXTURE_2D);
gl.glDisable(GL2.GL_CULL_FACE);
gl.glEnable(GL2.GL_TEXTURE_2D);
white.bind(gl);
gl.glBegin(GL2.GL_QUADS);
gl.glTexCoord2f(1f,1f); gl.glVertex3f(10, -.1f, 90);
gl.glTexCoord2f(1f,0f); gl.glVertex3f(10, -.1f, 40);
gl.glTexCoord2f(0f,0f); gl.glVertex3f(90, -.1f, 40);
gl.glTexCoord2f(0f,1f); gl.glVertex3f(90, -.1f, 90);
gl.glEnd();
gl.glDisable(GL2.GL_TEXTURE_2D);
}
public void drawSign(GL2 gl, GLU glu) {
renderer.begin3DRendering();
renderer.setColor(.2f, .2f, .5f, 1f);
renderer.draw3D("NORTH STATION", 10.5f, 23f, 90.1f, .05f);
renderer.setColor(1f, .8f, 0f, 1f);
renderer.draw3D("BOSTON GARDEN", 50f, 23f, 90.1f, .05f);
renderer.end3DRendering();
gl.glPushMatrix();
renderer.begin3DRendering();
gl.glTranslated(89.5, 23, 39.9);
gl.glRotated(180, 0, 1, 0);
renderer.setColor(.2f, .2f, .5f, 1f);
renderer.draw3D("NORTH STATION", 0, 0, 0, .05f);
renderer.setColor(1f, .8f, 0f, 1f);
renderer.draw3D("BOSTON GARDEN", 39.5f, 0, 0, .05f);
renderer.end3DRendering();
gl.glPopMatrix();
}
// Counterclockwise is frontfacing
public void drawRink(GL2 gl, GLU glu) {
gl.glEnable(GL2.GL_TEXTURE_2D);
// 8 Faceoff points
red.bind(gl);
gl.glBegin(GL2.GL_QUADS);
// 4 in the middle of the ice
gl.glVertex3d(38.5, .1, 53.5);
gl.glVertex3d(38.5, .1, 54.5);
gl.glVertex3d(39.5, .1, 54.5);
gl.glVertex3d(39.5, .1, 53.5);
gl.glVertex3d(38.5, .1, 75.5);
gl.glVertex3d(38.5, .1, 76.5);
gl.glVertex3d(39.5, .1, 76.5);
gl.glVertex3d(39.5, .1, 75.5);
gl.glVertex3d(60.5, .1, 53.5);
gl.glVertex3d(60.5, .1, 54.5);
gl.glVertex3d(61.5, .1, 54.5);
gl.glVertex3d(61.5, .1, 53.5);
gl.glVertex3d(60.5, .1, 75.5);
gl.glVertex3d(60.5, .1, 76.5);
gl.glVertex3d(61.5, .1, 76.5);
gl.glVertex3d(61.5, .1, 75.5);
// 4 near the nets
gl.glVertex3d(24.5, .1, 49.5);
gl.glVertex3d(24.5, .1, 50.5);
gl.glVertex3d(25.5, .1, 50.5);
gl.glVertex3d(25.5, .1, 49.5);
gl.glVertex3d(24.5, .1, 79.5);
gl.glVertex3d(24.5, .1, 80.5);
gl.glVertex3d(25.5, .1, 80.5);
gl.glVertex3d(25.5, .1, 79.5);
gl.glVertex3d(74.5, .1, 79.5);
gl.glVertex3d(74.5, .1, 80.5);
gl.glVertex3d(75.5, .1, 80.5);
gl.glVertex3d(75.5, .1, 79.5);
gl.glVertex3d(74.5, .1, 49.5);
gl.glVertex3d(74.5, .1, 50.5);
gl.glVertex3d(75.5, .1, 50.5);
gl.glVertex3d(75.5, .1, 49.5);
// Center line
gl.glVertex3d(49.5, .1, 40);
gl.glVertex3d(49.5, .1, 90);
gl.glVertex3d(51.5, .1, 90);
gl.glVertex3d(51.5, .1, 40);
gl.glEnd();
// Faceoff circles
double x = 0, z = 0, sides = 30;
for (int i = 0; i < 4; i++) {
if (i == 0) {x = 25; z = 50;}
else if (i == 1) {x = 25; z = 80;}
else if (i == 2) {x = 75; z = 50;}
else {x = 75; z = 80;}
gl.glPushMatrix();
gl.glTranslated(x, .2, z);
gl.glRotated(90, 1, 0, 0);
gl.glScaled(7, 7, 7);
gl.glLineWidth(1.5f);
gl.glBegin(GL2.GL_LINE_LOOP );
for (int j = 0; j < sides; j++)
gl.glVertex2d(Math.sin(2 * Math.PI * (j/sides)), Math.cos(2 * Math.PI * (j/sides)));
gl.glEnd();
gl.glPopMatrix();
}
// Goal Posts
gl.glLineWidth(5f);
gl.glBegin(GL2.GL_LINES);
// Left net
gl.glVertex3d(15, 0, 68);
gl.glVertex3d(15, 4, 68);
gl.glVertex3d(15, 4, 68);
gl.glVertex3d(15, 4, 62);
gl.glVertex3d(15, 4, 62);
gl.glVertex3d(15, 0, 62);
gl.glVertex3d(15, 0, 62);
gl.glVertex3d(13, 0, 63);
gl.glVertex3d(13, 0, 63);
gl.glVertex3d(13, 0, 67);
gl.glVertex3d(13, 0, 67);
gl.glVertex3d(15, 0, 68);
// Right net
gl.glVertex3d(85, 0, 68);
gl.glVertex3d(85, 4, 68);
gl.glVertex3d(85, 4, 68);
gl.glVertex3d(85, 4, 62);
gl.glVertex3d(85, 4, 62);
gl.glVertex3d(85, 0, 62);
gl.glVertex3d(85, 0, 62);
gl.glVertex3d(87, 0, 63);
gl.glVertex3d(87, 0, 63);
gl.glVertex3d(87, 0, 67);
gl.glVertex3d(87, 0, 67);
gl.glVertex3d(85, 0, 68);
gl.glEnd();
// 2 Blue lines and endlines
blue.bind(gl);
gl.glBegin(GL2.GL_QUADS);
gl.glVertex3d(34, .1, 40);
gl.glVertex3d(34, .1, 90);
gl.glVertex3d(36, .1, 90);
gl.glVertex3d(36, .1, 40);
gl.glVertex3d(64, .1, 40);
gl.glVertex3d(64, .1, 90);
gl.glVertex3d(66, .1, 90);
gl.glVertex3d(66, .1, 40);
gl.glVertex3d(14.75, .1, 40);
gl.glVertex3d(14.75, .1, 90);
gl.glVertex3d(15.25, .1, 90);
gl.glVertex3d(15.25, .1, 40);
gl.glVertex3d(84.75, .1, 40);
gl.glVertex3d(84.75, .1, 90);
gl.glVertex3d(85.25, .1, 90);
gl.glVertex3d(85.25, .1, 40);
gl.glEnd();
// Creases
gl.glPushMatrix();
gl.glTranslated(15, .2, 65);
gl.glScaled(5, 5, 5);
gl.glRotated(90, 1, 0, 0);
gl.glBegin(GL2.GL_POLYGON);
for (int i = 0; i < sides; i++)
gl.glVertex2d(Math.sin(Math.PI * (i/sides)), Math.cos(Math.PI * (i/sides)));
gl.glEnd();
gl.glPopMatrix();
gl.glPushMatrix();
gl.glTranslated(85, .2, 65);
gl.glScaled(5, 5, 5);
gl.glRotated(180, 0, 1, 0);
gl.glRotated(90, 1, 0, 0);
gl.glBegin(GL2.GL_POLYGON);
for (int i = 0; i < sides; i++)
gl.glVertex2d(Math.sin(Math.PI * (i/sides)), Math.cos(Math.PI * (i/sides)));
gl.glEnd();
gl.glPopMatrix();
// Nets
net.bind(gl);
gl.glBegin(GL2.GL_POLYGON);
gl.glTexCoord2d(5, 0); gl.glVertex3d(13, 0, 63);
gl.glTexCoord2d(5, 5); gl.glVertex3d(15, 4, 62);
gl.glTexCoord2d(0, 5); gl.glVertex3d(15, 0, 62);
gl.glEnd();
gl.glBegin(GL2.GL_POLYGON);
gl.glTexCoord2d(5, 0); gl.glVertex3d(13, 0, 67);
gl.glTexCoord2d(5, 5); gl.glVertex3d(15, 4, 68);
gl.glTexCoord2d(0, 5); gl.glVertex3d(15, 0, 68);
gl.glEnd();
gl.glBegin(GL2.GL_POLYGON);
gl.glTexCoord2d(5, 0); gl.glVertex3d(13, 0, 67);
gl.glTexCoord2d(5, 5); gl.glVertex3d(13, 0, 63);
gl.glTexCoord2d(0, 5); gl.glVertex3d(15, 4, 62);
gl.glTexCoord2d(0, 0); gl.glVertex3d(15, 4, 68);
gl.glEnd();
gl.glBegin(GL2.GL_POLYGON);
gl.glTexCoord2d(5, 0); gl.glVertex3d(87, 0, 63);
gl.glTexCoord2d(5, 5); gl.glVertex3d(85, 4, 62);
gl.glTexCoord2d(0, 5); gl.glVertex3d(85, 0, 62);
gl.glEnd();
gl.glBegin(GL2.GL_POLYGON);
gl.glTexCoord2d(5, 0); gl.glVertex3d(87, 0, 67);
gl.glTexCoord2d(5, 5); gl.glVertex3d(85, 4, 68);
gl.glTexCoord2d(0, 5); gl.glVertex3d(85, 0, 68);
gl.glEnd();
gl.glBegin(GL2.GL_POLYGON);
gl.glTexCoord2d(5, 0); gl.glVertex3d(87, 0, 67);
gl.glTexCoord2d(5, 5); gl.glVertex3d(87, 0, 63);
gl.glTexCoord2d(0, 5); gl.glVertex3d(85, 4, 62);
gl.glTexCoord2d(0, 0); gl.glVertex3d(85, 4, 68);
gl.glEnd();
gl.glDisable(GL2.GL_TEXTURE_2D);
}
public void drawJumbotron(GL2 gl, GLU glu) {
gl.glEnable(GL2.GL_TEXTURE_2D);
jumbo1.bind(gl);
gl.glPushMatrix();
gl.glTranslated(50, 30, 65);
gl.glRotated(frames++, 0, 1, 0);
gl.glTranslated(-50, -30, -65);
gl.glBegin(GL2.GL_QUADS);
gl.glTexCoord2d(0, 0); gl.glVertex3d(43, 30, 58);
gl.glTexCoord2d(1, 0); gl.glVertex3d(57, 30, 58);
gl.glTexCoord2d(1, 1); gl.glVertex3d(55, 15, 60);
gl.glTexCoord2d(0, 1); gl.glVertex3d(45, 15, 60);
gl.glTexCoord2d(1, 0); gl.glVertex3d(43, 30, 72);
gl.glTexCoord2d(0, 0); gl.glVertex3d(57, 30, 72);
gl.glTexCoord2d(0, 1); gl.glVertex3d(55, 15, 70);
gl.glTexCoord2d(1, 1); gl.glVertex3d(45, 15, 70);
gl.glEnd();
jumbo2.bind(gl);
gl.glBegin(GL2.GL_QUADS);
gl.glTexCoord2d(0, 0); gl.glVertex3d(43, 30, 72);
gl.glTexCoord2d(1, 0); gl.glVertex3d(43, 30, 58);
gl.glTexCoord2d(1, 1); gl.glVertex3d(45, 15, 60);
gl.glTexCoord2d(0, 1); gl.glVertex3d(45, 15, 70);
gl.glTexCoord2d(0, 0); gl.glVertex3d(57, 30, 58);
gl.glTexCoord2d(1, 0); gl.glVertex3d(57, 30, 72);
gl.glTexCoord2d(1, 1); gl.glVertex3d(55, 15, 70);
gl.glTexCoord2d(0, 1); gl.glVertex3d(55, 15, 60);
gl.glEnd();
black.bind(gl);
gl.glBegin(GL2.GL_QUADS);
gl.glTexCoord2d(0, 0); gl.glVertex3d(55, 15, 60);
gl.glTexCoord2d(1, 0); gl.glVertex3d(55, 15, 70);
gl.glTexCoord2d(1, 1); gl.glVertex3d(45, 15, 70);
gl.glTexCoord2d(0, 1); gl.glVertex3d(45, 15, 60);
gl.glEnd();
gl.glPopMatrix();
gl.glDisable(GL2.GL_TEXTURE_2D);
}
private void drawPool(GL2 gl, GLU glu) {
gl.glEnable(GL2.GL_TEXTURE_2D);
water.bind(gl);
gl.glBegin(GL2.GL_QUADS);
gl.glTexCoord2d(0, 0); gl.glVertex3d(25, .1, 10);
gl.glTexCoord2d(1, 0); gl.glVertex3d(25, .1, 30);
gl.glTexCoord2d(1, 3); gl.glVertex3d(75, .1, 30);
gl.glTexCoord2d(0, 3); gl.glVertex3d(75, .1, 10);
gl.glEnd();
white.bind(gl);
gl.glColor3d(1, 1, 1);
gl.glBegin(GL2.GL_QUADS);
gl.glVertex3d(23, 2, 19);
gl.glVertex3d(23, 2, 21);
gl.glVertex3d(23, 0, 21);
gl.glVertex3d(23, 0, 19);
gl.glVertex3d(23, 2, 19);
gl.glVertex3d(23, 2, 21);
gl.glVertex3d(30, 2, 21);
gl.glVertex3d(30, 2, 19);
gl.glEnd();
gl.glDisable(GL2.GL_TEXTURE_2D);
}
}
| src/buildings/ShippBuilding.java | package buildings;
import game.Building;
import javax.media.opengl.GL2;
import javax.media.opengl.glu.GLU;
import javax.media.opengl.glu.GLUquadric;
import java.awt.Font;
import com.jogamp.opengl.util.awt.TextRenderer;
import com.jogamp.opengl.util.texture.Texture;
public class ShippBuilding extends Building {
private GLUquadric quadric;
private Texture sidewalk, bruins, wood, tree, garden, bruinsWalls, ceiling,
sideWalls, black, red, blue, net, jumbo1, jumbo2, water, white;
private TextRenderer renderer;
private int fontSize = 88;
private int frames;
public ShippBuilding(GL2 gl, GLU glu) {
quadric = glu.gluNewQuadric();
glu.gluQuadricDrawStyle(quadric, GLU.GLU_FILL); // GLU_POINT, GLU_LINE, GLU_FILL, GLU_SILHOUETTE
glu.gluQuadricNormals (quadric, GLU.GLU_NONE); // GLU_NONE, GLU_FLAT, or GLU_SMOOTH
glu.gluQuadricTexture (quadric, true); // false, or true to generate texture coordinates
net = setupTexture(gl, "ShippNet.png");
sidewalk = setupTexture(gl, "ShippSidewalk.jpg");
bruins = setupTexture(gl, "ShippSpokedB.png");
bruinsWalls = setupTexture(gl, "ShippBruins.gif");
wood = setupTexture(gl, "ShippWood.jpg");
tree = setupTexture(gl, "ShippTree.jpg");
garden = setupTexture(gl, "ShippGardenExterior.jpg");
ceiling = setupTexture(gl, "ShippCeiling.png");
sideWalls = setupTexture(gl, "ShippWallGradient.png");
black = setupTexture(gl, "ShippBlack.png");
red = setupTexture(gl, "ShippRed.png");
blue = setupTexture(gl, "ShippBlue.png");
jumbo1 = setupTexture(gl, "ShippJumbotron1.png");
jumbo2 = setupTexture(gl, "ShippJumbotron2.jpg");
water = setupTexture(gl, "ShippWater.jpg");
white = setupTexture(gl, "ShippWhite.png");
frames = 0;
renderer = new TextRenderer(new Font("SansSerif", Font.BOLD, fontSize));
}
public void draw(GL2 gl, GLU glu) {
drawSidewalkAndTrees(gl, glu);
drawWalls(gl, glu);
drawSign(gl, glu);
drawRink(gl, glu);
drawJumbotron(gl, glu);
drawPool(gl, glu);
}
public void drawSidewalkAndTrees(GL2 gl, GLU glu) {
gl.glEnable(GL2.GL_TEXTURE_2D);
sidewalk.bind(gl); // Sidewalk surrounding the garden
gl.glBegin(GL2.GL_QUADS);
gl.glTexCoord2f(0f, 4f); gl.glVertex3f(0, 0, 40);
gl.glTexCoord2f(10f,4f); gl.glVertex3f(100, 0, 40);
gl.glTexCoord2f(10f,0f); gl.glVertex3f(100, 0, 0);
gl.glTexCoord2f(0f, 0f); gl.glVertex3f(0, 0, 0);
gl.glTexCoord2f(0f, 5f); gl.glVertex3f(0, 0, 100);
gl.glTexCoord2f(1f, 5f); gl.glVertex3f(10, 0, 100);
gl.glTexCoord2f(1f, 0f); gl.glVertex3f(10, 0, 40);
gl.glTexCoord2f(0f, 0f); gl.glVertex3f(0, 0, 40);
gl.glTexCoord2f(0f, 5f); gl.glVertex3f(90, 0, 100);
gl.glTexCoord2f(1f, 5f); gl.glVertex3f(100, 0, 100);
gl.glTexCoord2f(1f, 0f); gl.glVertex3f(100, 0, 40);
gl.glTexCoord2f(0f, 0f); gl.glVertex3f(90, 0, 40);
gl.glTexCoord2f(0f, 1f); gl.glVertex3f(10, 0, 100);
gl.glTexCoord2f(8f, 1f); gl.glVertex3f(90, 0, 100);
gl.glTexCoord2f(8f, 0f); gl.glVertex3f(90, 0, 90);
gl.glTexCoord2f(0f, 0f); gl.glVertex3f(10, 0, 90);
gl.glEnd();
ceiling.bind(gl); // Where the garden will go
gl.glBegin(GL2.GL_QUADS);
gl.glTexCoord2f(0f,0f); gl.glVertex3f(10, 30, 40);
gl.glTexCoord2f(1f,0f); gl.glVertex3f(90, 30, 40);
gl.glTexCoord2f(1f,1f); gl.glVertex3f(90, 30, 90);
gl.glTexCoord2f(0f,1f); gl.glVertex3f(10, 30, 90);
gl.glEnd();
bruins.bind(gl);
gl.glBegin(GL2.GL_QUADS);
gl.glTexCoord2f(0f,0f); gl.glVertex3f(45, .2f, 60);
gl.glTexCoord2f(1f,0f); gl.glVertex3f(55, .2f, 60);
gl.glTexCoord2f(1f,1f); gl.glVertex3f(55, .2f, 70);
gl.glTexCoord2f(0f,1f); gl.glVertex3f(45, .2f, 70);
gl.glEnd();
gl.glPushMatrix();
gl.glRotatef(90, 1, 0, 0);
gl.glTranslatef(5f, 5f, -4f);
drawTree(gl, glu);
gl.glTranslatef(90f, 0f, 0f);
drawTree(gl, glu);
gl.glTranslatef(0f, 90f, 0f);
drawTree(gl, glu);
gl.glTranslatef(-90f, 0f, 0f);
drawTree(gl, glu);
gl.glPopMatrix();
gl.glDisable(GL2.GL_TEXTURE_2D);
}
public void drawTree(GL2 gl, GLU glu) {
wood.bind(gl);
glu.gluCylinder(quadric, .75, .75, 4, 10, 10);
gl.glTranslatef(0f, 0f, -15f);
tree.bind(gl);
glu.gluCylinder(quadric, 0, 3, 15, 10, 10);
gl.glTranslatef(0f, 0f, 15f);
}
public void drawWalls(GL2 gl, GLU glu) {
gl.glEnable(GL2.GL_CULL_FACE);
gl.glEnable(GL2.GL_TEXTURE_2D);
// Inside of the big walls
bruinsWalls.bind(gl);
gl.glBegin(GL2.GL_QUADS);
// Inside of front wall (front face)
gl.glTexCoord2f(0f,0f); gl.glVertex3f(10, 0, 40);
gl.glTexCoord2f(0f,1f); gl.glVertex3f(90, 0, 40);
gl.glTexCoord2f(1f,1f); gl.glVertex3f(90, 30, 40);
gl.glTexCoord2f(1f,0f); gl.glVertex3f(10, 30, 40);
// Inside of back wall (back face)
gl.glTexCoord2f(1f,1f); gl.glVertex3f(10, 30, 90);
gl.glTexCoord2f(1f,0f); gl.glVertex3f(90, 30, 90);
gl.glTexCoord2f(0f,0f); gl.glVertex3f(90, 0, 90);
gl.glTexCoord2f(0f,1f); gl.glVertex3f(10, 0, 90);
gl.glEnd();
// Inside of the side walls
sideWalls.bind(gl);
gl.glBegin(GL2.GL_QUADS);
// Inside of right wall (back face)
gl.glTexCoord2f(1f,1f); gl.glVertex3f(10, 30, 40);
gl.glTexCoord2f(1f,0f); gl.glVertex3f(10, 30, 62);
gl.glTexCoord2f(0f,0f); gl.glVertex3f(10, 0, 62);
gl.glTexCoord2f(0f,1f); gl.glVertex3f(10, 0, 40);
gl.glTexCoord2f(1f,1f); gl.glVertex3f(10, 30, 68);
gl.glTexCoord2f(1f,0f); gl.glVertex3f(10, 30, 90);
gl.glTexCoord2f(0f,0f); gl.glVertex3f(10, 0, 90);
gl.glTexCoord2f(0f,1f); gl.glVertex3f(10, 0, 68);
// Inside of left wall (front face)
gl.glTexCoord2f(1f,1f); gl.glVertex3f(90, 30, 62);
gl.glTexCoord2f(1f,0f); gl.glVertex3f(90, 30, 40);
gl.glTexCoord2f(0f,0f); gl.glVertex3f(90, 0, 40);
gl.glTexCoord2f(0f,1f); gl.glVertex3f(90, 0, 62);
gl.glTexCoord2f(1f,1f); gl.glVertex3f(90, 30, 90);
gl.glTexCoord2f(1f,0f); gl.glVertex3f(90, 30, 68);
gl.glTexCoord2f(0f,0f); gl.glVertex3f(90, 0, 68);
gl.glTexCoord2f(0f,1f); gl.glVertex3f(90, 0, 90);
gl.glEnd();
black.bind(gl);
gl.glBegin(GL2.GL_QUADS);
gl.glTexCoord2f(1f,1f); gl.glVertex3f(10, 30, 62);
gl.glTexCoord2f(1f,0f); gl.glVertex3f(10, 30, 68);
gl.glTexCoord2f(0f,0f); gl.glVertex3f(10, 10, 68);
gl.glTexCoord2f(0f,1f); gl.glVertex3f(10, 10, 62);
gl.glTexCoord2f(1f,1f); gl.glVertex3f(90, 30, 68);
gl.glTexCoord2f(1f,0f); gl.glVertex3f(90, 30, 62);
gl.glTexCoord2f(0f,0f); gl.glVertex3f(90, 10, 62);
gl.glTexCoord2f(0f,1f); gl.glVertex3f(90, 10, 68);
gl.glEnd();
// Outside walls
garden.bind(gl);
gl.glBegin(GL2.GL_QUADS);
// Outside of front wall (back face)
gl.glTexCoord2f(0f,1f); gl.glVertex3f(10, 0, 40);
gl.glTexCoord2f(0f,0f); gl.glVertex3f(10, 30, 40);
gl.glTexCoord2f(1f,0f); gl.glVertex3f(90, 30, 40);
gl.glTexCoord2f(1f,1f); gl.glVertex3f(90, 0, 40);
// Outside of back wall (front face)
gl.glTexCoord2f(0f,1f); gl.glVertex3f(10, 0, 90);
gl.glTexCoord2f(0f,0f); gl.glVertex3f(90, 0, 90);
gl.glTexCoord2f(1f,0f); gl.glVertex3f(90, 30, 90);
gl.glTexCoord2f(1f,1f); gl.glVertex3f(10, 30, 90);
// Outside of right wall (front face)
gl.glTexCoord2f(1f,1f); gl.glVertex3f(10, 0, 40);
gl.glTexCoord2f(1f,0f); gl.glVertex3f(10, 0, 62);
gl.glTexCoord2f(0f,0f); gl.glVertex3f(10, 30, 62);
gl.glTexCoord2f(0f,1f); gl.glVertex3f(10, 30, 40);
gl.glTexCoord2f(1f,1f); gl.glVertex3f(10, 10, 62);
gl.glTexCoord2f(1f,0f); gl.glVertex3f(10, 10, 68);
gl.glTexCoord2f(0f,0f); gl.glVertex3f(10, 30, 68);
gl.glTexCoord2f(0f,1f); gl.glVertex3f(10, 30, 62);
gl.glTexCoord2f(1f,1f); gl.glVertex3f(10, 0, 68);
gl.glTexCoord2f(1f,0f); gl.glVertex3f(10, 0, 90);
gl.glTexCoord2f(0f,0f); gl.glVertex3f(10, 30, 90);
gl.glTexCoord2f(0f,1f); gl.glVertex3f(10, 30, 68);
// Outside of left wall (back face)
gl.glTexCoord2f(1f,1f); gl.glVertex3f(90, 0, 62);
gl.glTexCoord2f(1f,0f); gl.glVertex3f(90, 0, 40);
gl.glTexCoord2f(0f,0f); gl.glVertex3f(90, 30, 40);
gl.glTexCoord2f(0f,1f); gl.glVertex3f(90, 30, 62);
gl.glTexCoord2f(1f,1f); gl.glVertex3f(90, 10, 68);
gl.glTexCoord2f(1f,0f); gl.glVertex3f(90, 10, 62);
gl.glTexCoord2f(0f,0f); gl.glVertex3f(90, 30, 62);
gl.glTexCoord2f(0f,1f); gl.glVertex3f(90, 30, 68);
gl.glTexCoord2f(1f,1f); gl.glVertex3f(90, 0, 90);
gl.glTexCoord2f(1f,0f); gl.glVertex3f(90, 0, 68);
gl.glTexCoord2f(0f,0f); gl.glVertex3f(90, 30, 68);
gl.glTexCoord2f(0f,1f); gl.glVertex3f(90, 30, 90);
gl.glEnd();
// Cones on the corners
black.bind(gl);
gl.glPushMatrix();
gl.glTranslated(12, 30, 42);
gl.glRotated(-90, 1, 0, 0);
glu.gluCylinder(quadric, .5f, 0, 20, 10, 10);
gl.glPopMatrix();
gl.glPushMatrix();
gl.glTranslated(12, 30, 88);
gl.glRotated(-90, 1, 0, 0);
glu.gluCylinder(quadric, .5f, 0, 20, 10, 10);
gl.glPopMatrix();
gl.glPushMatrix();
gl.glTranslated(88, 30, 42);
gl.glRotated(-90, 1, 0, 0);
glu.gluCylinder(quadric, .5f, 0, 20, 10, 10);
gl.glPopMatrix();
gl.glPushMatrix();
gl.glTranslated(88, 30, 88);
gl.glRotated(-90, 1, 0, 0);
glu.gluCylinder(quadric, .5f, 0, 20, 10, 10);
gl.glPopMatrix();
gl.glDisable(GL2.GL_TEXTURE_2D);
gl.glDisable(GL2.GL_CULL_FACE);
}
public void drawSign(GL2 gl, GLU glu) {
renderer.begin3DRendering();
renderer.setColor(.2f, .2f, .5f, 1f);
renderer.draw3D("NORTH STATION", 10.5f, 23f, 90.1f, .05f);
renderer.setColor(1f, .8f, 0f, 1f);
renderer.draw3D("BOSTON GARDEN", 50f, 23f, 90.1f, .05f);
renderer.end3DRendering();
gl.glPushMatrix();
renderer.begin3DRendering();
gl.glTranslated(89.5, 23, 39.9);
gl.glRotated(180, 0, 1, 0);
renderer.setColor(.2f, .2f, .5f, 1f);
renderer.draw3D("NORTH STATION", 0, 0, 0, .05f);
renderer.setColor(1f, .8f, 0f, 1f);
renderer.draw3D("BOSTON GARDEN", 39.5f, 0, 0, .05f);
renderer.end3DRendering();
gl.glPopMatrix();
}
// Counterclockwise is frontfacing
public void drawRink(GL2 gl, GLU glu) {
gl.glEnable(GL2.GL_TEXTURE_2D);
// 8 Faceoff points
red.bind(gl);
gl.glBegin(GL2.GL_QUADS);
// 4 in the middle of the ice
gl.glVertex3d(38.5, .1, 53.5);
gl.glVertex3d(38.5, .1, 54.5);
gl.glVertex3d(39.5, .1, 54.5);
gl.glVertex3d(39.5, .1, 53.5);
gl.glVertex3d(38.5, .1, 75.5);
gl.glVertex3d(38.5, .1, 76.5);
gl.glVertex3d(39.5, .1, 76.5);
gl.glVertex3d(39.5, .1, 75.5);
gl.glVertex3d(60.5, .1, 53.5);
gl.glVertex3d(60.5, .1, 54.5);
gl.glVertex3d(61.5, .1, 54.5);
gl.glVertex3d(61.5, .1, 53.5);
gl.glVertex3d(60.5, .1, 75.5);
gl.glVertex3d(60.5, .1, 76.5);
gl.glVertex3d(61.5, .1, 76.5);
gl.glVertex3d(61.5, .1, 75.5);
// 4 near the nets
gl.glVertex3d(24.5, .1, 49.5);
gl.glVertex3d(24.5, .1, 50.5);
gl.glVertex3d(25.5, .1, 50.5);
gl.glVertex3d(25.5, .1, 49.5);
gl.glVertex3d(24.5, .1, 79.5);
gl.glVertex3d(24.5, .1, 80.5);
gl.glVertex3d(25.5, .1, 80.5);
gl.glVertex3d(25.5, .1, 79.5);
gl.glVertex3d(74.5, .1, 79.5);
gl.glVertex3d(74.5, .1, 80.5);
gl.glVertex3d(75.5, .1, 80.5);
gl.glVertex3d(75.5, .1, 79.5);
gl.glVertex3d(74.5, .1, 49.5);
gl.glVertex3d(74.5, .1, 50.5);
gl.glVertex3d(75.5, .1, 50.5);
gl.glVertex3d(75.5, .1, 49.5);
// Center line
gl.glVertex3d(49.5, .1, 40);
gl.glVertex3d(49.5, .1, 90);
gl.glVertex3d(51.5, .1, 90);
gl.glVertex3d(51.5, .1, 40);
gl.glEnd();
// Faceoff circles
double x = 0, z = 0, sides = 30;
for (int i = 0; i < 4; i++) {
if (i == 0) {x = 25; z = 50;}
else if (i == 1) {x = 25; z = 80;}
else if (i == 2) {x = 75; z = 50;}
else {x = 75; z = 80;}
gl.glPushMatrix();
gl.glTranslated(x, .2, z);
gl.glRotated(90, 1, 0, 0);
gl.glScaled(7, 7, 7);
gl.glLineWidth(1.5f);
gl.glBegin(GL2.GL_LINE_LOOP );
for (int j = 0; j < sides; j++)
gl.glVertex2d(Math.sin(2 * Math.PI * (j/sides)), Math.cos(2 * Math.PI * (j/sides)));
gl.glEnd();
gl.glPopMatrix();
}
// Goal Posts
gl.glLineWidth(5f);
gl.glBegin(GL2.GL_LINES);
// Left net
gl.glVertex3d(15, 0, 68);
gl.glVertex3d(15, 4, 68);
gl.glVertex3d(15, 4, 68);
gl.glVertex3d(15, 4, 62);
gl.glVertex3d(15, 4, 62);
gl.glVertex3d(15, 0, 62);
gl.glVertex3d(15, 0, 62);
gl.glVertex3d(13, 0, 63);
gl.glVertex3d(13, 0, 63);
gl.glVertex3d(13, 0, 67);
gl.glVertex3d(13, 0, 67);
gl.glVertex3d(15, 0, 68);
// Right net
gl.glVertex3d(85, 0, 68);
gl.glVertex3d(85, 4, 68);
gl.glVertex3d(85, 4, 68);
gl.glVertex3d(85, 4, 62);
gl.glVertex3d(85, 4, 62);
gl.glVertex3d(85, 0, 62);
gl.glVertex3d(85, 0, 62);
gl.glVertex3d(87, 0, 63);
gl.glVertex3d(87, 0, 63);
gl.glVertex3d(87, 0, 67);
gl.glVertex3d(87, 0, 67);
gl.glVertex3d(85, 0, 68);
gl.glEnd();
// 2 Blue lines and endlines
blue.bind(gl);
gl.glBegin(GL2.GL_QUADS);
gl.glVertex3d(34, .1, 40);
gl.glVertex3d(34, .1, 90);
gl.glVertex3d(36, .1, 90);
gl.glVertex3d(36, .1, 40);
gl.glVertex3d(64, .1, 40);
gl.glVertex3d(64, .1, 90);
gl.glVertex3d(66, .1, 90);
gl.glVertex3d(66, .1, 40);
gl.glVertex3d(14.75, .1, 40);
gl.glVertex3d(14.75, .1, 90);
gl.glVertex3d(15.25, .1, 90);
gl.glVertex3d(15.25, .1, 40);
gl.glVertex3d(84.75, .1, 40);
gl.glVertex3d(84.75, .1, 90);
gl.glVertex3d(85.25, .1, 90);
gl.glVertex3d(85.25, .1, 40);
gl.glEnd();
// Creases
gl.glPushMatrix();
gl.glTranslated(15, .2, 65);
gl.glScaled(5, 5, 5);
gl.glRotated(90, 1, 0, 0);
gl.glBegin(GL2.GL_POLYGON);
for (int i = 0; i < sides; i++)
gl.glVertex2d(Math.sin(Math.PI * (i/sides)), Math.cos(Math.PI * (i/sides)));
gl.glEnd();
gl.glPopMatrix();
gl.glPushMatrix();
gl.glTranslated(85, .2, 65);
gl.glScaled(5, 5, 5);
gl.glRotated(180, 0, 1, 0);
gl.glRotated(90, 1, 0, 0);
gl.glBegin(GL2.GL_POLYGON);
for (int i = 0; i < sides; i++)
gl.glVertex2d(Math.sin(Math.PI * (i/sides)), Math.cos(Math.PI * (i/sides)));
gl.glEnd();
gl.glPopMatrix();
// Nets
net.bind(gl);
gl.glBegin(GL2.GL_POLYGON);
gl.glTexCoord2d(5, 0); gl.glVertex3d(13, 0, 63);
gl.glTexCoord2d(5, 5); gl.glVertex3d(15, 4, 62);
gl.glTexCoord2d(0, 5); gl.glVertex3d(15, 0, 62);
gl.glEnd();
gl.glBegin(GL2.GL_POLYGON);
gl.glTexCoord2d(5, 0); gl.glVertex3d(13, 0, 67);
gl.glTexCoord2d(5, 5); gl.glVertex3d(15, 4, 68);
gl.glTexCoord2d(0, 5); gl.glVertex3d(15, 0, 68);
gl.glEnd();
gl.glBegin(GL2.GL_POLYGON);
gl.glTexCoord2d(5, 0); gl.glVertex3d(13, 0, 67);
gl.glTexCoord2d(5, 5); gl.glVertex3d(13, 0, 63);
gl.glTexCoord2d(0, 5); gl.glVertex3d(15, 4, 62);
gl.glTexCoord2d(0, 0); gl.glVertex3d(15, 4, 68);
gl.glEnd();
gl.glBegin(GL2.GL_POLYGON);
gl.glTexCoord2d(5, 0); gl.glVertex3d(87, 0, 63);
gl.glTexCoord2d(5, 5); gl.glVertex3d(85, 4, 62);
gl.glTexCoord2d(0, 5); gl.glVertex3d(85, 0, 62);
gl.glEnd();
gl.glBegin(GL2.GL_POLYGON);
gl.glTexCoord2d(5, 0); gl.glVertex3d(87, 0, 67);
gl.glTexCoord2d(5, 5); gl.glVertex3d(85, 4, 68);
gl.glTexCoord2d(0, 5); gl.glVertex3d(85, 0, 68);
gl.glEnd();
gl.glBegin(GL2.GL_POLYGON);
gl.glTexCoord2d(5, 0); gl.glVertex3d(87, 0, 67);
gl.glTexCoord2d(5, 5); gl.glVertex3d(87, 0, 63);
gl.glTexCoord2d(0, 5); gl.glVertex3d(85, 4, 62);
gl.glTexCoord2d(0, 0); gl.glVertex3d(85, 4, 68);
gl.glEnd();
gl.glDisable(GL2.GL_TEXTURE_2D);
}
public void drawJumbotron(GL2 gl, GLU glu) {
gl.glEnable(GL2.GL_TEXTURE_2D);
jumbo1.bind(gl);
gl.glPushMatrix();
gl.glTranslated(50, 30, 65);
gl.glRotated(frames++, 0, 1, 0);
gl.glTranslated(-50, -30, -65);
gl.glBegin(GL2.GL_QUADS);
gl.glTexCoord2d(0, 0); gl.glVertex3d(43, 30, 58);
gl.glTexCoord2d(1, 0); gl.glVertex3d(57, 30, 58);
gl.glTexCoord2d(1, 1); gl.glVertex3d(55, 15, 60);
gl.glTexCoord2d(0, 1); gl.glVertex3d(45, 15, 60);
gl.glTexCoord2d(1, 0); gl.glVertex3d(43, 30, 72);
gl.glTexCoord2d(0, 0); gl.glVertex3d(57, 30, 72);
gl.glTexCoord2d(0, 1); gl.glVertex3d(55, 15, 70);
gl.glTexCoord2d(1, 1); gl.glVertex3d(45, 15, 70);
gl.glEnd();
jumbo2.bind(gl);
gl.glBegin(GL2.GL_QUADS);
gl.glTexCoord2d(0, 0); gl.glVertex3d(43, 30, 72);
gl.glTexCoord2d(1, 0); gl.glVertex3d(43, 30, 58);
gl.glTexCoord2d(1, 1); gl.glVertex3d(45, 15, 60);
gl.glTexCoord2d(0, 1); gl.glVertex3d(45, 15, 70);
gl.glTexCoord2d(0, 0); gl.glVertex3d(57, 30, 58);
gl.glTexCoord2d(1, 0); gl.glVertex3d(57, 30, 72);
gl.glTexCoord2d(1, 1); gl.glVertex3d(55, 15, 70);
gl.glTexCoord2d(0, 1); gl.glVertex3d(55, 15, 60);
gl.glEnd();
black.bind(gl);
gl.glBegin(GL2.GL_QUADS);
gl.glTexCoord2d(0, 0); gl.glVertex3d(55, 15, 60);
gl.glTexCoord2d(1, 0); gl.glVertex3d(55, 15, 70);
gl.glTexCoord2d(1, 1); gl.glVertex3d(45, 15, 70);
gl.glTexCoord2d(0, 1); gl.glVertex3d(45, 15, 60);
gl.glEnd();
gl.glPopMatrix();
gl.glDisable(GL2.GL_TEXTURE_2D);
}
private void drawPool(GL2 gl, GLU glu) {
gl.glEnable(GL2.GL_TEXTURE_2D);
water.bind(gl);
gl.glBegin(GL2.GL_QUADS);
gl.glTexCoord2d(0, 0); gl.glVertex3d(25, .1, 10);
gl.glTexCoord2d(1, 0); gl.glVertex3d(25, .1, 30);
gl.glTexCoord2d(1, 3); gl.glVertex3d(75, .1, 30);
gl.glTexCoord2d(0, 3); gl.glVertex3d(75, .1, 10);
gl.glEnd();
white.bind(gl);
gl.glColor3d(1, 1, 1);
gl.glBegin(GL2.GL_QUADS);
gl.glVertex3d(23, 2, 19);
gl.glVertex3d(23, 2, 21);
gl.glVertex3d(23, 0, 21);
gl.glVertex3d(23, 0, 19);
gl.glVertex3d(23, 2, 19);
gl.glVertex3d(23, 2, 21);
gl.glVertex3d(30, 2, 21);
gl.glVertex3d(30, 2, 19);
gl.glEnd();
gl.glDisable(GL2.GL_TEXTURE_2D);
}
}
| Fixes to my building
Added motion and made the ice white | src/buildings/ShippBuilding.java | Fixes to my building Added motion and made the ice white |
|
Java | mit | a569ee12d27445020f7a47826d4d03e5b7a7d004 | 0 | classgraph/classgraph,lukehutch/fast-classpath-scanner,lukehutch/fast-classpath-scanner | /*
* This file is part of FastClasspathScanner.
*
* Author: Luke Hutchison
*
* Hosted at: https://github.com/lukehutch/fast-classpath-scanner
*
* --
*
* The MIT License (MIT)
*
* Copyright (c) 2018 Luke Hutchison
*
* 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 io.github.lukehutch.fastclasspathscanner.scanner;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import io.github.lukehutch.fastclasspathscanner.json.JSONDeserializer;
import io.github.lukehutch.fastclasspathscanner.json.JSONSerializer;
import io.github.lukehutch.fastclasspathscanner.utils.AutoCloseableList;
import io.github.lukehutch.fastclasspathscanner.utils.ClassLoaderAndModuleFinder;
import io.github.lukehutch.fastclasspathscanner.utils.GraphvizDotfileGenerator;
import io.github.lukehutch.fastclasspathscanner.utils.InterruptionChecker;
import io.github.lukehutch.fastclasspathscanner.utils.JarUtils;
import io.github.lukehutch.fastclasspathscanner.utils.JarfileMetadataReader;
import io.github.lukehutch.fastclasspathscanner.utils.LogNode;
import io.github.lukehutch.fastclasspathscanner.utils.NestedJarHandler;
/** The result of a scan. */
public class ScanResult {
/** The scan spec. */
transient ScanSpec scanSpec;
/** The order of unique classpath elements. */
transient List<ClasspathElement> classpathOrder;
/** The list of all files that were found in whitelisted packages. */
transient AutoCloseableList<ClasspathResource> allResources;
/**
* The default order in which ClassLoaders are called to load classes. Used when a specific class does not have
* a record of which ClassLoader provided the URL used to locate the class (e.g. if the class is found using
* java.class.path).
*/
private transient ClassLoader[] envClassLoaderOrder;
/** The nested jar handler instance. */
private transient NestedJarHandler nestedJarHandler;
/**
* The file, directory and jarfile resources timestamped during a scan, along with their timestamp at the time
* of the scan. For jarfiles, the timestamp represents the timestamp of all files within the jar. May be null,
* if this ScanResult object is the result of a call to FastClasspathScanner#getUniqueClasspathElementsAsync().
*/
private transient Map<File, Long> fileToLastModified;
/**
* The class graph builder. May be null, if this ScanResult object is the result of a call to
* FastClasspathScanner#getUniqueClasspathElementsAsync().
*/
Map<String, ClassInfo> classNameToClassInfo;
/** The interruption checker. */
transient InterruptionChecker interruptionChecker;
/** The log. */
transient LogNode log;
/** Called after deserialization. */
void setFields(final ScanSpec scanSpec) {
for (final ClassInfo classInfo : classNameToClassInfo.values()) {
classInfo.setFields(scanSpec);
classInfo.setScanResult(this);
}
}
// -------------------------------------------------------------------------------------------------------------
/** The result of a scan. Make sure you call complete() after calling the constructor. */
ScanResult(final ScanSpec scanSpec, final List<ClasspathElement> classpathOrder,
final ClassLoader[] envClassLoaderOrder, final Map<String, ClassInfo> classNameToClassInfo,
final Map<File, Long> fileToLastModified, final NestedJarHandler nestedJarHandler,
final InterruptionChecker interruptionChecker, final LogNode log) {
this.scanSpec = scanSpec;
this.classpathOrder = classpathOrder;
for (final ClasspathElement classpathElt : classpathOrder) {
if (classpathElt.fileMatches != null) {
if (allResources == null) {
allResources = new AutoCloseableList<>();
}
allResources.addAll(classpathElt.fileMatches);
}
}
this.envClassLoaderOrder = envClassLoaderOrder;
this.fileToLastModified = fileToLastModified;
this.classNameToClassInfo = classNameToClassInfo;
this.nestedJarHandler = nestedJarHandler;
this.interruptionChecker = interruptionChecker;
this.log = log;
// Add some post-scan backrefs from info objects to this ScanResult and to the scan spec
if (classNameToClassInfo != null) {
setFields(scanSpec);
}
}
// -------------------------------------------------------------------------------------------------------------
/**
* Returns the list of File objects for unique classpath elements (directories or jarfiles), in classloader
* resolution order.
*
* @return The unique classpath elements.
*/
public List<File> getUniqueClasspathElements() {
final List<File> classpathElementOrderFiles = new ArrayList<>();
for (final ClasspathElement classpathElement : classpathOrder) {
final ModuleRef modRef = classpathElement.getClasspathElementModuleRef();
if (modRef != null) {
if (!modRef.isSystemModule()) {
// Add module files when they don't have a "jrt:/" scheme
classpathElementOrderFiles.add(modRef.getModuleLocationFile());
}
} else {
classpathElementOrderFiles.add(classpathElement.getClasspathElementFile(log));
}
}
return classpathElementOrderFiles;
}
/**
* Returns all unique directories or zip/jarfiles on the classpath, in classloader resolution order, as a
* classpath string, delineated with the standard path separator character.
*
* @return a the unique directories and jarfiles on the classpath, in classpath resolution order, as a path
* string.
*/
public String getUniqueClasspathElementsAsPathStr() {
return JarUtils.pathElementsToPathStr(getUniqueClasspathElements());
}
/**
* Returns the list of unique classpath element paths as URLs, in classloader resolution order.
*
* @return The unique classpath element URLs.
*/
public List<URL> getUniqueClasspathElementURLs() {
final List<URL> classpathElementOrderURLs = new ArrayList<>();
for (final ClasspathElement classpathElement : classpathOrder) {
final ModuleRef modRef = classpathElement.getClasspathElementModuleRef();
if (modRef != null) {
// Add module URLs whether or not they have a "jrt:/" scheme
try {
classpathElementOrderURLs.add(modRef.getModuleLocation().toURL());
} catch (final MalformedURLException e) {
// Skip malformed URLs (shouldn't happen)
}
} else {
try {
classpathElementOrderURLs.add(classpathElement.getClasspathElementFile(log).toURI().toURL());
} catch (final MalformedURLException e) {
// Shouldn't happen
}
}
}
return classpathElementOrderURLs;
}
// -------------------------------------------------------------------------------------------------------------
/** Get a list of all resources (including classfiles and non-classfiles) found in whitelisted packages. */
public AutoCloseableList<ClasspathResource> getAllResources() {
if (allResources == null || allResources.isEmpty()) {
return new AutoCloseableList<>(1);
} else {
return allResources;
}
}
/**
* Get a list of all resources found in whitelisted packages that have a path (relative to the package root of
* the classpath element) matching the requested path.
*/
public AutoCloseableList<ClasspathResource> getAllResourcesWithPath(final String resourcePath) {
if (allResources == null || allResources.isEmpty()) {
return new AutoCloseableList<>(1);
} else {
String path = resourcePath;
while (path.startsWith("/")) {
path = path.substring(1);
}
final AutoCloseableList<ClasspathResource> filteredResources = new AutoCloseableList<>();
for (final ClasspathResource classpathResource : allResources) {
if (classpathResource.getPathRelativeToPackageRoot().equals(path)) {
filteredResources.add(classpathResource);
}
}
return filteredResources;
}
}
/**
* Get a list of all resources found in whitelisted packages that have a path (relative to the package root of
* the classpath element) that starts with the requested path.
*/
public AutoCloseableList<ClasspathResource> getResourcesWithPathPrefix(final String resourcePathPrefix) {
if (allResources == null || allResources.isEmpty()) {
return new AutoCloseableList<>(1);
} else {
String pathPrefix = resourcePathPrefix;
while (pathPrefix.startsWith("/")) {
pathPrefix = pathPrefix.substring(1);
}
if (!pathPrefix.endsWith("/") && !pathPrefix.isEmpty()) {
pathPrefix = pathPrefix + "/";
}
final AutoCloseableList<ClasspathResource> filteredResources = new AutoCloseableList<>();
for (final ClasspathResource classpathResource : allResources) {
if (classpathResource.getPathRelativeToPackageRoot().startsWith(pathPrefix)) {
filteredResources.add(classpathResource);
}
}
return filteredResources;
}
}
/** Get a list of all resources found in whitelisted packages that have the requested leafname. */
public AutoCloseableList<ClasspathResource> getResourcesWithLeafName(final String leafName) {
if (allResources == null || allResources.isEmpty()) {
return new AutoCloseableList<>(1);
} else {
final AutoCloseableList<ClasspathResource> filteredResources = new AutoCloseableList<>();
for (final ClasspathResource classpathResource : allResources) {
final String relativePath = classpathResource.getPathRelativeToPackageRoot();
final int lastSlashIdx = relativePath.lastIndexOf('/');
if (relativePath.substring(lastSlashIdx + 1).equals(leafName)) {
filteredResources.add(classpathResource);
}
}
return filteredResources;
}
}
/**
* Get a list of all resources found in whitelisted packages that have the requested extension (e.g. "xml" to
* match all files ending in ".xml").
*/
public AutoCloseableList<ClasspathResource> getResourcesWithExtension(final String extension) {
if (allResources == null || allResources.isEmpty()) {
return new AutoCloseableList<>(1);
} else {
final AutoCloseableList<ClasspathResource> filteredResources = new AutoCloseableList<>();
for (final ClasspathResource classpathResource : allResources) {
final String relativePath = classpathResource.getPathRelativeToPackageRoot();
final int lastSlashIdx = relativePath.lastIndexOf('/');
final int lastDotIdx = relativePath.lastIndexOf('.');
if (lastDotIdx > lastSlashIdx) {
if (relativePath.substring(lastDotIdx + 1).equalsIgnoreCase(extension)) {
filteredResources.add(classpathResource);
}
}
}
return filteredResources;
}
}
/**
* Get a list of all resources found in whitelisted packages that have a path matching the requested pattern.
*/
public AutoCloseableList<ClasspathResource> getResourcesMatchingPattern(final Pattern pattern) {
if (allResources == null || allResources.isEmpty()) {
return new AutoCloseableList<>(1);
} else {
final AutoCloseableList<ClasspathResource> filteredResources = new AutoCloseableList<>();
for (final ClasspathResource classpathResource : allResources) {
final String relativePath = classpathResource.getPathRelativeToPackageRoot();
if (pattern.matcher(relativePath).matches()) {
filteredResources.add(classpathResource);
}
}
return filteredResources;
}
}
// -------------------------------------------------------------------------------------------------------------
/**
* Determine whether the classpath contents have been modified since the last scan. Checks the timestamps of
* files and jarfiles encountered during the previous scan to see if they have changed. Does not perform a full
* scan, so cannot detect the addition of directories that newly match whitelist criteria -- you need to perform
* a full scan to detect those changes.
*
* @return true if the classpath contents have been modified since the last scan.
*/
public boolean classpathContentsModifiedSinceScan() {
if (fileToLastModified == null) {
return true;
} else {
for (final Entry<File, Long> ent : fileToLastModified.entrySet()) {
if (ent.getKey().lastModified() != ent.getValue()) {
return true;
}
}
return false;
}
}
/**
* Find the maximum last-modified timestamp of any whitelisted file/directory/jarfile encountered during the
* scan. Checks the current timestamps, so this should increase between calls if something changes in
* whitelisted paths. Assumes both file and system timestamps were generated from clocks whose time was
* accurate. Ignores timestamps greater than the system time.
*
* <p>
* This method cannot in general tell if classpath has changed (or modules have been added or removed) if it is
* run twice during the same runtime session.
*
* @return the maximum last-modified time for whitelisted files/directories/jars encountered during the scan.
*/
public long classpathContentsLastModifiedTime() {
long maxLastModifiedTime = 0L;
if (fileToLastModified != null) {
final long currTime = System.currentTimeMillis();
for (final long timestamp : fileToLastModified.values()) {
if (timestamp > maxLastModifiedTime && timestamp < currTime) {
maxLastModifiedTime = timestamp;
}
}
}
return maxLastModifiedTime;
}
// -------------------------------------------------------------------------------------------------------------
// Classes
/**
* Get the ClassInfo object for the named class, or null if no class of the requested name was found in a
* whitelisted/non-blacklisted package during scanning.
*
* @return The ClassInfo object for the named class, or null if the class was not found.
*/
public ClassInfo getClassInfo(final String className) {
return classNameToClassInfo.get(className);
}
/**
* Get all classes, interfaces and annotations found during the scan.
*
* @return A list of all whitelisted classes found during the scan, or the empty list if none.
*/
public ClassInfoList getAllClasses() {
return ClassInfo.getAllClasses(classNameToClassInfo.values(), scanSpec, this);
}
/**
* Get all standard (non-interface/non-annotation) classes found during the scan.
*
* @return A list of all whitelisted standard classes found during the scan, or the empty list if none.
*/
public ClassInfoList getAllStandardClasses() {
return ClassInfo.getAllStandardClasses(classNameToClassInfo.values(), scanSpec, this);
}
/**
* Get all subclasses of the named superclass.
*
* @param superclassName
* The name of the superclass.
* @return A list of subclasses of the named superclass, or the empty list if none.
*/
public ClassInfoList getSubclassesOf(final String superclassName) {
final ClassInfo superclass = classNameToClassInfo.get(superclassName);
return superclass == null ? ClassInfoList.EMPTY_LIST : superclass.getSubclasses();
}
/**
* Get superclasses of the named subclass.
*
* @param subclassName
* The name of the subclass.
* @return A list of superclasses of the named subclass, or the empty list if none.
*/
public ClassInfoList getSuperclassesOf(final String subclassName) {
final ClassInfo subclass = classNameToClassInfo.get(subclassName);
return subclass == null ? ClassInfoList.EMPTY_LIST : subclass.getSuperclasses();
}
/**
* Get classes that have a method with an annotation of the named type.
*
* @param annotationName
* the name of the method annotation.
* @return The sorted list of classes with a method that has an annotation of the named type, or the empty list
* if none.
*/
public ClassInfoList getClassesWithMethodAnnotation(final String annotationName) {
if (!scanSpec.enableMethodInfo) {
throw new IllegalArgumentException(
"Please call FastClasspathScanner#enableMethodInfo() before calling scan() -- "
+ "method annotation indexing is disabled by default for efficiency");
}
final ClassInfo classInfo = classNameToClassInfo.get(annotationName);
return classInfo == null ? ClassInfoList.EMPTY_LIST : classInfo.getClassesWithMethodAnnotation();
}
/**
* Get classes that have a field with an annotation of the named type.
*
* @param annotationName
* the name of the field annotation.
* @return The sorted list of classes that have a field with an annotation of the named type, or the empty list
* if none.
*/
public ClassInfoList getClassesWithFieldAnnotation(final String annotationName) {
if (!scanSpec.enableFieldInfo) {
throw new IllegalArgumentException(
"Please call FastClasspathScanner#enableFieldAnnotationIndexing() before calling scan() -- "
+ "field annotation indexing is disabled by default for efficiency");
}
final ClassInfo classInfo = classNameToClassInfo.get(annotationName);
return classInfo == null ? ClassInfoList.EMPTY_LIST : classInfo.getClassesWithFieldAnnotation();
}
// -------------------------------------------------------------------------------------------------------------
// Interfaces
/**
* Get all interface classes found during the scan, not including annotations. See also
* {@link #getAllInterfaceOrAnnotationClasses()}.
*
* @return A list of all whitelisted interfaces found during the scan, or the empty list if none.
*/
public ClassInfoList getAllInterfaceClasses() {
return ClassInfo.getAllImplementedInterfaceClasses(classNameToClassInfo.values(), scanSpec, this);
}
/**
* Get all subinterfaces of the named interface.
*
* @param interfaceName
* The interface name.
* @return The sorted list of all subinterfaces of the named interface, or the empty list if none.
*/
public ClassInfoList getSubinterfacesOf(final String interfaceName) {
final ClassInfo classInfo = classNameToClassInfo.get(interfaceName);
return classInfo == null ? ClassInfoList.EMPTY_LIST : classInfo.getSubinterfaces();
}
/**
* Get all superinterfaces of the named interface.
*
* @param subInterfaceName
* The subinterface name.
* @return The sorted list of superinterfaces of the named subinterface, or the empty list if none.
*/
public ClassInfoList getSuperinterfacesOf(final String subInterfaceName) {
final ClassInfo classInfo = classNameToClassInfo.get(subInterfaceName);
return classInfo == null ? ClassInfoList.EMPTY_LIST : classInfo.getSuperinterfaces();
}
/**
* Get all classes that implement (or have superclasses that implement) the named interface (or one of its
* subinterfaces).
*
* @param interfaceName
* The interface name.
* @return The sorted list of all classes that implement the named interface, or the empty list if none.
*/
public ClassInfoList getClassesImplementing(final String interfaceName) {
final ClassInfo classInfo = classNameToClassInfo.get(interfaceName);
return classInfo == null ? ClassInfoList.EMPTY_LIST : classInfo.getClassesImplementing();
}
// -------------------------------------------------------------------------------------------------------------
// Annotations
/**
* Get all annotation classes found during the scan. See also {@link #getAllInterfaceOrAnnotationClasses()}.
*
* @return A list of all annotation classes found during the scan, or the empty list if none.
*/
public ClassInfoList getAllAnnotationClasses() {
return ClassInfo.getAllAnnotationClasses(classNameToClassInfo.values(), scanSpec, this);
}
/**
* Get all interface or annotation classes found during the scan. (Annotations are technically interfaces, and
* they can be implemented.)
*
* @return A list of all whitelisted interfaces found during the scan, or the empty list if none.
*/
public ClassInfoList getAllInterfaceOrAnnotationClasses() {
return ClassInfo.getAllInterfaceOrAnnotationClasses(classNameToClassInfo.values(), scanSpec, this);
}
/**
* Get non-annotation classes with the named class annotation or meta-annotation.
*
* @param annotationName
* The name of the class annotation or meta-annotation.
* @return The sorted list of all non-annotation classes that were found with the named class annotation during
* the scan, or the empty list if none.
*/
public ClassInfoList getClassesWithAnnotation(final String annotationName) {
final ClassInfo classInfo = classNameToClassInfo.get(annotationName);
return classInfo == null ? ClassInfoList.EMPTY_LIST : classInfo.getClassesWithAnnotation();
}
/**
* Get all annotations and meta-annotations on the named class.
*
* @param className
* The class name.
* @return The sorted list of annotations and meta-annotations on the named class, or the empty list if none.
*/
public ClassInfoList getAnnotationsOnClass(final String className) {
final ClassInfo classInfo = classNameToClassInfo.get(className);
return classInfo == null ? ClassInfoList.EMPTY_LIST : classInfo.getAnnotations();
}
// -------------------------------------------------------------------------------------------------------------
/**
* Generate a .dot file which can be fed into GraphViz for layout and visualization of the class graph. The
* sizeX and sizeY parameters are the image output size to use (in inches) when GraphViz is asked to render the
* .dot file.
*
* <p>
* Note that if you call this with showFields or showMethods set to false, but with method and/or field info
* enabled during scanning, then arrows will still be added between classes even if the field or method that
* created that dependency is not shown.
*
* @param sizeX
* The GraphViz layout width in inches.
* @param sizeY
* The GraphViz layout width in inches.
* @param showFields
* If true, show fields within class nodes in the graph. To show field info,
* {@link io.github.lukehutch.fastclasspathscanner.FastClasspathScanner#enableFieldInfo()} should be
* called before scanning. You may also want to call
* {@link io.github.lukehutch.fastclasspathscanner.FastClasspathScanner#ignoreFieldVisibility()}
* before scanning, to show non-public fields.
* @param showMethods
* If true, show methods within class nodes in the graph. To show method info,
* {@link io.github.lukehutch.fastclasspathscanner.FastClasspathScanner#enableMethodInfo()} should be
* called before scanning. You may also want to call
* {@link io.github.lukehutch.fastclasspathscanner.FastClasspathScanner#ignoreMethodVisibility()}
* before scanning, to show non-public methods.
* @return the GraphViz file contents.
*/
public String generateClassGraphDotFile(final float sizeX, final float sizeY, final boolean showFields,
final boolean showMethods) {
return GraphvizDotfileGenerator.generateClassGraphDotFile(this, sizeX, sizeY, showFields, showMethods,
scanSpec);
}
/**
* Generate a .dot file which can be fed into GraphViz for layout and visualization of the class graph. Methods
* and fields are shown, if method and field info have been enabled respectively, via
* {@link io.github.lukehutch.fastclasspathscanner.FastClasspathScanner#enableMethodInfo()} and
* {@link io.github.lukehutch.fastclasspathscanner.FastClasspathScanner#enableFieldInfo()}. Only public
* methods/fields are shown, unless
* {@link io.github.lukehutch.fastclasspathscanner.FastClasspathScanner#ignoreMethodVisibility()} and/or
* {@link io.github.lukehutch.fastclasspathscanner.FastClasspathScanner#ignoreFieldVisibility()} has been
* called. The sizeX and sizeY parameters are the image output size to use (in inches) when GraphViz is asked to
* render the .dot file.
*
* @param sizeX
* The GraphViz layout width in inches.
* @param sizeY
* The GraphViz layout width in inches.
* @return the GraphViz file contents.
*/
public String generateClassGraphDotFile(final float sizeX, final float sizeY) {
return generateClassGraphDotFile(sizeX, sizeY, /* showFields = */ true, /* showMethods = */ true);
}
/**
* Generate a .dot file which can be fed into GraphViz for layout and visualization of the class graph. Methods
* and fields are shown, if method and field info have been enabled respectively, via
* {@link io.github.lukehutch.fastclasspathscanner.FastClasspathScanner#enableMethodInfo()} and
* {@link io.github.lukehutch.fastclasspathscanner.FastClasspathScanner#enableFieldInfo()}. Only public
* methods/fields are shown, unless
* {@link io.github.lukehutch.fastclasspathscanner.FastClasspathScanner#ignoreMethodVisibility()} and/or
* {@link io.github.lukehutch.fastclasspathscanner.FastClasspathScanner#ignoreFieldVisibility()} has been
* called. The size defaults to 10.5 x 8 inches.
*
* @return the GraphViz file contents.
*/
public String generateClassGraphDotFile() {
return generateClassGraphDotFile(/* sizeX = */ 10.5f, /* sizeY = */ 8f, /* showFields = */ true,
/* showMethods = */ true);
}
// -------------------------------------------------------------------------------------------------------------
/**
* Call the classloader using Class.forName(className, initializeLoadedClasses, classLoader), for all known
* ClassLoaders, until one is able to load the class, or until there are no more ClassLoaders to try.
*
* @throw IllegalArgumentException if LinkageError (including ExceptionInInitializerError) is thrown, or if no
* ClassLoader is able to load the class.
* @return a reference to the loaded class, or null if the class could not be found.
*/
private Class<?> loadClass(final String className, final ClassLoader classLoader, final LogNode log)
throws IllegalArgumentException {
try {
return Class.forName(className, scanSpec.initializeLoadedClasses, classLoader);
} catch (final ClassNotFoundException e) {
return null;
} catch (final Throwable e) {
throw new IllegalArgumentException("Exception while loading class " + className, e);
}
}
/**
* Call the classloader using Class.forName(className, initializeLoadedClasses, classLoader), for all known
* ClassLoaders, until one is able to load the class, or until there are no more ClassLoaders to try.
*
* @throw IllegalArgumentException if LinkageError (including ExceptionInInitializerError) is thrown, or if
* returnNullIfClassNotFound is false and no ClassLoader is able to load the class.
* @return a reference to the loaded class, or null if returnNullIfClassNotFound was true and the class could
* not be loaded.
*/
Class<?> loadClass(final String className, final boolean returnNullIfClassNotFound, final LogNode log)
throws IllegalArgumentException {
if (scanSpec.overrideClasspath != null) {
// Unfortunately many surprises can result when overriding classpath (e.g. the wrong class definition
// could be loaded, if a class is defined more than once in the classpath). Even when overriding the
// ClassLoaders, a class may not be able to be cast to its superclass, if the class and its superclass
// are loaded into different classloaders, possibly due to accidental loading and caching in the
// non-custom classloader). Basically if you're overriding the classpath and/or defining custom
// classloaders, bad things will probably happen at some point!
if (log != null) {
log.log("When loading classes from a custom classpath, defined using .overrideClasspath(), "
+ "the correct classloader for the requested class " + className
+ " cannot reliably be determined. Will try loading the class using the default context "
+ "classLoader (which may or may not even be able to find the class). "
+ "Preferably always use .overrideClassLoaders() instead.");
}
}
if (className == null || className.isEmpty()) {
throw new IllegalArgumentException("Cannot load class -- class names cannot be null or empty");
}
// Try loading class via each classloader in turn
final ClassInfo classInfo = classNameToClassInfo.get(className);
final ClassLoader[] classLoadersForClass = classInfo != null ? classInfo.classLoaders : envClassLoaderOrder;
if (classLoadersForClass != null) {
for (final ClassLoader classLoader : classLoadersForClass) {
final Class<?> classRef = loadClass(className, classLoader, log);
if (classRef != null) {
return classRef;
}
}
}
// Try with null (bootstrap) ClassLoader
final Class<?> classRef = loadClass(className, /* classLoader = */ null, log);
if (classRef != null) {
return classRef;
}
// If this class came from a jarfile with a package root (e.g. a Spring-Boot jar, with packages rooted
// at BOOT-INF/classes), then the problem is probably that the jarfile was on the classpath, but the
// scanner is not running inside the jar itself, so the necessary ClassLoader for the jar is not
// available. Unzip the jar starting from the package root, and create a URLClassLoader to load classes
// from the unzipped jar. (This is only done once per jar and package root, using the singleton pattern.)
if (classInfo != null && nestedJarHandler != null) {
try {
ClassLoader customClassLoader = null;
if (classInfo.classpathElementFile.isDirectory()) {
// Should not happen, but we should handle this anyway -- create a URLClassLoader for the dir
customClassLoader = new URLClassLoader(
new URL[] { classInfo.classpathElementFile.toURI().toURL() });
} else {
// Get the outermost jar containing this jarfile, so that if a lib jar was extracted during
// scanning, we obtain the classloader from the outer jar. This is needed so that package roots
// and lib jars are loaded from the same classloader.
final File outermostJar = nestedJarHandler.getOutermostJar(classInfo.classpathElementFile);
// Get jarfile metadata for classpath element jarfile
final JarfileMetadataReader jarfileMetadataReader = //
nestedJarHandler.getJarfileMetadataReader(outermostJar, "", log);
// Create a custom ClassLoader for the jarfile. This might be time consuming, as it could
// trigger the extraction of all classes (for a classpath root other than ""), and/or any
// lib jars (e.g. in BOOT-INF/lib).
customClassLoader = jarfileMetadataReader.getCustomClassLoader(nestedJarHandler, log);
}
if (customClassLoader != null) {
final Class<?> classRefFromCustomClassLoader = loadClass(className, customClassLoader, log);
if (classRefFromCustomClassLoader != null) {
return classRefFromCustomClassLoader;
}
} else {
if (log != null) {
log.log("Unable to create custom classLoader to load class " + className);
}
}
} catch (final Throwable e) {
if (log != null) {
log.log("Exception while trying to load class " + className + " : " + e);
}
}
}
// Could not load class
if (!returnNullIfClassNotFound) {
throw new IllegalArgumentException("No classloader was able to load class " + className);
} else {
if (log != null) {
log.log("No classloader was able to load class " + className);
}
return null;
}
}
// -------------------------------------------------------------------------------------------------------------
/**
* Produce Class reference given a class name. If ignoreExceptions is false, and the class cannot be loaded (due
* to classloading error, or due to an exception being thrown in the class initialization block), an
* IllegalArgumentException is thrown; otherwise, the class will simply be skipped if an exception is thrown.
*
* <p>
* Enable verbose scanning to see details of any exceptions thrown during classloading, even if ignoreExceptions
* is false.
*
* @param className
* the class to load.
* @param ignoreExceptions
* If true, null is returned if there was an exception during classloading, otherwise
* IllegalArgumentException is thrown if a class could not be loaded.
* @throws IllegalArgumentException
* if ignoreExceptions is false, IllegalArgumentException is thrown if there were problems loading
* or initializing the class. (Note that class initialization on load is disabled by default, you
* can enable it with {@code FastClasspathScanner#initializeLoadedClasses(true)} .) Otherwise
* exceptions are suppressed, and null is returned if any of these problems occurs.
* @return a reference to the loaded class, or null if the class could not be loaded and ignoreExceptions is
* true.
*/
Class<?> classNameToClassRef(final String className, final boolean ignoreExceptions)
throws IllegalArgumentException {
try {
return loadClass(className, /* returnNullIfClassNotFound = */ ignoreExceptions, log);
} catch (final Throwable e) {
if (ignoreExceptions) {
return null;
} else {
throw new IllegalArgumentException("Could not load class " + className, e);
}
} finally {
// Manually flush log, since this method is called after scanning is complete
if (log != null) {
log.flush();
}
}
}
/**
* Produce Class reference given a class name. If ignoreExceptions is false, and the class cannot be loaded (due
* to classloading error, or due to an exception being thrown in the class initialization block), an
* IllegalArgumentException is thrown; otherwise, the class will simply be skipped if an exception is thrown.
*
* <p>
* Enable verbose scanning to see details of any exceptions thrown during classloading, even if ignoreExceptions
* is false.
*
* @param className
* the class to load.
* @param classType
* The class type to cast the result to.
* @param ignoreExceptions
* If true, null is returned if there was an exception during classloading, otherwise
* IllegalArgumentException is thrown if a class could not be loaded.
* @throws IllegalArgumentException
* if ignoreExceptions is false, IllegalArgumentException is thrown if there were problems loading
* the class, initializing the class, or casting it to the requested type. (Note that class
* initialization on load is disabled by default, you can enable it with
* {@code FastClasspathScanner#initializeLoadedClasses(true)} .) Otherwise exceptions are
* suppressed, and null is returned if any of these problems occurs.
* @return a reference to the loaded class, or null if the class could not be loaded and ignoreExceptions is
* true.
*/
<T> Class<T> classNameToClassRef(final String className, final Class<T> classType,
final boolean ignoreExceptions) throws IllegalArgumentException {
try {
if (classType == null) {
if (ignoreExceptions) {
return null;
} else {
throw new IllegalArgumentException("classType parameter cannot be null");
}
}
final Class<?> loadedClass = loadClass(className, /* returnNullIfClassNotFound = */ ignoreExceptions,
log);
if (loadedClass != null && !classType.isAssignableFrom(loadedClass)) {
if (ignoreExceptions) {
return null;
} else {
throw new IllegalArgumentException(
"Loaded class " + loadedClass.getName() + " cannot be cast to " + classType.getName());
}
}
@SuppressWarnings("unchecked")
final Class<T> castClass = (Class<T>) loadedClass;
return castClass;
} catch (final Throwable e) {
if (ignoreExceptions) {
return null;
} else {
throw new IllegalArgumentException("Could not load class " + className, e);
}
} finally {
// Manually flush log, since this method is called after scanning is complete
if (log != null) {
log.flush();
}
}
}
// -------------------------------------------------------------------------------------------------------------
/** The current serialization format. */
private static final String CURRENT_SERIALIZATION_FORMAT = "4";
/** A class to hold a serialized ScanResult along with the ScanSpec that was used to scan. */
private static class SerializationFormat {
public String serializationFormat;
public ScanSpec scanSpec;
public List<ClassInfo> allClassInfo;
@SuppressWarnings("unused")
public SerializationFormat() {
}
public SerializationFormat(final String serializationFormat, final ScanSpec scanSpec,
final Map<String, ClassInfo> classNameToClassInfo) {
this.serializationFormat = serializationFormat;
this.scanSpec = scanSpec;
this.allClassInfo = new ArrayList<>(classNameToClassInfo.values());
}
}
/** Deserialize a ScanResult from previously-saved JSON. */
public static ScanResult fromJSON(final String json) {
final Matcher matcher = Pattern.compile("\\{[\\n\\r ]*\"serializationFormat\"[ ]?:[ ]?\"([^\"]+)\"")
.matcher(json);
if (!matcher.find()) {
throw new IllegalArgumentException("JSON is not in correct format");
}
if (!CURRENT_SERIALIZATION_FORMAT.equals(matcher.group(1))) {
throw new IllegalArgumentException(
"JSON was serialized in a different format from the format used by the current version of "
+ "FastClasspathScanner -- please serialize and deserialize your ScanResult using "
+ "the same version of FastClasspathScanner");
}
final SerializationFormat deserialized = JSONDeserializer.deserializeObject(SerializationFormat.class,
json);
if (!deserialized.serializationFormat.equals(CURRENT_SERIALIZATION_FORMAT)) {
// Probably the deserialization failed before now anyway, if fields have changed, etc.
throw new IllegalArgumentException("JSON was serialized by newer version of FastClasspathScanner");
}
final ClassLoader[] envClassLoaderOrder = new ClassLoaderAndModuleFinder(deserialized.scanSpec,
/* log = */ null).getClassLoaders();
final Map<String, ClassInfo> classNameToClassInfo = new HashMap<>();
for (final ClassInfo ci : deserialized.allClassInfo) {
classNameToClassInfo.put(ci.getClassName(), ci);
}
final ScanResult scanResult = new ScanResult(deserialized.scanSpec,
Collections.<ClasspathElement> emptyList(), envClassLoaderOrder, classNameToClassInfo,
/* fileToLastModified = */ null, /* nestedJarHandler = */ null, /* interruptionChecker = */ null,
/* log = */ null);
return scanResult;
}
/**
* Serialize a ScanResult to JSON.
*
* @param indentWidth
* If greater than 0, JSON will be formatted (indented), otherwise it will be minified (un-indented).
*/
public String toJSON(final int indentWidth) {
return JSONSerializer.serializeObject(
new SerializationFormat(CURRENT_SERIALIZATION_FORMAT, scanSpec, classNameToClassInfo), indentWidth,
false);
}
/** Serialize a ScanResult to minified (un-indented) JSON. */
public String toJSON() {
return toJSON(0);
}
// -------------------------------------------------------------------------------------------------------------
/**
* Free any temporary files created by extracting jars from within jars. By default, temporary files are removed
* at the end of a scan, after MatchProcessors have completed, so this typically does not need to be called. The
* case where it might need to be called is if the list of classpath elements has been fetched, and the
* classpath contained jars within jars. Without calling this method, the temporary files created by extracting
* the inner jars will not be removed until the temporary file system cleans them up (typically at reboot).
*
* @param log
* The log.
*/
public void freeTempFiles(final LogNode log) {
if (allResources != null) {
for (final ClasspathResource classpathResource : allResources) {
classpathResource.close();
}
}
if (nestedJarHandler != null) {
nestedJarHandler.close(log);
}
}
@Override
protected void finalize() throws Throwable {
// NestedJarHandler also adds a runtime shutdown hook, since finalizers are not reliable
freeTempFiles(null);
}
}
| src/main/java/io/github/lukehutch/fastclasspathscanner/scanner/ScanResult.java | /*
* This file is part of FastClasspathScanner.
*
* Author: Luke Hutchison
*
* Hosted at: https://github.com/lukehutch/fast-classpath-scanner
*
* --
*
* The MIT License (MIT)
*
* Copyright (c) 2018 Luke Hutchison
*
* 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 io.github.lukehutch.fastclasspathscanner.scanner;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import io.github.lukehutch.fastclasspathscanner.json.JSONDeserializer;
import io.github.lukehutch.fastclasspathscanner.json.JSONSerializer;
import io.github.lukehutch.fastclasspathscanner.utils.AutoCloseableList;
import io.github.lukehutch.fastclasspathscanner.utils.ClassLoaderAndModuleFinder;
import io.github.lukehutch.fastclasspathscanner.utils.GraphvizDotfileGenerator;
import io.github.lukehutch.fastclasspathscanner.utils.InterruptionChecker;
import io.github.lukehutch.fastclasspathscanner.utils.JarUtils;
import io.github.lukehutch.fastclasspathscanner.utils.JarfileMetadataReader;
import io.github.lukehutch.fastclasspathscanner.utils.LogNode;
import io.github.lukehutch.fastclasspathscanner.utils.NestedJarHandler;
/** The result of a scan. */
public class ScanResult {
/** The scan spec. */
transient ScanSpec scanSpec;
/** The order of unique classpath elements. */
transient List<ClasspathElement> classpathOrder;
/** The list of all files that were found in whitelisted packages. */
transient AutoCloseableList<ClasspathResource> allResources;
/**
* The default order in which ClassLoaders are called to load classes. Used when a specific class does not have
* a record of which ClassLoader provided the URL used to locate the class (e.g. if the class is found using
* java.class.path).
*/
private transient ClassLoader[] envClassLoaderOrder;
/** The nested jar handler instance. */
private transient NestedJarHandler nestedJarHandler;
/**
* The file, directory and jarfile resources timestamped during a scan, along with their timestamp at the time
* of the scan. For jarfiles, the timestamp represents the timestamp of all files within the jar. May be null,
* if this ScanResult object is the result of a call to FastClasspathScanner#getUniqueClasspathElementsAsync().
*/
private transient Map<File, Long> fileToLastModified;
/**
* The class graph builder. May be null, if this ScanResult object is the result of a call to
* FastClasspathScanner#getUniqueClasspathElementsAsync().
*/
Map<String, ClassInfo> classNameToClassInfo;
/** The interruption checker. */
transient InterruptionChecker interruptionChecker;
/** The log. */
transient LogNode log;
/** Called after deserialization. */
void setFields(final ScanSpec scanSpec) {
for (final ClassInfo classInfo : classNameToClassInfo.values()) {
classInfo.setFields(scanSpec);
classInfo.setScanResult(this);
}
}
// -------------------------------------------------------------------------------------------------------------
/** The result of a scan. Make sure you call complete() after calling the constructor. */
ScanResult(final ScanSpec scanSpec, final List<ClasspathElement> classpathOrder,
final ClassLoader[] envClassLoaderOrder, final Map<String, ClassInfo> classNameToClassInfo,
final Map<File, Long> fileToLastModified, final NestedJarHandler nestedJarHandler,
final InterruptionChecker interruptionChecker, final LogNode log) {
this.scanSpec = scanSpec;
this.classpathOrder = classpathOrder;
for (final ClasspathElement classpathElt : classpathOrder) {
if (classpathElt.fileMatches != null) {
if (allResources == null) {
allResources = new AutoCloseableList<>();
}
allResources.addAll(classpathElt.fileMatches);
}
}
this.envClassLoaderOrder = envClassLoaderOrder;
this.fileToLastModified = fileToLastModified;
this.classNameToClassInfo = classNameToClassInfo;
this.nestedJarHandler = nestedJarHandler;
this.interruptionChecker = interruptionChecker;
this.log = log;
// Add some post-scan backrefs from info objects to this ScanResult and to the scan spec
if (classNameToClassInfo != null) {
setFields(scanSpec);
}
}
// -------------------------------------------------------------------------------------------------------------
/**
* Returns the list of File objects for unique classpath elements (directories or jarfiles), in classloader
* resolution order.
*
* @return The unique classpath elements.
*/
public List<File> getUniqueClasspathElements() {
final List<File> classpathElementOrderFiles = new ArrayList<>();
for (final ClasspathElement classpathElement : classpathOrder) {
final ModuleRef modRef = classpathElement.getClasspathElementModuleRef();
if (modRef != null) {
if (!modRef.isSystemModule()) {
// Add module files when they don't have a "jrt:/" scheme
classpathElementOrderFiles.add(modRef.getModuleLocationFile());
}
} else {
classpathElementOrderFiles.add(classpathElement.getClasspathElementFile(log));
}
}
return classpathElementOrderFiles;
}
/**
* Returns all unique directories or zip/jarfiles on the classpath, in classloader resolution order, as a
* classpath string, delineated with the standard path separator character.
*
* @return a the unique directories and jarfiles on the classpath, in classpath resolution order, as a path
* string.
*/
public String getUniqueClasspathElementsAsPathStr() {
return JarUtils.pathElementsToPathStr(getUniqueClasspathElements());
}
/**
* Returns the list of unique classpath element paths as URLs, in classloader resolution order.
*
* @return The unique classpath element URLs.
*/
public List<URL> getUniqueClasspathElementURLs() {
final List<URL> classpathElementOrderURLs = new ArrayList<>();
for (final ClasspathElement classpathElement : classpathOrder) {
final ModuleRef modRef = classpathElement.getClasspathElementModuleRef();
if (modRef != null) {
// Add module URLs whether or not they have a "jrt:/" scheme
try {
classpathElementOrderURLs.add(modRef.getModuleLocation().toURL());
} catch (final MalformedURLException e) {
// Skip malformed URLs (shouldn't happen)
}
} else {
try {
classpathElementOrderURLs.add(classpathElement.getClasspathElementFile(log).toURI().toURL());
} catch (final MalformedURLException e) {
// Shouldn't happen
}
}
}
return classpathElementOrderURLs;
}
// -------------------------------------------------------------------------------------------------------------
/** Get a list of all resources (including classfiles and non-classfiles) found in whitelisted packages. */
public AutoCloseableList<ClasspathResource> getAllResources() {
if (allResources == null || allResources.isEmpty()) {
return new AutoCloseableList<>(1);
} else {
return allResources;
}
}
/**
* Get a list of all resources found in whitelisted packages that have a path (relative to the package root of
* the classpath element) matching the requested path.
*/
public AutoCloseableList<ClasspathResource> getAllResourcesWithPath(final String resourcePath) {
if (allResources == null || allResources.isEmpty()) {
return new AutoCloseableList<>(1);
} else {
String path = resourcePath;
while (path.startsWith("/")) {
path = path.substring(1);
}
final AutoCloseableList<ClasspathResource> filteredResources = new AutoCloseableList<>();
for (final ClasspathResource classpathResource : allResources) {
if (classpathResource.getPathRelativeToPackageRoot().equals(path)) {
filteredResources.add(classpathResource);
}
}
return filteredResources;
}
}
/**
* Get a list of all resources found in whitelisted packages that have a path (relative to the package root of
* the classpath element) that starts with the requested path.
*/
public AutoCloseableList<ClasspathResource> getAllResourcesWithPathPrefix(final String resourcePathPrefix) {
if (allResources == null || allResources.isEmpty()) {
return new AutoCloseableList<>(1);
} else {
String pathPrefix = resourcePathPrefix;
while (pathPrefix.startsWith("/")) {
pathPrefix = pathPrefix.substring(1);
}
if (!pathPrefix.endsWith("/") && !pathPrefix.isEmpty()) {
pathPrefix = pathPrefix + "/";
}
final AutoCloseableList<ClasspathResource> filteredResources = new AutoCloseableList<>();
for (final ClasspathResource classpathResource : allResources) {
if (classpathResource.getPathRelativeToPackageRoot().startsWith(pathPrefix)) {
filteredResources.add(classpathResource);
}
}
return filteredResources;
}
}
/** Get a list of all resources found in whitelisted packages that have the requested leafname. */
public AutoCloseableList<ClasspathResource> getAllResourcesWithLeafName(final String leafName) {
if (allResources == null || allResources.isEmpty()) {
return new AutoCloseableList<>(1);
} else {
final AutoCloseableList<ClasspathResource> filteredResources = new AutoCloseableList<>();
for (final ClasspathResource classpathResource : allResources) {
final String relativePath = classpathResource.getPathRelativeToPackageRoot();
final int lastSlashIdx = relativePath.lastIndexOf('/');
if (relativePath.substring(lastSlashIdx + 1).equals(leafName)) {
filteredResources.add(classpathResource);
}
}
return filteredResources;
}
}
/**
* Get a list of all resources found in whitelisted packages that have the requested extension (e.g. "xml" to
* match all files ending in ".xml").
*/
public AutoCloseableList<ClasspathResource> getAllResourcesWithExtension(final String extension) {
if (allResources == null || allResources.isEmpty()) {
return new AutoCloseableList<>(1);
} else {
final AutoCloseableList<ClasspathResource> filteredResources = new AutoCloseableList<>();
for (final ClasspathResource classpathResource : allResources) {
final String relativePath = classpathResource.getPathRelativeToPackageRoot();
final int lastSlashIdx = relativePath.lastIndexOf('/');
final int lastDotIdx = relativePath.lastIndexOf('.');
if (lastDotIdx > lastSlashIdx) {
if (relativePath.substring(lastDotIdx + 1).equalsIgnoreCase(extension)) {
filteredResources.add(classpathResource);
}
}
}
return filteredResources;
}
}
/**
* Get a list of all resources found in whitelisted packages that have a path matching the requested pattern.
*/
public AutoCloseableList<ClasspathResource> getAllResourcesMatchingPattern(final Pattern pattern) {
if (allResources == null || allResources.isEmpty()) {
return new AutoCloseableList<>(1);
} else {
final AutoCloseableList<ClasspathResource> filteredResources = new AutoCloseableList<>();
for (final ClasspathResource classpathResource : allResources) {
final String relativePath = classpathResource.getPathRelativeToPackageRoot();
if (pattern.matcher(relativePath).matches()) {
filteredResources.add(classpathResource);
}
}
return filteredResources;
}
}
// -------------------------------------------------------------------------------------------------------------
/**
* Determine whether the classpath contents have been modified since the last scan. Checks the timestamps of
* files and jarfiles encountered during the previous scan to see if they have changed. Does not perform a full
* scan, so cannot detect the addition of directories that newly match whitelist criteria -- you need to perform
* a full scan to detect those changes.
*
* @return true if the classpath contents have been modified since the last scan.
*/
public boolean classpathContentsModifiedSinceScan() {
if (fileToLastModified == null) {
return true;
} else {
for (final Entry<File, Long> ent : fileToLastModified.entrySet()) {
if (ent.getKey().lastModified() != ent.getValue()) {
return true;
}
}
return false;
}
}
/**
* Find the maximum last-modified timestamp of any whitelisted file/directory/jarfile encountered during the
* scan. Checks the current timestamps, so this should increase between calls if something changes in
* whitelisted paths. Assumes both file and system timestamps were generated from clocks whose time was
* accurate. Ignores timestamps greater than the system time.
*
* <p>
* This method cannot in general tell if classpath has changed (or modules have been added or removed) if it is
* run twice during the same runtime session.
*
* @return the maximum last-modified time for whitelisted files/directories/jars encountered during the scan.
*/
public long classpathContentsLastModifiedTime() {
long maxLastModifiedTime = 0L;
if (fileToLastModified != null) {
final long currTime = System.currentTimeMillis();
for (final long timestamp : fileToLastModified.values()) {
if (timestamp > maxLastModifiedTime && timestamp < currTime) {
maxLastModifiedTime = timestamp;
}
}
}
return maxLastModifiedTime;
}
// -------------------------------------------------------------------------------------------------------------
// Classes
/**
* Get the ClassInfo object for the named class, or null if no class of the requested name was found in a
* whitelisted/non-blacklisted package during scanning.
*
* @return The ClassInfo object for the named class, or null if the class was not found.
*/
public ClassInfo getClassInfo(final String className) {
return classNameToClassInfo.get(className);
}
/**
* Get all classes, interfaces and annotations found during the scan.
*
* @return A list of all whitelisted classes found during the scan, or the empty list if none.
*/
public ClassInfoList getAllClasses() {
return ClassInfo.getAllClasses(classNameToClassInfo.values(), scanSpec, this);
}
/**
* Get all standard (non-interface/non-annotation) classes found during the scan.
*
* @return A list of all whitelisted standard classes found during the scan, or the empty list if none.
*/
public ClassInfoList getAllStandardClasses() {
return ClassInfo.getAllStandardClasses(classNameToClassInfo.values(), scanSpec, this);
}
/**
* Get all subclasses of the named superclass.
*
* @param superclassName
* The name of the superclass.
* @return A list of subclasses of the named superclass, or the empty list if none.
*/
public ClassInfoList getSubclassesOf(final String superclassName) {
final ClassInfo superclass = classNameToClassInfo.get(superclassName);
return superclass == null ? ClassInfoList.EMPTY_LIST : superclass.getSubclasses();
}
/**
* Get superclasses of the named subclass.
*
* @param subclassName
* The name of the subclass.
* @return A list of superclasses of the named subclass, or the empty list if none.
*/
public ClassInfoList getSuperclassesOf(final String subclassName) {
final ClassInfo subclass = classNameToClassInfo.get(subclassName);
return subclass == null ? ClassInfoList.EMPTY_LIST : subclass.getSuperclasses();
}
/**
* Get classes that have a method with an annotation of the named type.
*
* @param annotationName
* the name of the method annotation.
* @return The sorted list of classes with a method that has an annotation of the named type, or the empty list
* if none.
*/
public ClassInfoList getClassesWithMethodAnnotation(final String annotationName) {
if (!scanSpec.enableMethodInfo) {
throw new IllegalArgumentException(
"Please call FastClasspathScanner#enableMethodInfo() before calling scan() -- "
+ "method annotation indexing is disabled by default for efficiency");
}
final ClassInfo classInfo = classNameToClassInfo.get(annotationName);
return classInfo == null ? ClassInfoList.EMPTY_LIST : classInfo.getClassesWithMethodAnnotation();
}
/**
* Get classes that have a field with an annotation of the named type.
*
* @param annotationName
* the name of the field annotation.
* @return The sorted list of classes that have a field with an annotation of the named type, or the empty list
* if none.
*/
public ClassInfoList getClassesWithFieldAnnotation(final String annotationName) {
if (!scanSpec.enableFieldInfo) {
throw new IllegalArgumentException(
"Please call FastClasspathScanner#enableFieldAnnotationIndexing() before calling scan() -- "
+ "field annotation indexing is disabled by default for efficiency");
}
final ClassInfo classInfo = classNameToClassInfo.get(annotationName);
return classInfo == null ? ClassInfoList.EMPTY_LIST : classInfo.getClassesWithFieldAnnotation();
}
// -------------------------------------------------------------------------------------------------------------
// Interfaces
/**
* Get all interface classes found during the scan, not including annotations. See also
* {@link #getAllInterfaceOrAnnotationClasses()}.
*
* @return A list of all whitelisted interfaces found during the scan, or the empty list if none.
*/
public ClassInfoList getAllInterfaceClasses() {
return ClassInfo.getAllImplementedInterfaceClasses(classNameToClassInfo.values(), scanSpec, this);
}
/**
* Get all subinterfaces of the named interface.
*
* @param interfaceName
* The interface name.
* @return The sorted list of all subinterfaces of the named interface, or the empty list if none.
*/
public ClassInfoList getSubinterfacesOf(final String interfaceName) {
final ClassInfo classInfo = classNameToClassInfo.get(interfaceName);
return classInfo == null ? ClassInfoList.EMPTY_LIST : classInfo.getSubinterfaces();
}
/**
* Get all superinterfaces of the named interface.
*
* @param subInterfaceName
* The subinterface name.
* @return The sorted list of superinterfaces of the named subinterface, or the empty list if none.
*/
public ClassInfoList getSuperinterfacesOf(final String subInterfaceName) {
final ClassInfo classInfo = classNameToClassInfo.get(subInterfaceName);
return classInfo == null ? ClassInfoList.EMPTY_LIST : classInfo.getSuperinterfaces();
}
/**
* Get all classes that implement (or have superclasses that implement) the named interface (or one of its
* subinterfaces).
*
* @param interfaceName
* The interface name.
* @return The sorted list of all classes that implement the named interface, or the empty list if none.
*/
public ClassInfoList getClassesImplementing(final String interfaceName) {
final ClassInfo classInfo = classNameToClassInfo.get(interfaceName);
return classInfo == null ? ClassInfoList.EMPTY_LIST : classInfo.getClassesImplementing();
}
// -------------------------------------------------------------------------------------------------------------
// Annotations
/**
* Get all annotation classes found during the scan. See also {@link #getAllInterfaceOrAnnotationClasses()}.
*
* @return A list of all annotation classes found during the scan, or the empty list if none.
*/
public ClassInfoList getAllAnnotationClasses() {
return ClassInfo.getAllAnnotationClasses(classNameToClassInfo.values(), scanSpec, this);
}
/**
* Get all interface or annotation classes found during the scan. (Annotations are technically interfaces, and
* they can be implemented.)
*
* @return A list of all whitelisted interfaces found during the scan, or the empty list if none.
*/
public ClassInfoList getAllInterfaceOrAnnotationClasses() {
return ClassInfo.getAllInterfaceOrAnnotationClasses(classNameToClassInfo.values(), scanSpec, this);
}
/**
* Get non-annotation classes with the named class annotation or meta-annotation.
*
* @param annotationName
* The name of the class annotation or meta-annotation.
* @return The sorted list of all non-annotation classes that were found with the named class annotation during
* the scan, or the empty list if none.
*/
public ClassInfoList getClassesWithAnnotation(final String annotationName) {
final ClassInfo classInfo = classNameToClassInfo.get(annotationName);
return classInfo == null ? ClassInfoList.EMPTY_LIST : classInfo.getClassesWithAnnotation();
}
/**
* Get all annotations and meta-annotations on the named class.
*
* @param className
* The class name.
* @return The sorted list of annotations and meta-annotations on the named class, or the empty list if none.
*/
public ClassInfoList getAnnotationsOnClass(final String className) {
final ClassInfo classInfo = classNameToClassInfo.get(className);
return classInfo == null ? ClassInfoList.EMPTY_LIST : classInfo.getAnnotations();
}
// -------------------------------------------------------------------------------------------------------------
/**
* Generate a .dot file which can be fed into GraphViz for layout and visualization of the class graph. The
* sizeX and sizeY parameters are the image output size to use (in inches) when GraphViz is asked to render the
* .dot file.
*
* <p>
* Note that if you call this with showFields or showMethods set to false, but with method and/or field info
* enabled during scanning, then arrows will still be added between classes even if the field or method that
* created that dependency is not shown.
*
* @param sizeX
* The GraphViz layout width in inches.
* @param sizeY
* The GraphViz layout width in inches.
* @param showFields
* If true, show fields within class nodes in the graph. To show field info,
* {@link io.github.lukehutch.fastclasspathscanner.FastClasspathScanner#enableFieldInfo()} should be
* called before scanning. You may also want to call
* {@link io.github.lukehutch.fastclasspathscanner.FastClasspathScanner#ignoreFieldVisibility()}
* before scanning, to show non-public fields.
* @param showMethods
* If true, show methods within class nodes in the graph. To show method info,
* {@link io.github.lukehutch.fastclasspathscanner.FastClasspathScanner#enableMethodInfo()} should be
* called before scanning. You may also want to call
* {@link io.github.lukehutch.fastclasspathscanner.FastClasspathScanner#ignoreMethodVisibility()}
* before scanning, to show non-public methods.
* @return the GraphViz file contents.
*/
public String generateClassGraphDotFile(final float sizeX, final float sizeY, final boolean showFields,
final boolean showMethods) {
return GraphvizDotfileGenerator.generateClassGraphDotFile(this, sizeX, sizeY, showFields, showMethods,
scanSpec);
}
/**
* Generate a .dot file which can be fed into GraphViz for layout and visualization of the class graph. Methods
* and fields are shown, if method and field info have been enabled respectively, via
* {@link io.github.lukehutch.fastclasspathscanner.FastClasspathScanner#enableMethodInfo()} and
* {@link io.github.lukehutch.fastclasspathscanner.FastClasspathScanner#enableFieldInfo()}. Only public
* methods/fields are shown, unless
* {@link io.github.lukehutch.fastclasspathscanner.FastClasspathScanner#ignoreMethodVisibility()} and/or
* {@link io.github.lukehutch.fastclasspathscanner.FastClasspathScanner#ignoreFieldVisibility()} has been
* called. The sizeX and sizeY parameters are the image output size to use (in inches) when GraphViz is asked to
* render the .dot file.
*
* @param sizeX
* The GraphViz layout width in inches.
* @param sizeY
* The GraphViz layout width in inches.
* @return the GraphViz file contents.
*/
public String generateClassGraphDotFile(final float sizeX, final float sizeY) {
return generateClassGraphDotFile(sizeX, sizeY, /* showFields = */ true, /* showMethods = */ true);
}
/**
* Generate a .dot file which can be fed into GraphViz for layout and visualization of the class graph. Methods
* and fields are shown, if method and field info have been enabled respectively, via
* {@link io.github.lukehutch.fastclasspathscanner.FastClasspathScanner#enableMethodInfo()} and
* {@link io.github.lukehutch.fastclasspathscanner.FastClasspathScanner#enableFieldInfo()}. Only public
* methods/fields are shown, unless
* {@link io.github.lukehutch.fastclasspathscanner.FastClasspathScanner#ignoreMethodVisibility()} and/or
* {@link io.github.lukehutch.fastclasspathscanner.FastClasspathScanner#ignoreFieldVisibility()} has been
* called. The size defaults to 10.5 x 8 inches.
*
* @return the GraphViz file contents.
*/
public String generateClassGraphDotFile() {
return generateClassGraphDotFile(/* sizeX = */ 10.5f, /* sizeY = */ 8f, /* showFields = */ true,
/* showMethods = */ true);
}
// -------------------------------------------------------------------------------------------------------------
/**
* Call the classloader using Class.forName(className, initializeLoadedClasses, classLoader), for all known
* ClassLoaders, until one is able to load the class, or until there are no more ClassLoaders to try.
*
* @throw IllegalArgumentException if LinkageError (including ExceptionInInitializerError) is thrown, or if no
* ClassLoader is able to load the class.
* @return a reference to the loaded class, or null if the class could not be found.
*/
private Class<?> loadClass(final String className, final ClassLoader classLoader, final LogNode log)
throws IllegalArgumentException {
try {
return Class.forName(className, scanSpec.initializeLoadedClasses, classLoader);
} catch (final ClassNotFoundException e) {
return null;
} catch (final Throwable e) {
throw new IllegalArgumentException("Exception while loading class " + className, e);
}
}
/**
* Call the classloader using Class.forName(className, initializeLoadedClasses, classLoader), for all known
* ClassLoaders, until one is able to load the class, or until there are no more ClassLoaders to try.
*
* @throw IllegalArgumentException if LinkageError (including ExceptionInInitializerError) is thrown, or if
* returnNullIfClassNotFound is false and no ClassLoader is able to load the class.
* @return a reference to the loaded class, or null if returnNullIfClassNotFound was true and the class could
* not be loaded.
*/
Class<?> loadClass(final String className, final boolean returnNullIfClassNotFound, final LogNode log)
throws IllegalArgumentException {
if (scanSpec.overrideClasspath != null) {
// Unfortunately many surprises can result when overriding classpath (e.g. the wrong class definition
// could be loaded, if a class is defined more than once in the classpath). Even when overriding the
// ClassLoaders, a class may not be able to be cast to its superclass, if the class and its superclass
// are loaded into different classloaders, possibly due to accidental loading and caching in the
// non-custom classloader). Basically if you're overriding the classpath and/or defining custom
// classloaders, bad things will probably happen at some point!
if (log != null) {
log.log("When loading classes from a custom classpath, defined using .overrideClasspath(), "
+ "the correct classloader for the requested class " + className
+ " cannot reliably be determined. Will try loading the class using the default context "
+ "classLoader (which may or may not even be able to find the class). "
+ "Preferably always use .overrideClassLoaders() instead.");
}
}
if (className == null || className.isEmpty()) {
throw new IllegalArgumentException("Cannot load class -- class names cannot be null or empty");
}
// Try loading class via each classloader in turn
final ClassInfo classInfo = classNameToClassInfo.get(className);
final ClassLoader[] classLoadersForClass = classInfo != null ? classInfo.classLoaders : envClassLoaderOrder;
if (classLoadersForClass != null) {
for (final ClassLoader classLoader : classLoadersForClass) {
final Class<?> classRef = loadClass(className, classLoader, log);
if (classRef != null) {
return classRef;
}
}
}
// Try with null (bootstrap) ClassLoader
final Class<?> classRef = loadClass(className, /* classLoader = */ null, log);
if (classRef != null) {
return classRef;
}
// If this class came from a jarfile with a package root (e.g. a Spring-Boot jar, with packages rooted
// at BOOT-INF/classes), then the problem is probably that the jarfile was on the classpath, but the
// scanner is not running inside the jar itself, so the necessary ClassLoader for the jar is not
// available. Unzip the jar starting from the package root, and create a URLClassLoader to load classes
// from the unzipped jar. (This is only done once per jar and package root, using the singleton pattern.)
if (classInfo != null && nestedJarHandler != null) {
try {
ClassLoader customClassLoader = null;
if (classInfo.classpathElementFile.isDirectory()) {
// Should not happen, but we should handle this anyway -- create a URLClassLoader for the dir
customClassLoader = new URLClassLoader(
new URL[] { classInfo.classpathElementFile.toURI().toURL() });
} else {
// Get the outermost jar containing this jarfile, so that if a lib jar was extracted during
// scanning, we obtain the classloader from the outer jar. This is needed so that package roots
// and lib jars are loaded from the same classloader.
final File outermostJar = nestedJarHandler.getOutermostJar(classInfo.classpathElementFile);
// Get jarfile metadata for classpath element jarfile
final JarfileMetadataReader jarfileMetadataReader = //
nestedJarHandler.getJarfileMetadataReader(outermostJar, "", log);
// Create a custom ClassLoader for the jarfile. This might be time consuming, as it could
// trigger the extraction of all classes (for a classpath root other than ""), and/or any
// lib jars (e.g. in BOOT-INF/lib).
customClassLoader = jarfileMetadataReader.getCustomClassLoader(nestedJarHandler, log);
}
if (customClassLoader != null) {
final Class<?> classRefFromCustomClassLoader = loadClass(className, customClassLoader, log);
if (classRefFromCustomClassLoader != null) {
return classRefFromCustomClassLoader;
}
} else {
if (log != null) {
log.log("Unable to create custom classLoader to load class " + className);
}
}
} catch (final Throwable e) {
if (log != null) {
log.log("Exception while trying to load class " + className + " : " + e);
}
}
}
// Could not load class
if (!returnNullIfClassNotFound) {
throw new IllegalArgumentException("No classloader was able to load class " + className);
} else {
if (log != null) {
log.log("No classloader was able to load class " + className);
}
return null;
}
}
// -------------------------------------------------------------------------------------------------------------
/**
* Produce Class reference given a class name. If ignoreExceptions is false, and the class cannot be loaded (due
* to classloading error, or due to an exception being thrown in the class initialization block), an
* IllegalArgumentException is thrown; otherwise, the class will simply be skipped if an exception is thrown.
*
* <p>
* Enable verbose scanning to see details of any exceptions thrown during classloading, even if ignoreExceptions
* is false.
*
* @param className
* the class to load.
* @param ignoreExceptions
* If true, null is returned if there was an exception during classloading, otherwise
* IllegalArgumentException is thrown if a class could not be loaded.
* @throws IllegalArgumentException
* if ignoreExceptions is false, IllegalArgumentException is thrown if there were problems loading
* or initializing the class. (Note that class initialization on load is disabled by default, you
* can enable it with {@code FastClasspathScanner#initializeLoadedClasses(true)} .) Otherwise
* exceptions are suppressed, and null is returned if any of these problems occurs.
* @return a reference to the loaded class, or null if the class could not be loaded and ignoreExceptions is
* true.
*/
Class<?> classNameToClassRef(final String className, final boolean ignoreExceptions)
throws IllegalArgumentException {
try {
return loadClass(className, /* returnNullIfClassNotFound = */ ignoreExceptions, log);
} catch (final Throwable e) {
if (ignoreExceptions) {
return null;
} else {
throw new IllegalArgumentException("Could not load class " + className, e);
}
} finally {
// Manually flush log, since this method is called after scanning is complete
if (log != null) {
log.flush();
}
}
}
/**
* Produce Class reference given a class name. If ignoreExceptions is false, and the class cannot be loaded (due
* to classloading error, or due to an exception being thrown in the class initialization block), an
* IllegalArgumentException is thrown; otherwise, the class will simply be skipped if an exception is thrown.
*
* <p>
* Enable verbose scanning to see details of any exceptions thrown during classloading, even if ignoreExceptions
* is false.
*
* @param className
* the class to load.
* @param classType
* The class type to cast the result to.
* @param ignoreExceptions
* If true, null is returned if there was an exception during classloading, otherwise
* IllegalArgumentException is thrown if a class could not be loaded.
* @throws IllegalArgumentException
* if ignoreExceptions is false, IllegalArgumentException is thrown if there were problems loading
* the class, initializing the class, or casting it to the requested type. (Note that class
* initialization on load is disabled by default, you can enable it with
* {@code FastClasspathScanner#initializeLoadedClasses(true)} .) Otherwise exceptions are
* suppressed, and null is returned if any of these problems occurs.
* @return a reference to the loaded class, or null if the class could not be loaded and ignoreExceptions is
* true.
*/
<T> Class<T> classNameToClassRef(final String className, final Class<T> classType,
final boolean ignoreExceptions) throws IllegalArgumentException {
try {
if (classType == null) {
if (ignoreExceptions) {
return null;
} else {
throw new IllegalArgumentException("classType parameter cannot be null");
}
}
final Class<?> loadedClass = loadClass(className, /* returnNullIfClassNotFound = */ ignoreExceptions,
log);
if (loadedClass != null && !classType.isAssignableFrom(loadedClass)) {
if (ignoreExceptions) {
return null;
} else {
throw new IllegalArgumentException(
"Loaded class " + loadedClass.getName() + " cannot be cast to " + classType.getName());
}
}
@SuppressWarnings("unchecked")
final Class<T> castClass = (Class<T>) loadedClass;
return castClass;
} catch (final Throwable e) {
if (ignoreExceptions) {
return null;
} else {
throw new IllegalArgumentException("Could not load class " + className, e);
}
} finally {
// Manually flush log, since this method is called after scanning is complete
if (log != null) {
log.flush();
}
}
}
// -------------------------------------------------------------------------------------------------------------
/** The current serialization format. */
private static final String CURRENT_SERIALIZATION_FORMAT = "4";
/** A class to hold a serialized ScanResult along with the ScanSpec that was used to scan. */
private static class SerializationFormat {
public String serializationFormat;
public ScanSpec scanSpec;
public List<ClassInfo> allClassInfo;
@SuppressWarnings("unused")
public SerializationFormat() {
}
public SerializationFormat(final String serializationFormat, final ScanSpec scanSpec,
final Map<String, ClassInfo> classNameToClassInfo) {
this.serializationFormat = serializationFormat;
this.scanSpec = scanSpec;
this.allClassInfo = new ArrayList<>(classNameToClassInfo.values());
}
}
/** Deserialize a ScanResult from previously-saved JSON. */
public static ScanResult fromJSON(final String json) {
final Matcher matcher = Pattern.compile("\\{[\\n\\r ]*\"serializationFormat\"[ ]?:[ ]?\"([^\"]+)\"")
.matcher(json);
if (!matcher.find()) {
throw new IllegalArgumentException("JSON is not in correct format");
}
if (!CURRENT_SERIALIZATION_FORMAT.equals(matcher.group(1))) {
throw new IllegalArgumentException(
"JSON was serialized in a different format from the format used by the current version of "
+ "FastClasspathScanner -- please serialize and deserialize your ScanResult using "
+ "the same version of FastClasspathScanner");
}
final SerializationFormat deserialized = JSONDeserializer.deserializeObject(SerializationFormat.class,
json);
if (!deserialized.serializationFormat.equals(CURRENT_SERIALIZATION_FORMAT)) {
// Probably the deserialization failed before now anyway, if fields have changed, etc.
throw new IllegalArgumentException("JSON was serialized by newer version of FastClasspathScanner");
}
final ClassLoader[] envClassLoaderOrder = new ClassLoaderAndModuleFinder(deserialized.scanSpec,
/* log = */ null).getClassLoaders();
final Map<String, ClassInfo> classNameToClassInfo = new HashMap<>();
for (final ClassInfo ci : deserialized.allClassInfo) {
classNameToClassInfo.put(ci.getClassName(), ci);
}
final ScanResult scanResult = new ScanResult(deserialized.scanSpec,
Collections.<ClasspathElement> emptyList(), envClassLoaderOrder, classNameToClassInfo,
/* fileToLastModified = */ null, /* nestedJarHandler = */ null, /* interruptionChecker = */ null,
/* log = */ null);
return scanResult;
}
/**
* Serialize a ScanResult to JSON.
*
* @param indentWidth
* If greater than 0, JSON will be formatted (indented), otherwise it will be minified (un-indented).
*/
public String toJSON(final int indentWidth) {
return JSONSerializer.serializeObject(
new SerializationFormat(CURRENT_SERIALIZATION_FORMAT, scanSpec, classNameToClassInfo), indentWidth,
false);
}
/** Serialize a ScanResult to minified (un-indented) JSON. */
public String toJSON() {
return toJSON(0);
}
// -------------------------------------------------------------------------------------------------------------
/**
* Free any temporary files created by extracting jars from within jars. By default, temporary files are removed
* at the end of a scan, after MatchProcessors have completed, so this typically does not need to be called. The
* case where it might need to be called is if the list of classpath elements has been fetched, and the
* classpath contained jars within jars. Without calling this method, the temporary files created by extracting
* the inner jars will not be removed until the temporary file system cleans them up (typically at reboot).
*
* @param log
* The log.
*/
public void freeTempFiles(final LogNode log) {
if (allResources != null) {
for (final ClasspathResource classpathResource : allResources) {
classpathResource.close();
}
}
if (nestedJarHandler != null) {
nestedJarHandler.close(log);
}
}
@Override
protected void finalize() throws Throwable {
// NestedJarHandler also adds a runtime shutdown hook, since finalizers are not reliable
freeTempFiles(null);
}
}
| Change method names | src/main/java/io/github/lukehutch/fastclasspathscanner/scanner/ScanResult.java | Change method names |
|
Java | mit | 72d0e222c2b6bd128bcaa5bdedda9e56f3c03ea2 | 0 | Wreulicke/spring-sandbox,Wreulicke/spring-sandbox,Wreulicke/spring-sandbox,Wreulicke/spring-sandbox | /**
* MIT License
*
* Copyright (c) 2017 Wreulicke
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.wreulicke.simple;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final UserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic()
.realmName("test")
.and()
.csrf()
.disable()
.authorizeRequests()
.anyRequest()
.authenticated();
}
@Bean
public PasswordEncoder bcrpt() {
return new BCryptPasswordEncoder();
}
}
| simple-jpa/src/main/java/com/github/wreulicke/simple/SecurityConfiguration.java | /**
* MIT License
*
* Copyright (c) 2017 Wreulicke
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.wreulicke.simple;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@RequiredArgsConstructor
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final UserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic()
.realmName("test")
.and()
.csrf()
.disable()
.authorizeRequests()
.anyRequest()
.authenticated();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(bcrpt());
}
@Bean
public PasswordEncoder bcrpt() {
return new BCryptPasswordEncoder();
}
}
| remove unnecessary configuration
| simple-jpa/src/main/java/com/github/wreulicke/simple/SecurityConfiguration.java | remove unnecessary configuration |
|
Java | epl-1.0 | 129804b6d1a1fa6821051eb0a3adf567368d81f0 | 0 | floralvikings/jenjin | package com.jenjinstudios.client.net;
import com.jenjinstudios.core.MessageIO;
import com.jenjinstudios.core.io.MessageInputStream;
import com.jenjinstudios.core.io.MessageOutputStream;
import org.testng.Assert;
import org.testng.annotations.Test;
import static org.mockito.Mockito.mock;
/**
* Test the AuthClient class.
* @author Caleb Brinkman
*/
public class AuthClientTest
{
@Test
public void testIsLoggedIn() {
MessageInputStream mis = mock(MessageInputStream.class);
MessageOutputStream mos = mock(MessageOutputStream.class);
MessageIO messageIO = new MessageIO(mis, mos);
ClientUser clientUser = mock(ClientUser.class);
boolean random = ((Math.random() * 10) % 2) == 0;
AuthClient authClient = new AuthClient(messageIO, clientUser);
authClient.getLoginTracker().setLoggedIn(random);
Assert.assertEquals(authClient.getLoginTracker().isLoggedIn(), random);
}
@Test
public void testLoggedInTime() {
MessageInputStream mis = mock(MessageInputStream.class);
MessageOutputStream mos = mock(MessageOutputStream.class);
MessageIO messageIO = new MessageIO(mis, mos);
ClientUser clientUser = mock(ClientUser.class);
long random = (long) (Math.random() * 1000);
AuthClient authClient = new AuthClient(messageIO, clientUser);
authClient.getLoginTracker().setLoggedInTime(random);
Assert.assertEquals(authClient.getLoginTracker().getLoggedInTime(), random);
}
@Test
public void testGetUser() {
MessageInputStream mis = mock(MessageInputStream.class);
MessageOutputStream mos = mock(MessageOutputStream.class);
MessageIO messageIO = new MessageIO(mis, mos);
ClientUser clientUser = mock(ClientUser.class);
AuthClient authClient = new AuthClient(messageIO, clientUser);
Assert.assertEquals(authClient.getUser(), clientUser);
}
}
| jenjin-core-client/src/test/java/com/jenjinstudios/client/net/AuthClientTest.java | package com.jenjinstudios.client.net;
import com.jenjinstudios.core.MessageIO;
import com.jenjinstudios.core.io.MessageInputStream;
import com.jenjinstudios.core.io.MessageOutputStream;
import org.testng.Assert;
import org.testng.annotations.Test;
import static org.mockito.Mockito.mock;
/**
* @author Caleb Brinkman
*/
public class AuthClientTest
{
@Test
public void testIsLoggedIn() {
MessageInputStream mis = mock(MessageInputStream.class);
MessageOutputStream mos = mock(MessageOutputStream.class);
MessageIO messageIO = new MessageIO(mis, mos);
ClientUser clientUser = mock(ClientUser.class);
boolean random = ((Math.random() * 10) % 2) == 0;
AuthClient authClient = new AuthClient(messageIO, clientUser);
authClient.getLoginTracker().setLoggedIn(random);
Assert.assertEquals(authClient.getLoginTracker().isLoggedIn(), random);
}
@Test
public void testLoggedInTime() {
MessageInputStream mis = mock(MessageInputStream.class);
MessageOutputStream mos = mock(MessageOutputStream.class);
MessageIO messageIO = new MessageIO(mis, mos);
ClientUser clientUser = mock(ClientUser.class);
long random = (long) (Math.random() * 1000);
AuthClient authClient = new AuthClient(messageIO, clientUser);
authClient.getLoginTracker().setLoggedInTime(random);
Assert.assertEquals(authClient.getLoginTracker().getLoggedInTime(), random);
}
@Test
public void testGetUser() {
MessageInputStream mis = mock(MessageInputStream.class);
MessageOutputStream mos = mock(MessageOutputStream.class);
MessageIO messageIO = new MessageIO(mis, mos);
ClientUser clientUser = mock(ClientUser.class);
AuthClient authClient = new AuthClient(messageIO, clientUser);
Assert.assertEquals(authClient.getUser(), clientUser);
}
}
| Added class JavaDoc
| jenjin-core-client/src/test/java/com/jenjinstudios/client/net/AuthClientTest.java | Added class JavaDoc |
|
Java | epl-1.0 | 34f81c58883c4b05dd681883b2e48c5f31e598ff | 0 | rrimmana/birt-1,Charling-Huang/birt,Charling-Huang/birt,Charling-Huang/birt,Charling-Huang/birt,Charling-Huang/birt,rrimmana/birt-1,sguan-actuate/birt,rrimmana/birt-1,sguan-actuate/birt,sguan-actuate/birt,sguan-actuate/birt,rrimmana/birt-1,rrimmana/birt-1,sguan-actuate/birt | /***********************************************************************
* Copyright (c) 2004,2005,2006,2007 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
***********************************************************************/
package org.eclipse.birt.chart.extension.render;
import java.awt.Color;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;
import org.eclipse.birt.chart.computation.BoundingBox;
import org.eclipse.birt.chart.computation.DataPointHints;
import org.eclipse.birt.chart.computation.GObjectFactory;
import org.eclipse.birt.chart.computation.IChartComputation;
import org.eclipse.birt.chart.computation.IConstants;
import org.eclipse.birt.chart.computation.IGObjectFactory;
import org.eclipse.birt.chart.device.IDeviceRenderer;
import org.eclipse.birt.chart.device.IDisplayServer;
import org.eclipse.birt.chart.device.IStructureDefinitionListener;
import org.eclipse.birt.chart.engine.extension.i18n.Messages;
import org.eclipse.birt.chart.event.ArcRenderEvent;
import org.eclipse.birt.chart.event.AreaRenderEvent;
import org.eclipse.birt.chart.event.EventObjectCache;
import org.eclipse.birt.chart.event.InteractionEvent;
import org.eclipse.birt.chart.event.LineRenderEvent;
import org.eclipse.birt.chart.event.PolygonRenderEvent;
import org.eclipse.birt.chart.event.PrimitiveRenderEvent;
import org.eclipse.birt.chart.event.StructureSource;
import org.eclipse.birt.chart.event.TextRenderEvent;
import org.eclipse.birt.chart.event.WrappedStructureSource;
import org.eclipse.birt.chart.exception.ChartException;
import org.eclipse.birt.chart.factory.RunTimeContext.StateKey;
import org.eclipse.birt.chart.log.ILogger;
import org.eclipse.birt.chart.log.Logger;
import org.eclipse.birt.chart.model.ChartWithoutAxes;
import org.eclipse.birt.chart.model.attribute.Bounds;
import org.eclipse.birt.chart.model.attribute.ChartDimension;
import org.eclipse.birt.chart.model.attribute.ColorDefinition;
import org.eclipse.birt.chart.model.attribute.Fill;
import org.eclipse.birt.chart.model.attribute.Gradient;
import org.eclipse.birt.chart.model.attribute.Insets;
import org.eclipse.birt.chart.model.attribute.LeaderLineStyle;
import org.eclipse.birt.chart.model.attribute.LegendItemType;
import org.eclipse.birt.chart.model.attribute.LineAttributes;
import org.eclipse.birt.chart.model.attribute.LineStyle;
import org.eclipse.birt.chart.model.attribute.Location;
import org.eclipse.birt.chart.model.attribute.Palette;
import org.eclipse.birt.chart.model.attribute.Position;
import org.eclipse.birt.chart.model.attribute.Size;
import org.eclipse.birt.chart.model.attribute.impl.SizeImpl;
import org.eclipse.birt.chart.model.component.Label;
import org.eclipse.birt.chart.model.data.Trigger;
import org.eclipse.birt.chart.model.type.PieSeries;
import org.eclipse.birt.chart.plugin.ChartEngineExtensionPlugin;
import org.eclipse.birt.chart.script.AbstractScriptHandler;
import org.eclipse.birt.chart.script.ScriptHandler;
import org.eclipse.birt.chart.util.ChartUtil;
import org.eclipse.birt.chart.util.FillUtil;
import org.eclipse.emf.common.util.EList;
/**
* PieRenderer
*/
public final class PieRenderer
{
static final int UNKNOWN = 0;
protected static final IGObjectFactory goFactory = GObjectFactory.instance( );
private static final int LOWER = 1;
private static final int UPPER = 2;
private static final double LEADER_TICK_MIN_SIZE = 10; // POINTS
private static final int LESS = -1;
private static final int MORE = 1;
private static final int EQUAL = 0;
private final Position lpDataPoint;
private final Position lpSeriesTitle;
private transient double dLeaderLength;
private final LeaderLineStyle lls;
/**
* Series thickness
*/
private transient final double dThickness;
private transient double dExplosion = 0;
private transient String sExplosionExpression = null;
private final Pie pie;
private final PieSeries ps;
private final List<PieSlice> pieSliceList = new ArrayList<PieSlice>( );
/**
* Holds list of deferred planes (flat and curved) to be sorted before
* rendering
*/
/**
* The list stores back curved planes whose angle are between 0 to 180 and
* will be drown before drawing flat planes and front curved planes.
*/
private final List backCurvedPlanes = new ArrayList( );
/**
* The list stores front curved planes whose angle are between 180 to 360
* and will be drown after drawing back planes and front planes.
*/
private final List frontCurvedPlanes = new ArrayList( );
/** The list stores all flat planes of pie slices. */
private final List flatPlanes = new ArrayList( );
private final Palette pa;
private final Label laSeriesTitle;
private final LineAttributes liaLL;
private final LineAttributes liaEdges;
private transient IDisplayServer xs = null;
private transient IDeviceRenderer idr = null;
private transient Bounds boTitleContainer = null;
private transient Bounds boSeriesNoTitle = null;
private transient Insets insCA = null;
private transient Bounds boSetDuringComputation = null;
private final boolean bPaletteByCategory;
private transient boolean bBoundsAdjustedForInsets = false;
private transient boolean bMinSliceDefined = false;
private transient double dMinSlice = 0;
private transient double dAbsoluteMinSlice = 0;
private transient boolean bPercentageMinSlice = false;
private transient boolean bMinSliceApplied = false;
private transient int orginalSliceCount = 0;
private transient double ratio = 0;
private transient double rotation = 0;
private final IChartComputation cComp;
/**
* The constant variable is used to adjust start angle of plane for getting
* correct rendering order of planes.
* <p>
*
* Note: Since its value is very little, it will not affect computing the
* coordinates of pie slice.
*/
private final double MIN_DOUBLE = 0.0000000001d;
private static ILogger logger = Logger.getLogger( "org.eclipse.birt.chart.engine.extension/render" ); //$NON-NLS-1$
/**
*
* @param cwoa
* @param pie
* @param dpha
* @param da
* @param pa
*/
PieRenderer( ChartWithoutAxes cwoa, Pie pie, DataPointHints[] dpha,
double[] da, Palette pa ) throws ChartException
{
this.pa = pa;
this.pie = pie;
this.cComp = pie.getRunTimeContext( )
.getState( StateKey.CHART_COMPUTATION_KEY );
ps = (PieSeries) pie.getSeries( );
sExplosionExpression = ps.getExplosionExpression( );
dExplosion = ps.getExplosion( ) * pie.getDeviceScale( );
dThickness = ( ( cwoa.getDimension( ) == ChartDimension.TWO_DIMENSIONAL_LITERAL ) ? 0
: cwoa.getSeriesThickness( ) )
* pie.getDeviceScale( );
ratio = ps.isSetRatio( ) ? ps.getRatio( ) : 1;
rotation = ps.isSetRotation( ) ? ps.getRotation( ) : 0;
liaLL = ps.getLeaderLineAttributes( );
if ( ps.getLeaderLineAttributes( ).isVisible( ) )
{
dLeaderLength = ps.getLeaderLineLength( ) * pie.getDeviceScale( );
}
else
{
dLeaderLength = 0;
}
liaEdges = goFactory.createLineAttributes( goFactory.BLACK( ),
LineStyle.SOLID_LITERAL,
1 );
bPaletteByCategory = ( cwoa.getLegend( ).getItemType( ) == LegendItemType.CATEGORIES_LITERAL );
lpDataPoint = ps.getLabelPosition( );
lpSeriesTitle = ps.getTitlePosition( );
laSeriesTitle = goFactory.copyOf( ps.getTitle( ) );
laSeriesTitle.getCaption( )
.setValue( pie.getRunTimeContext( )
.externalizedMessage( String.valueOf( ps.getSeriesIdentifier( ) ) ) ); // TBD:
laSeriesTitle.getCaption( )
.getFont( )
.setAlignment( pie.switchTextAlignment( laSeriesTitle.getCaption( )
.getFont( )
.getAlignment( ) ) );
// call script BEFORE_DRAW_SERIES_TITLE
final AbstractScriptHandler sh = pie.getRunTimeContext( ).getScriptHandler( );
ScriptHandler.callFunction( sh,
ScriptHandler.BEFORE_DRAW_SERIES_TITLE,
ps,
laSeriesTitle,
pie.getRunTimeContext( ).getScriptContext( ) );
pie.getRunTimeContext( )
.notifyStructureChange( IStructureDefinitionListener.BEFORE_DRAW_SERIES_TITLE,
laSeriesTitle );
// APPLY
// FORMAT
// SPECIFIER
lls = ps.getLeaderLineStyle( );
bMinSliceDefined = cwoa.isSetMinSlice( );
dMinSlice = cwoa.getMinSlice( );
bPercentageMinSlice = cwoa.isMinSlicePercent( );
double dTotal = 0;
orginalSliceCount = da.length;
for ( int i = 0; i < da.length; i++ )
{
if ( da[i] < 0 )
{
dTotal -= da[i]; // use negative values as absolute
}
else if ( !Double.isNaN( da[i] ) )
{
dTotal += da[i];
}
}
if ( bMinSliceDefined )
{
if ( bPercentageMinSlice )
{
dAbsoluteMinSlice = dMinSlice * dTotal / 100d;
}
else
{
dAbsoluteMinSlice = dMinSlice;
}
double residualPos = 0;
double residualNeg = 0;
DataPointHints dphPos = null;
DataPointHints dphNeg = null;
for ( int i = 0; i < da.length; i++ )
{
// filter null values.
if ( Double.isNaN( da[i] ) )
{
continue;
}
if ( Math.abs( da[i] ) >= Math.abs( dAbsoluteMinSlice ) )
{
pieSliceList.add( new PieSlice( da[i], dpha[i], i ) );
}
else
{
if ( da[i] >= 0 )
{
residualPos += da[i];
if ( dphPos == null )
{
dphPos = dpha[i].getVirtualCopy( );
}
else
{
dphPos.accumulate( dpha[i].getBaseValue( ),
dpha[i].getOrthogonalValue( ),
dpha[i].getSeriesValue( ),
dpha[i].getPercentileOrthogonalValue( ) );
}
}
else
{
residualNeg += da[i];
if ( dphNeg == null )
{
dphNeg = dpha[i].getVirtualCopy( );
}
else
{
dphNeg.accumulate( dpha[i].getBaseValue( ),
dpha[i].getOrthogonalValue( ),
dpha[i].getSeriesValue( ),
dpha[i].getPercentileOrthogonalValue( ) );
}
}
}
}
String extSliceLabel = pie.getRunTimeContext( )
.externalizedMessage( cwoa.getMinSliceLabel( ) );
if ( dphPos != null )
{
dphPos.setBaseValue( extSliceLabel );
dphPos.setIndex( orginalSliceCount );
// neg and pos "other" slice share the same palette color
pieSliceList.add( new PieSlice( residualPos,
dphPos,
orginalSliceCount ) );
bMinSliceApplied = true;
}
if ( dphNeg != null )
{
dphNeg.setBaseValue( extSliceLabel );
dphNeg.setIndex( orginalSliceCount );
pieSliceList.add( new PieSlice( residualNeg,
dphNeg,
orginalSliceCount ) );
bMinSliceApplied = true;
}
}
else
{
for ( int i = 0; i < da.length; i++ )
{
// filter null values.
if ( Double.isNaN( da[i] ) )
{
continue;
}
pieSliceList.add( new PieSlice( da[i], dpha[i], i ) );
}
}
double startAngle = rotation;
double originalStartAngle = rotation;
if ( dTotal == 0 )
{
dTotal = 1;
}
if ( ps.isClockwise( ) )
{
Collections.reverse( pieSliceList );
}
PieSlice slice = null;
double totalAngle = 0d;
for ( Iterator iter = pieSliceList.iterator( ); iter.hasNext( ); )
{
slice = (PieSlice) iter.next( );
double length = ( Math.abs( slice.getPrimitiveValue( ) ) / dTotal ) * 360d;
double percentage = ( slice.getPrimitiveValue( ) / dTotal ) * 100d;
slice.setStartAngle( startAngle );
slice.setOriginalStartAngle( originalStartAngle );
slice.setSliceLength( length );
slice.setPercentage( percentage );
startAngle += length + MIN_DOUBLE;
originalStartAngle += length;
startAngle = wrapAngle( startAngle );
originalStartAngle = wrapAngle( originalStartAngle );
totalAngle += length;
}
// complement the last slice with residual angle
// TODO What is this for?
if ( totalAngle > 0 && 360 - totalAngle > 0.001 ) // handle precision
// loss during
// computations
{
slice.setSliceLength( 360 - slice.getStartAngle( ) );
}
initExploded( );
}
private double wrapAngle( double angle )
{
return angle > 360 ? angle - 360 : angle;
}
/**
*
* @param idr
* @throws ChartException
*/
private final void renderDataPoints( IDeviceRenderer idr )
throws ChartException
{
final AbstractScriptHandler sh = pie.getRunTimeContext( ).getScriptHandler( );
int iTextRenderType = TextRenderEvent.RENDER_TEXT_IN_BLOCK;
if ( lpDataPoint.getValue( ) == Position.OUTSIDE )
{
// RENDER SHADOWS (IF ANY) FIRST
for ( PieSlice slice : pieSliceList )
{
if ( slice.getLabel( ).getShadowColor( ) != null )
{
slice.renderLabel( idr,
TextRenderEvent.RENDER_SHADOW_AT_LOCATION );
}
}
iTextRenderType = TextRenderEvent.RENDER_TEXT_AT_LOCATION;
}
// RENDER ACTUAL TEXT CAPTIONS ON DATA POINTS
for ( PieSlice slice : pieSliceList )
{
if ( slice.getLabel( ).isVisible( ) )
{
slice.renderLabel( idr, iTextRenderType );
}
ScriptHandler.callFunction( sh,
ScriptHandler.AFTER_DRAW_DATA_POINT_LABEL,
slice.getDataPointHints( ),
slice.getLabel( ),
pie.getRunTimeContext( ).getScriptContext( ) );
pie.getRunTimeContext( )
.notifyStructureChange( IStructureDefinitionListener.AFTER_DRAW_DATA_POINT_LABEL,
slice.getLabel( ) );
}
}
/**
*
* @param bo
*/
/**
*
* @param bo
*/
private final void computeLabelBounds( Bounds bo, boolean isOutside )
throws ChartException
{
// compute additional bottom tick size due to series thickness.
for ( PieSlice slice : pieSliceList )
{
slice.setBounds( bo );
if ( isOutside )
{
slice.computeLabelBoundOutside( lls, dLeaderLength, null );
}
else
{
slice.computeLabelBoundInside( );
}
}
}
/**
*
* LabelOverlapResover
*/
private static class LabelOverlapResover
{
// min distance (x) from label to pie
private static final double DMINDIST = 5;
// min space between labels
private static final double HSPACE = 3;
private static final double VSPACE = 3;
private final LeaderLineStyle lls;
private double dLeadLineLen = 0; // length of the lead line
private final List<PieSlice> src_sliceList;
private final double dLeftEdge, dRightEdge, dTopEdge, dBottomEdge;
private int idRightFirst, idLeftFirst, idRightLast, idLeftLast;
public LabelOverlapResover( LeaderLineStyle lls, List<PieSlice> sliceList, Bounds bo, double dLeaderLength )
{
this.dLeftEdge = bo.getLeft( );
this.dRightEdge = bo.getLeft( ) + bo.getWidth( );
this.dTopEdge = bo.getTop( );
this.dBottomEdge = bo.getTop( ) + bo.getHeight( );
this.src_sliceList = sliceList;
this.lls = lls;
if (lls == LeaderLineStyle.FIXED_LENGTH_LITERAL)
{
this.dLeadLineLen = dLeaderLength;
}
}
private void seekForIndexes( )
{
int len = src_sliceList.size( );
if ( len == 0 )
{
return;
}
else if ( len == 1 )
{
if (isLeftSideSlice( src_sliceList.get( 0 ) ))
{
this.idLeftFirst = 0;
this.idLeftLast = 0;
this.idRightLast = -1;
}
else
{
this.idRightFirst = 0;
this.idLeftLast = -1;
}
// this.idLeftLast
// this.idLeftLast
return;
}
boolean bCurrentIsLeft = isLeftSideSlice( src_sliceList.get( 0 ) );
boolean bLastFound = false;
boolean bFirstFound = false;
for ( int i = 1; i < len; i++ )
{
if ( bCurrentIsLeft )
{
if ( !isLeftSideSlice( src_sliceList.get( i ) ) )
{
this.idLeftLast = i - 1;
this.idRightLast = i;
bCurrentIsLeft = false;
bLastFound = true;
}
}
else
{
if ( isLeftSideSlice( src_sliceList.get( i ) ) )
{
this.idRightFirst = i - 1;
this.idLeftFirst = i;
bCurrentIsLeft = true;
bFirstFound = true;
}
}
}
if (!bFirstFound)
{
this.idLeftFirst = 0;
this.idRightFirst = len - 1;
}
if (!bLastFound)
{
idRightLast = 0;
idLeftLast = len - 1;
}
}
private void processLeftSideLoop( LabelGroupList lList, int id0, int id1 )
{
for (int i = id0; i <= id1; i++ )
{
PieSlice slice = src_sliceList.get( i );
if (!lList.isFull)
{
SliceLabel sLabel = new SliceLabel( slice, false );
lList.addSliceLabel( sLabel, false );
}
else
{
break;
}
}
}
private void processLeftSide( int len )
{
LabelGroupList lList = new LabelGroupList(false);
if ( idLeftLast < 0 )
{
return;
}
if (idLeftLast >= idLeftFirst)
{
processLeftSideLoop( lList, idLeftFirst, idLeftLast );
}
else
{
processLeftSideLoop( lList, idLeftFirst, len - 1 );
processLeftSideLoop( lList, 0, idLeftLast );
}
//
LabelGroup lg = lList.head.lgNext;
for (; !lg.isTail( ); lg = lg.lgNext)
{
lg.updateSlices();
}
}
private void processRightSideLoop( LabelGroupList rList, int id0, int id1 )
{
for (int i = id0; i >= id1; i-- )
{
PieSlice slice = src_sliceList.get( i );
if (!rList.isFull)
{
SliceLabel sLabel = new SliceLabel( slice, true );
rList.addSliceLabel( sLabel, true );
}
else
{
break;
}
}
}
private void processRightSide( int len )
{
LabelGroupList rList = new LabelGroupList(true);
if ( idRightLast < 0 )
{
return;
}
if (idRightLast <= idRightFirst)
{
processRightSideLoop( rList, idRightFirst, idRightLast );
}
else
{
processRightSideLoop( rList, idRightFirst, 0 );
processRightSideLoop( rList, len - 1, idRightLast );
}
//
LabelGroup lg = rList.head.lgNext;
for (; !lg.isTail( ); lg = lg.lgNext)
{
lg.updateSlices();
}
}
public void resolve( )
{
int len = src_sliceList.size( );
if ( len > 0 )
{
// search the start and end index
seekForIndexes( );
// process the slices on the left side
processLeftSide( len );
// process the slices on the right side
processRightSide( len );
}
}
private static boolean isLeftSideSlice( PieSlice slice )
{
double angle = slice.getOriginalMidAngle( ) % 360;
return ( angle >= 90 && angle < 270 );
}
/**
* a vertical list of label groups, from top to bottom
* LabelGroupList
*/
private class LabelGroupList
{
private boolean isFull = false;
private LabelGroup head;
private LabelGroup tail;
LabelGroupList( boolean bRight )
{
if (bRight)
{
head = new RightLabelGroup( 1 );
tail = new RightLabelGroup( 2 );
}
else
{
head = new LeftLabelGroup( 1 );
tail = new LeftLabelGroup( 2 );
}
head.lgNext = tail;
tail.lgLast = head;
}
private void append_simply( LabelGroup lg )
{
tail.lgLast.lgNext = lg;
lg.lgLast = tail.lgLast;
lg.lgNext = tail;
tail.lgLast = lg;
}
private boolean limitLgTop( LabelGroup lg )
{
double minTop = lg.computeMinTop( );
double maxTop = lg.computeMaxTop( );
if ( minTop > maxTop )
{
return false;
}
else
{
lg.top = Math.max( lg.top, lg.computeMinTop( ) );
lg.top = Math.min( lg.top, lg.computeMaxTop( ) );
return true;
}
}
/**
* add a slice label to the bottom of the list
* @param sLabel
* @param bRight
* @return
*/
public boolean addSliceLabel( SliceLabel sLabel, boolean bRight )
{
// create a label group with the label
LabelGroup lg = createLabelGroup(sLabel, bRight);
if ( tail.lgLast == head )
{
// the first
append_simply( lg );
if ( !limitLgTop( lg ) )
{
return false;
}
lg.xStart = lg.getXStartClosestToPie( );
return true;
}
else
{
if ( !limitLgTop( lg ) )
{
return false;
}
limitLgTop( lg );
lg.xStart = lg.getXStartClosestToPie( );
double last_bottom = tail.lgLast.top
+ tail.lgLast.height + VSPACE;
double dy = last_bottom - lg.top;
if ( dy > 0 )
{
double lg_top_old = lg.top;
lg.top = last_bottom;
append_simply( lg );
double dMaxTop = lg.computeMaxTop( );
if (lg.top <= dMaxTop)
{
return true;
}
if (tail.lgLast.pushUp( lg.top - dMaxTop ) )
{
return true;
}
else
{
tail.lgLast.delete( );
lg.top = lg_top_old;
this.isFull = true;
return false;
}
}
else
{
// no overlapping
append_simply( lg );
return true;
}
}
}
}
private LabelGroup createLabelGroup( SliceLabel sLabel, boolean bRight )
{
LabelGroup lg = bRight ? new RightLabelGroup(sLabel) : new LeftLabelGroup(sLabel);
return lg;
}
/*
* a row of slice label on the right side of the pie
*/
private class RightLabelGroup extends LabelGroup
{
public RightLabelGroup( SliceLabel sLabel )
{
super(sLabel);
}
public RightLabelGroup( int type )
{
super(type);
}
@Override
protected double getXStartLimit( )
{
return dRightEdge - width - dLeadLineLen - DMINDIST;
}
protected double getPrefferredXStart( )
{
double x1 = getXStartLimit( );
double x0 = getXStartClosestToPie( );
double dx = x1 - x0;
double len = 0;
if (dx > 0)
{
len = Math.abs( dx );
len = Math.min( len, dLeadLineLen + DMINDIST );
}
return x0 + len * Math.signum( dx );
}
@Override
public boolean addSliceLabel( SliceLabel sLabel )
{
double width_new = ( label_list.size( ) == 0 ) ? 0 : width
+ HSPACE;
width_new += sLabel.width;
double height_new = Math.max( height, sLabel.height );
label_list.add( sLabel );
double xStart_new = this.getXStartClosestToPie( );
if ( width_new > dRightEdge - xStart_new || height_new > dBottomEdge - top )
{
label_list.remove( label_list.size( ) - 1 );
return false;
}
this.width = width_new;
this.xStart = xStart_new;
this.height = height_new;
return true;
}
@Override
public double getXStartClosestToPie( )
{
int len = label_list.size( );
double lspace = this.height / ( len + 1 );
double y = top + lspace;
double xStart = label_list.get( 0 ).getXStartClosestToPie( y );
for (int i=1; i<len; i++ )
{
xStart = Math.max( xStart, label_list.get( i ).getXStartClosestToPie( y ) );
}
return xStart;
}
@Override
public void updateSlices()
{
this.top = Math.min( this.top, dBottomEdge - this.height );
int len = label_list.size();
double lspace = this.height / ( len + 1 );
double dYLeadLine = this.top + lspace;
xStart = getPrefferredXStart( );
if (lls == LeaderLineStyle.FIXED_LENGTH_LITERAL)
{
double dLeft = this.xStart;
for ( int i = 0; i < len; i++ )
{
SliceLabel sLabel = label_list.get(i);
// update the label bounding
sLabel.slice.labelBounding.setTop(top);
sLabel.slice.labelBounding.setLeft(dLeft);
// update the lead line
sLabel.slice.loEnd.setX( dLeft );
sLabel.slice.loEnd.setY( dYLeadLine );
sLabel.slice.loStart.setX( this.xStart - dLeadLineLen );
sLabel.slice.loStart.setY( dYLeadLine );
dLeft += sLabel.width + HSPACE;
dYLeadLine += lspace;
}
}
else
{
double dRight = dRightEdge;
for ( int i = 0; i < len; i++ )
{
SliceLabel sLabel = label_list.get(i);
// update the label bounding
sLabel.slice.labelBounding.setTop(top);
sLabel.slice.labelBounding.setLeft(dRight - sLabel.width);
// update the lead line
sLabel.slice.loEnd.setX( dRight - sLabel.width );
sLabel.slice.loEnd.setY( dYLeadLine );
sLabel.slice.loStart.setX( this.xStart - dLeadLineLen );
sLabel.slice.loStart.setY( dYLeadLine );
dRight -= sLabel.width + HSPACE;
dYLeadLine += lspace;
}
}
}
}
/*
* a row of slice label on the left side of the pie
*/
private class LeftLabelGroup extends LabelGroup
{
public LeftLabelGroup( SliceLabel sLabel )
{
super(sLabel);
}
public LeftLabelGroup( int type )
{
super(type);
}
@Override
protected double getXStartLimit( )
{
return dLeftEdge + width + dLeadLineLen + DMINDIST;
}
protected double getPrefferredXStart( )
{
double x1 = getXStartLimit( );
double x0 = getXStartClosestToPie( );
double dx = x1 - x0;
double len = 0;
if ( dx < 0 )
{
len = Math.abs( dx );
len = Math.min( len, dLeadLineLen + DMINDIST );
}
return x0 + len * Math.signum( dx );
}
@Override
public boolean addSliceLabel( SliceLabel sLabel )
{
double height_new = Math.max( this.height, sLabel.height );
double width_new = ( label_list.size( ) == 0 ) ? 0 : width
+ HSPACE;
width_new += sLabel.width;
label_list.add( sLabel );
double xStart_new = this.getXStartClosestToPie( );
if ( width_new > xStart_new - dLeftEdge || sLabel.height > dBottomEdge - this.top )
{
label_list.remove( label_list.size( ) - 1 );
return false;
}
this.width = width_new;
this.xStart = xStart_new;
this.height = height_new;
return true;
}
@Override
public double getXStartClosestToPie( )
{
int len = label_list.size( );
double lspace = this.height / ( len + 1 );
double y = top + lspace;
double xStart = label_list.get( 0 ).getXStartClosestToPie( y );
for (int i=1; i<len; i++ )
{
xStart = Math.min( xStart, label_list.get( i ).getXStartClosestToPie( y ) );
}
return xStart;
}
@Override
public void updateSlices()
{
this.top = Math.min( this.top, dBottomEdge - this.height );
int len = label_list.size();
double lspace = this.height / ( len + 1 );
double dYLeadLine = this.top + lspace;
xStart = getPrefferredXStart( );
if (lls == LeaderLineStyle.FIXED_LENGTH_LITERAL)
{
double dRight = xStart;
for ( int i = 0; i < len; i++ )
{
SliceLabel sLabel = label_list.get( i );
// update the label bounding
sLabel.slice.labelBounding.setTop( top );
sLabel.slice.labelBounding.setLeft( dRight
- sLabel.width );
// update the lead line
sLabel.slice.loEnd.setX( dRight );
sLabel.slice.loEnd.setY( dYLeadLine );
sLabel.slice.loStart.setX( this.xStart + dLeadLineLen );
sLabel.slice.loStart.setY( dYLeadLine );
dRight -= sLabel.width + HSPACE;
dYLeadLine += lspace;
}
}
else
{
//STRETCH_TO_SIDE
double dLeft = dLeftEdge;
for (int i = 0; i<len; i++)
{
SliceLabel sLabel = label_list.get( i );
// update the label bounding
sLabel.slice.labelBounding.setTop( top );
sLabel.slice.labelBounding.setLeft( dLeft );
// update the lead line
sLabel.slice.loEnd.setX( dLeft + sLabel.width );
sLabel.slice.loEnd.setY( dYLeadLine );
sLabel.slice.loStart.setX( this.xStart );
sLabel.slice.loStart.setY( dYLeadLine );
dLeft += sLabel.width + HSPACE;
dYLeadLine += lspace;
}
}
}
}
/*
* a row of slice label
*/
private abstract class LabelGroup
{
private int type = 0; // 0 normal, 1 head, 2 tail
private LabelGroup lgLast = null;
private LabelGroup lgNext = null;
protected List<SliceLabel> label_list = new ArrayList<SliceLabel>();
protected double xStart, width = 0, top, height = 0;
private boolean isFull = false;
public LabelGroup( SliceLabel sLabel )
{
label_list.add( sLabel );
this.top = sLabel.top_init;
this.width = sLabel.width;
this.xStart = sLabel.xStart;
this.height = sLabel.height;
}
public LabelGroup( int type )
{
this.type = type;
}
public boolean isHead()
{
return ( type == 1 );
}
public boolean isTail()
{
return ( type == 2 );
}
private void recomputeHeight()
{
int len = label_list.size( );
height = label_list.get( 0 ).height;
for (int i=1; i<len; i++)
{
height = Math.max( height, label_list.get( i ).height );
}
}
private void removeLastLabel()
{
int len = label_list.size( );
if ( len < 2 )
{
return;
}
SliceLabel sLabel = label_list.get( len - 1 );
label_list.remove( len - 1 );
width -= sLabel.width + HSPACE;
recomputeHeight( );
xStart = getXStartClosestToPie( );
}
public void setTop(double top)
{
this.top = top;
}
public abstract double getXStartClosestToPie( );
public double computeMinTop( )
{
double dMinTop = dTopEdge;
int len = label_list.size();
if ( len > 0 )
{
SliceLabel sLabel = label_list.get( label_list.size( ) - 1 );
if ( !sLabel.bUp )
{
double dx = getXStartLimit( ) - sLabel.slice.xDock;
double dy = 0;
if ( dx != 0 )
{
dy = dx / sLabel.dRampRate;
}
double lspace = height / ( len + 1 );
dMinTop = sLabel.slice.yDock + dy - height + lspace;
}
}
return dMinTop;
}
protected abstract double getXStartLimit( );
public double computeMaxTop( )
{
double dMaxTop = dBottomEdge - height;
int len = label_list.size();
if ( len > 0 )
{
SliceLabel sLabel = label_list.get( 0 );
if ( sLabel.bUp )
{
double dx = getXStartLimit( ) - sLabel.slice.xDock;
double dy = 0;
if ( dx != 0 )
{
dy = dx / sLabel.dRampRate;
}
double lspace = height / ( len + 1 );
dMaxTop = sLabel.slice.yDock + dy - lspace;
}
}
return dMaxTop;
}
private double getBottomLast( )
{
double dBottomLast = dTopEdge;
if (lgLast!=null)
{
dBottomLast = lgLast.top + lgLast.height + VSPACE;
}
return dBottomLast;
}
public boolean pushUp( double dy )
{
if ( this.isFull )
{
return false;
}
double top_new = top - dy;
double dTopMin = this.computeMinTop( );
double bottom_last = getBottomLast( );
if( lgLast == null || top_new >= bottom_last )
{
// head of the list || no overlapping
top = Math.max( top_new, dTopMin );
return ( top_new >= dTopMin );
}
else
{
// top_new < bottom_last
if ( lgLast.pushUp( bottom_last - top_new ) )
{
// push succeeded
top = Math.max( top_new, dTopMin );
return ( top_new >= dTopMin );
}
else
{
// push failed
bottom_last = getBottomLast( ); // lgLast may have changed
if ( top - lgLast.top >= dy)
{
// if possible, merge myself to the last one
if ( lgLast.merge( this ) )
{
return true;
}
else
{
top = Math.max( bottom_last, dTopMin );
return false;
}
}
else
{
if (!lgLast.merge( this ))
{
top = Math.max( bottom_last, dTopMin );
}
return false;
}
}
}
}
public boolean merge( LabelGroup lg )
{
if ( lg.label_list.size( ) > 1 )
{
// only merge lg contains one label
return false;
}
else if ( lg.label_list.size( ) > 0 )
{
SliceLabel sLabel = lg.label_list.get( 0 );
if (!addSliceLabel( sLabel ))
{
this.isFull = true;
return false;
}
else
{
if (this.top < this.computeMinTop( ) || this.top > this.computeMaxTop( ))
{
removeLastLabel( );
this.isFull = true;
return false;
}
}
}
// success
lg.delete( );
return true;
}
// delete myself from the list
public void delete( )
{
if (this.type==0)
{
this.lgLast.lgNext = this.lgNext;
this.lgNext.lgLast = this.lgLast;
}
// if ( this.lgLast != null )
// {
// this.lgLast.lgNext = this.lgNext;
// }
//
// if (this.lgNext!=null)
// {
// this.lgNext.lgLast = this.lgLast;
// }
}
public abstract boolean addSliceLabel( SliceLabel sLabel );
public abstract void updateSlices();
@Override
public String toString( )
{
StringBuffer sBuf = new StringBuffer();
Iterator<SliceLabel> it = label_list.iterator( );
while (it.hasNext( ) )
{
SliceLabel sLabel = it.next( );
sBuf.append( sLabel.slice.categoryIndex );
if (it.hasNext( ))
{
sBuf.append( ", " ); //$NON-NLS-1$
}
}
StringBuilder sb = new StringBuilder( "{ " ); //$NON-NLS-1$
sb.append( sBuf.toString( ) );
sb.append( " }" ); //$NON-NLS-1$
return sb.toString( );
}
}
/*
* wrapping class of slice label
*/
private class SliceLabel
{
private boolean bRight = true;
private boolean bUp = true;
private final PieSlice slice;
private double xStart;
private final double width;
private final double height;
private final double top_init;
private double dRampRate;
public SliceLabel( PieSlice slice, boolean bRight )
{
this.slice = slice;
this.bRight = bRight;
this.width = slice.labelBounding.getWidth( );
this.height = slice.labelBounding.getHeight( );
this.top_init = slice.labelBounding.getTop( );
computeRampRate();
if ( !bRight )
{
xStart = slice.xDock - DMINDIST - dLeadLineLen;
}
else
{
xStart = slice.xDock + DMINDIST + dLeadLineLen;
}
}
public double getXStartClosestToPie( double y )
{
double dy = y - slice.yDock;
double dx = dy * dRampRate;
if ( ( bUp && dy <= 0 ) || ( !bUp && dy >= 0 ) )
{
dx = 0;
}
if ( !bRight )
{
return slice.xDock - DMINDIST - dLeadLineLen + dx;
}
else
{
return slice.xDock + DMINDIST + dLeadLineLen + dx;
}
}
private void computeRampRate( )
{
double angle = slice.getdMidAngle( ) % 360;
dRampRate = Math.tan( Math.toRadians( angle ) );
if (angle>180 && angle < 360)
{
bUp = false;
}
}
}
}
private void resolveOverlap( )
{
new LabelOverlapResover( lls, pieSliceList, boSeriesNoTitle, dLeaderLength ).resolve();
}
/**
*
* @param bo
* @param boAdjusted
* @param ins
* @return
* @throws IllegalArgumentException
*/
private final Insets adjust( Bounds bo, Bounds boAdjusted, Insets ins )
throws ChartException
{
computeLabelBounds( boAdjusted, true );
ins.set( 0, 0, 0, 0 );
double dDelta = 0;
for ( Iterator<PieSlice> iter = pieSliceList.iterator( ); iter.hasNext( ); )
{
PieSlice slice = iter.next( );
BoundingBox bb = slice.getLabelBounding( );
if ( bb.getLeft( ) < bo.getLeft( ) )
{
dDelta = bo.getLeft( ) - bb.getLeft( );
if ( ins.getLeft( ) < dDelta )
{
ins.setLeft( dDelta );
}
}
if ( bb.getTop( ) < bo.getTop( ) )
{
dDelta = bo.getTop( ) - bb.getTop( );
if ( ins.getTop( ) < dDelta )
{
ins.setTop( dDelta );
}
}
if ( bb.getLeft( ) + bb.getWidth( ) > bo.getLeft( ) + bo.getWidth( ) )
{
dDelta = bb.getLeft( )
+ bb.getWidth( )
- bo.getLeft( )
- bo.getWidth( );
if ( ins.getRight( ) < dDelta )
{
ins.setRight( dDelta );
}
}
if ( bb.getTop( ) + bb.getHeight( ) > bo.getTop( ) + bo.getHeight( ) )
{
dDelta = bb.getTop( )
+ bb.getHeight( )
- bo.getTop( )
- bo.getHeight( );
if ( ins.getBottom( ) < dDelta )
{
ins.setBottom( dDelta );
}
}
}
return ins;
}
/**
*
* @param bo
* @throws ChartException
* @throws IllegalArgumentException
*/
final void computeInsets( Bounds bo ) throws ChartException
{
boSetDuringComputation = goFactory.copyOf( bo );
xs = pie.getXServer( );
// ALLOCATE SPACE FOR THE SERIES TITLE
boTitleContainer = null;
if ( laSeriesTitle.isVisible( ) )
{
if ( lpSeriesTitle == null )
{
throw new ChartException( ChartEngineExtensionPlugin.ID,
ChartException.UNDEFINED_VALUE,
"exception.unspecified.visible.series.title", //$NON-NLS-1$
Messages.getResourceBundle( pie.getRunTimeContext( )
.getULocale( ) ) );
}
final BoundingBox bb = cComp.computeBox( xs,
IConstants.BELOW,
laSeriesTitle,
0,
0 );
boTitleContainer = goFactory.createBounds( 0, 0, 0, 0 );
switch ( lpSeriesTitle.getValue( ) )
{
case Position.BELOW :
bo.setHeight( bo.getHeight( ) - bb.getHeight( ) );
boTitleContainer.set( bo.getLeft( ), bo.getTop( )
+ bo.getHeight( ), bo.getWidth( ), bb.getHeight( ) );
break;
case Position.ABOVE :
boTitleContainer.set( bo.getLeft( ),
bo.getTop( ),
bo.getWidth( ),
bb.getHeight( ) );
bo.setTop( bo.getTop( ) + bb.getHeight( ) );
bo.setHeight( bo.getHeight( ) - bb.getHeight( ) );
break;
case Position.LEFT :
bo.setWidth( bo.getWidth( ) - bb.getWidth( ) );
boTitleContainer.set( bo.getLeft( ),
bo.getTop( ),
bb.getWidth( ),
bo.getHeight( ) );
bo.setLeft( bo.getLeft( ) + bb.getWidth( ) );
break;
case Position.RIGHT :
bo.setWidth( bo.getWidth( ) - bb.getWidth( ) );
boTitleContainer.set( bo.getLeft( ) + bo.getWidth( ),
bo.getTop( ),
bb.getWidth( ),
bo.getHeight( ) );
break;
default :
throw new IllegalArgumentException( Messages.getString( "exception.illegal.pie.series.title.position", //$NON-NLS-1$
new Object[]{
lpSeriesTitle
},
pie.getRunTimeContext( ).getULocale( ) ) );
}
}
boSeriesNoTitle = goFactory.copyOf( bo );
ChartWithoutAxes cwa = (ChartWithoutAxes) pie.getModel( );
if ( cwa.isSetCoverage( ) )
{
double rate = cwa.getCoverage( );
double ww = 0.5 * ( 1d - rate ) * bo.getWidth( );
double hh = 0.5 * ( 1d - rate ) * bo.getHeight( );
insCA = goFactory.createInsets( hh, ww, hh, ww );
}
else
{
if ( lpDataPoint == Position.OUTSIDE_LITERAL )
{
if ( ps.getLabel( ).isVisible( ) ) // FILTERED FOR PERFORMANCE
// GAIN
{
// ADJUST THE BOUNDS TO ACCOMODATE THE DATA POINT LABELS +
// LEADER LINES RENDERED OUTSIDE
// Bounds boBeforeAdjusted = BoundsImpl.copyInstance( bo );
Bounds boAdjusted = goFactory.copyOf( bo );
Insets insTrim = goFactory.createInsets( 0, 0, 0, 0 );
do
{
adjust( bo, boAdjusted, insTrim );
boAdjusted.adjust( insTrim );
} while ( !insTrim.areLessThan( 0.5 )
&& boAdjusted.getWidth( ) > 0
&& boAdjusted.getHeight( ) > 0 );
bo = boAdjusted;
}
}
else if ( lpDataPoint == Position.INSIDE_LITERAL )
{
if ( ps.getLabel( ).isVisible( ) ) // FILTERED FOR PERFORMANCE
// GAIN
{
computeLabelBounds( bo, false );
}
}
else
{
throw new IllegalArgumentException( MessageFormat.format( Messages.getResourceBundle( pie.getRunTimeContext( )
.getULocale( ) )
.getString( "exception.invalid.datapoint.position.pie" ), //$NON-NLS-1$
new Object[]{
lpDataPoint
} )
);
}
insCA = goFactory.createInsets( bo.getTop( )
- boSetDuringComputation.getTop( ),
bo.getLeft( ) - boSetDuringComputation.getLeft( ),
boSetDuringComputation.getTop( )
+ boSetDuringComputation.getHeight( )
- ( bo.getTop( ) + bo.getHeight( ) ),
boSetDuringComputation.getLeft( )
+ boSetDuringComputation.getWidth( )
- ( bo.getLeft( ) + bo.getWidth( ) ) );
}
bBoundsAdjustedForInsets = false;
}
/**
*
* @return
*/
final Insets getFittingInsets( )
{
return insCA;
}
/**
*
* @param insCA
*/
final void setFittingInsets( Insets insCA ) throws ChartException
{
this.insCA = insCA;
if ( !bBoundsAdjustedForInsets ) // CHECK IF PREVIOUSLY ADJUSTED
{
bBoundsAdjustedForInsets = true;
boSetDuringComputation.adjust( insCA );
}
if ( lpDataPoint == Position.OUTSIDE_LITERAL )
{
if ( ps.getLabel( ).isVisible( ) ) // FILTERED FOR PERFORMANCE GAIN
{
computeLabelBounds( boSetDuringComputation, true );
}
}
else if ( lpDataPoint == Position.INSIDE_LITERAL )
{
if ( ps.getLabel( ).isVisible( ) ) // FILTERED FOR PERFORMANCE GAIN
{
computeLabelBounds( boSetDuringComputation, false );
}
}
}
/**
*
* @param idr
* @param bo
* @throws ChartException
*/
public final void render( IDeviceRenderer idr, Bounds bo )
throws ChartException
{
bo.adjust( insCA );
xs = idr.getDisplayServer( );
this.idr = idr;
final AbstractScriptHandler sh = pie.getRunTimeContext( ).getScriptHandler( );
double w = bo.getWidth( ) / 2d - dExplosion;
double h = bo.getHeight( ) / 2d - dExplosion - dThickness / 2d;
double xc = bo.getLeft( ) + bo.getWidth( ) / 2d;
double yc = bo.getTop( ) + bo.getHeight( ) / 2d;
if ( ratio > 0 && w > 0 )
{
if ( h / w > ratio )
{
h = w * ratio;
}
else if ( h / w < ratio )
{
w = h / ratio;
}
}
// detect invalid rendering size.
if ( w > 0 && h > 0 )
{
// RENDER THE INSIDE OF THE PIE SLICES AS DEFERRED PLANES (FLAT AND
// CURVED)
if ( dThickness > 0 )
{
for ( Iterator<PieSlice> iter = pieSliceList.iterator( ); iter.hasNext( ); )
{
PieSlice slice = iter.next( );
Fill fPaletteEntry = null;
if ( bPaletteByCategory )
{
fPaletteEntry = getPaletteColor( slice.getCategoryIndex( ),
slice.getDataPointHints( ) );
}
else
{
fPaletteEntry = getPaletteColor( pie.getSeriesDefinition( )
.getRunTimeSeries( )
.indexOf( ps ),
slice.getDataPointHints( ) );
}
ScriptHandler.callFunction( sh,
ScriptHandler.BEFORE_DRAW_ELEMENT,
slice.getDataPointHints( ),
fPaletteEntry );
ScriptHandler.callFunction( sh,
ScriptHandler.BEFORE_DRAW_DATA_POINT,
slice.getDataPointHints( ),
fPaletteEntry,
pie.getRunTimeContext( ).getScriptContext( ) );
pie.getRunTimeContext( )
.notifyStructureChange( IStructureDefinitionListener.BEFORE_DRAW_ELEMENT,
slice.getDataPointHints( ) );
pie.getRunTimeContext( )
.notifyStructureChange( IStructureDefinitionListener.BEFORE_DRAW_DATA_POINT,
slice.getDataPointHints( ) );
slice.render( goFactory.createLocation( xc, yc ),
goFactory.createLocation( 0, dThickness ),
SizeImpl.create( w, h ),
fPaletteEntry,
LOWER );
ScriptHandler.callFunction( sh,
ScriptHandler.AFTER_DRAW_ELEMENT,
slice.getDataPointHints( ),
fPaletteEntry );
ScriptHandler.callFunction( sh,
ScriptHandler.AFTER_DRAW_DATA_POINT,
slice.getDataPointHints( ),
fPaletteEntry,
pie.getRunTimeContext( ).getScriptContext( ) );
pie.getRunTimeContext( )
.notifyStructureChange( IStructureDefinitionListener.AFTER_DRAW_ELEMENT,
slice.getDataPointHints( ) );
pie.getRunTimeContext( )
.notifyStructureChange( IStructureDefinitionListener.AFTER_DRAW_DATA_POINT,
slice.getDataPointHints( ) );
}
// SORT AND ACTUALLY RENDER THE PLANES PREVIOUSLY WRITTEN AS
// DEFERRED
sortAndRenderPlanes( );
}
// RENDER THE UPPER SECTORS ON THE PIE SLICES (DON'T CARE ABOUT
// THE ORDER)
for ( Iterator<PieSlice> iter = pieSliceList.iterator( ); iter.hasNext( ); )
{
PieSlice slice = iter.next( );
Fill fPaletteEntry = null;
if ( bPaletteByCategory )
{
fPaletteEntry = getPaletteColor( slice.getCategoryIndex( ),
slice.getDataPointHints( ) );
}
else
{
fPaletteEntry = getPaletteColor( pie.getSeriesDefinition( )
.getRunTimeSeries( )
.indexOf( ps ), slice.getDataPointHints( ) );
}
ScriptHandler.callFunction( sh,
ScriptHandler.BEFORE_DRAW_DATA_POINT,
slice.getDataPointHints( ),
fPaletteEntry,
pie.getRunTimeContext( ).getScriptContext( ) );
pie.getRunTimeContext( )
.notifyStructureChange( IStructureDefinitionListener.BEFORE_DRAW_DATA_POINT,
slice.getDataPointHints( ) );
slice.render( goFactory.createLocation( xc, yc ),
goFactory.createLocation( 0, dThickness ),
SizeImpl.create( w, h ),
fPaletteEntry,
UPPER );
ScriptHandler.callFunction( sh,
ScriptHandler.AFTER_DRAW_DATA_POINT,
slice.getDataPointHints( ),
fPaletteEntry,
pie.getRunTimeContext( ).getScriptContext( ) );
pie.getRunTimeContext( )
.notifyStructureChange( IStructureDefinitionListener.AFTER_DRAW_DATA_POINT,
slice.getDataPointHints( ) );
}
}
// RENDER THE SERIES TITLE NOW
// ScriptHandler.callFunction( sh,
// ScriptHandler.BEFORE_DRAW_SERIES_TITLE,
// ps,
// laSeriesTitle,
// pie.getRunTimeContext( ).getScriptContext( ) );
// pie.getRunTimeContext( )
// .notifyStructureChange( IStructureDefinitionListener.BEFORE_DRAW_SERIES_TITLE,
// laSeriesTitle );
// laDataPoint = LabelImpl.copyInstance( ps.getLabel( ) );
if ( laSeriesTitle.isVisible( ) )
{
final TextRenderEvent tre = ( (EventObjectCache) idr ).getEventObject( WrappedStructureSource.createSeriesTitle( ps,
laSeriesTitle ),
TextRenderEvent.class );
tre.setLabel( laSeriesTitle );
tre.setBlockBounds( boTitleContainer );
tre.setBlockAlignment( null );
tre.setAction( TextRenderEvent.RENDER_TEXT_IN_BLOCK );
idr.drawText( tre );
}
ScriptHandler.callFunction( sh,
ScriptHandler.AFTER_DRAW_SERIES_TITLE,
ps,
laSeriesTitle,
pie.getRunTimeContext( ).getScriptContext( ) );
pie.getRunTimeContext( )
.notifyStructureChange( IStructureDefinitionListener.AFTER_DRAW_SERIES_TITLE,
laSeriesTitle );
// LASTLY, RENDER THE DATA POINTS
if ( ps.getLabel( ).isVisible( ) )
{ // IF NOT VISIBLE, DON'T DO ANYTHING
try
{
if ( ps.getLabel( ).getCaption( ).getFont( ).getRotation( ) == 0 )
{
if ( lpDataPoint == Position.OUTSIDE_LITERAL )
{
resolveOverlap( );
}
}
renderDataPoints( idr );
}
catch ( ChartException rex )
{
logger.log( rex );
// Throw the exception to engine at runtime and engine will
// display the exception to user.
throw rex;
}
}
}
/**
* Add curved planes to a list for deferring to draw them.
*
* @param planesList
* the list is used to receive the planes.
* @param angle
* angle of pie slice, normally it should be the start angle of
* pie slice.
* @param areBentOrTwistedCurve
* @param dX1
* @param dX2
*/
private final void deferCurvedPlane( List list, double angle,
AreaRenderEvent areBentOrTwistedCurve, double dX1, double dX2 )
{
double newAngle = convertAngleForRenderingOrder( angle );
list.add( new CurvedPlane( newAngle, areBentOrTwistedCurve ) );
}
/**
* Defer to draw curved outline.
*
* @param planesList
* the list is used to receive the planes.
* @param angle
* angle of pie slice, normally it should be the start angle of
* pie slice.
* @param areBentOrTwistedCurve
* outline group.
*/
private final void deferCurvedOutline( List list, double angle,
AreaRenderEvent areBentOrTwistedCurve )
{
double newAngle = convertAngleForRenderingOrder( angle );
list.add( new CurvedPlane( newAngle, areBentOrTwistedCurve ) );
}
/**
* Add flat planes to a list for deferring to draw them.
*
* @param planesList
* the list is used to receive the planes.
* @param angle
* angle of pie slice, normally it should be the start angle of
* pie slice.
* @param daXPoints
* @param daYPoints
* @param cd
*/
private final void deferFlatPlane( List planesList, double angle,
double[] daXPoints, double[] daYPoints, Fill cd, DataPointHints dph )
{
double newAngle = convertAngleForRenderingOrder( angle );
planesList.add( new FlatPlane( newAngle, daXPoints, daYPoints, cd, dph ) );
}
/**
* Convert angle of pie slice for getting correct rendering order before
* rendering each pie slice.
*
* @param angle
* angle of pie slice, normally it should be the start angle of
* pie slice.
* @return adjusted angle.
*/
private double convertAngleForRenderingOrder( double angle )
{
double newAngle = angle;
newAngle = wrapAngle( newAngle );
if ( newAngle < 180 )
{
newAngle = Math.abs( newAngle - 90 );
}
else
{
newAngle = ( 90 - Math.abs( newAngle - 270 ) ) + 180;
}
return newAngle;
}
/**
* Sort all planes and draw them.
*
* @throws ChartException
*/
private final void sortAndRenderPlanes( ) throws ChartException
{
// Draw each planes, first draw the back curved planes of view, second
// draw the flat planes, last to draw the front curved planes of view.
renderPlanes( backCurvedPlanes );
backCurvedPlanes.clear( );
renderPlanes( flatPlanes );
flatPlanes.clear( );
renderPlanes( frontCurvedPlanes );
frontCurvedPlanes.clear( );
}
/**
* Render planes.
*
* @param planesList
* the list contains plane objects.
* @throws ChartException
*/
private void renderPlanes( List planesList ) throws ChartException
{
Object[] planes = planesList.toArray( );
Arrays.sort( planes, new Comparator( ) {
/**
*
* @param arg0
* @param arg1
* @return
*/
public int compare( Object arg0, Object arg1 )
{
double angleA = 0d;
double angleB = 0d;
if ( arg0 instanceof FlatPlane )
{
angleA = ( (FlatPlane) arg0 ).getAngle( );
}
else if ( arg0 instanceof CurvedPlane )
{
angleA = ( (CurvedPlane) arg0 ).getAngle( );
}
if ( arg1 instanceof FlatPlane )
{
angleB = ( (FlatPlane) arg1 ).getAngle( );
}
else if ( arg0 instanceof CurvedPlane )
{
angleB = ( (CurvedPlane) arg1 ).getAngle( );
}
return Double.compare( angleA, angleB );
}
} );
for ( int i = 0; i < planes.length; i++ )
{
IDrawable id = (IDrawable) planes[i];
id.draw( );
}
}
private final ColorDefinition getSliceOutline( Fill f )
{
if ( ps.getSliceOutline( ) == null )
{
if ( f instanceof ColorDefinition )
{
return goFactory.darker( (ColorDefinition) f );
}
else
{
return goFactory.TRANSPARENT( );
}
}
return goFactory.copyOf( ps.getSliceOutline( ) );
}
private void initExploded( )
{
if ( sExplosionExpression == null )
{
return;
}
for ( PieSlice slice : pieSliceList )
{
try
{
pie.getRunTimeContext( )
.getScriptHandler( )
.registerVariable( ScriptHandler.BASE_VALUE,
slice.getDataPointHints( ).getBaseValue( ) );
pie.getRunTimeContext( )
.getScriptHandler( )
.registerVariable( ScriptHandler.ORTHOGONAL_VALUE,
slice.getDataPointHints( ).getOrthogonalValue( ) );
pie.getRunTimeContext( )
.getScriptHandler( )
.registerVariable( ScriptHandler.SERIES_VALUE,
slice.getDataPointHints( ).getSeriesValue( ) );
Object obj = pie.getRunTimeContext( )
.getScriptHandler( )
.evaluate( sExplosionExpression );
if ( obj instanceof Boolean )
{
slice.setExploded( ( (Boolean) obj ).booleanValue( ) );
}
pie.getRunTimeContext( )
.getScriptHandler( )
.unregisterVariable( ScriptHandler.BASE_VALUE );
pie.getRunTimeContext( )
.getScriptHandler( )
.unregisterVariable( ScriptHandler.ORTHOGONAL_VALUE );
pie.getRunTimeContext( )
.getScriptHandler( )
.unregisterVariable( ScriptHandler.SERIES_VALUE );
}
catch ( ChartException e )
{
logger.log( e );
}
}
}
// HANDLE ELEVATION COMPUTATION FOR SOLID
// COLORS,
// GRADIENTS AND IMAGES
protected Gradient getDepthGradient( Fill cd )
{
if ( cd instanceof Gradient )
{
return goFactory.createGradient( goFactory.darker( ( (Gradient) cd ).getStartColor( ) ),
goFactory.darker( ( (Gradient) cd ).getEndColor( ) ),
( (Gradient) cd ).getDirection( ),
( (Gradient) cd ).isCyclic( ) );
}
else
return goFactory.createGradient( ( cd instanceof ColorDefinition ) ? goFactory.darker( (ColorDefinition) cd )
: goFactory.GREY( ),
goFactory.BLACK( ),
0,
true );
}
/**
* @param cd
* @param startAngle
* @param endAngle
* @return
*/
protected Gradient getDepthGradient( Fill cd, double startAngle,
double endAngle )
{
if ( cd instanceof Gradient )
{
return goFactory.createGradient( goFactory.darker( ( (Gradient) cd ).getStartColor( ) ),
goFactory.darker( ( (Gradient) cd ).getEndColor( ) ),
( (Gradient) cd ).getDirection( ),
( (Gradient) cd ).isCyclic( ) );
}
else
{
ColorDefinition standCD = ( cd instanceof ColorDefinition ) ? goFactory.darker( (ColorDefinition) cd )
: goFactory.GREY( );
float[] hsbvals = Color.RGBtoHSB( standCD.getRed( ),
standCD.getGreen( ),
standCD.getBlue( ),
null );
float[] startHSB = new float[3];
startHSB[0] = hsbvals[0];
startHSB[1] = hsbvals[1];
startHSB[2] = hsbvals[2];
float[] endHSB = new float[3];
endHSB[0] = hsbvals[0];
endHSB[1] = hsbvals[1];
endHSB[2] = hsbvals[2];
float brightAlpha = 1f / 180;
if ( startAngle < 180 )
{
startHSB[2] = (float) ( startAngle * brightAlpha );
}
else
{
startHSB[2] = (float) ( 1 - ( startAngle - 180 ) * brightAlpha );
}
if ( endAngle < 180 )
{
endHSB[2] = (float) ( endAngle * brightAlpha );
}
else
{
endHSB[2] = (float) ( 1 - ( endAngle - 180 ) * brightAlpha );
}
Color startColor = new Color( Color.HSBtoRGB( startHSB[0],
startHSB[1],
startHSB[2] ) );
Color endColor = new Color( Color.HSBtoRGB( endHSB[0],
endHSB[1],
endHSB[2] ) );
ColorDefinition startCD = goFactory.copyOf( standCD );
startCD.set( startColor.getRed( ),
startColor.getGreen( ),
startColor.getBlue( ) );
ColorDefinition endCD = goFactory.copyOf( standCD );
endCD.set( endColor.getRed( ),
endColor.getGreen( ),
endColor.getBlue( ) );
if ( endAngle <= 180 )
{
return goFactory.createGradient( endCD, startCD, 0, true );
}
else
{
return goFactory.createGradient( startCD, endCD, 0, true );
}
}
}
/**
* Used for deferred rendering
*
* @param topBound
* The top round bounds of pie slice.
* @param bottomBound
* The bottom round bounds of pie slice.
* @param dStartAngle
* The start agnle of pie slice.
* @param dAngleExtent
* The extent angle of pie slice.
* @param lreStartB2T
* The bottom to top line rendering event in start location of
* pie slice.
* @param lreEndB2T
* The top to bottom line rendering event in end location of pie
* slice.
* @param cd
* @param dph
* data point hints.
* @param loC
* center point of bottom cycle.
* @param loCTop
* center point of top cycle.
* @param sz
* width and height of cycle.
*/
private final void registerCurvedSurface( Bounds topBound,
Bounds bottomBound, double dStartAngle, double dAngleExtent,
LineRenderEvent lreStartB2T, LineRenderEvent lreEndB2T, Fill cd,
DataPointHints dph, Location loC, Location loCTop, Size sz )
{
// 1. Get all splited angles.
double[] anglePoints = new double[4];
double endAngle = dStartAngle + dAngleExtent;
int i = 0;
anglePoints[i++] = dStartAngle;
if ( endAngle > 180 && dStartAngle < 180 )
{
anglePoints[i++] = 180;
}
if ( endAngle > 360 && dStartAngle < 360 )
{
anglePoints[i++] = 360;
if ( endAngle > 540 )
{
anglePoints[i++] = 540;
}
}
anglePoints[i] = endAngle;
// 2. Do Render.
if ( i == 1 ) // The simple case, only has one curved plane.
{
// CURVED PLANE 1
final ArcRenderEvent arcRE1 = new ArcRenderEvent( WrappedStructureSource.createSeriesDataPoint( ps,
dph ) );
final ArcRenderEvent arcRE2 = new ArcRenderEvent( WrappedStructureSource.createSeriesDataPoint( ps,
dph ) );
arcRE1.setBounds( topBound );
arcRE1.setStartAngle( dStartAngle );
arcRE1.setAngleExtent( dAngleExtent );
arcRE1.setStyle( ArcRenderEvent.OPEN );
arcRE2.setBounds( bottomBound );
arcRE2.setStartAngle( dStartAngle + dAngleExtent );
arcRE2.setAngleExtent( -dAngleExtent );
arcRE2.setStyle( ArcRenderEvent.OPEN );
AreaRenderEvent areRE = new AreaRenderEvent( WrappedStructureSource.createSeriesDataPoint( ps,
dph ) );
areRE.add( lreStartB2T );
areRE.add( arcRE1 );
areRE.add( lreEndB2T );
areRE.add( arcRE2 );
areRE.setOutline( goFactory.createLineAttributes( getSliceOutline( cd ),
LineStyle.SOLID_LITERAL,
1 ) );
areRE.setBackground( getDepthGradient( cd, dStartAngle, dStartAngle
+ dAngleExtent ) );
deferCurvedPlane( selectPlanesList( dStartAngle ),
dStartAngle,
areRE,
lreStartB2T.getStart( ).getX( ),
lreEndB2T.getStart( ).getX( ) );
}
else
// The multiple case, should be more curved plane.
{
Stack<PrimitiveRenderEvent> lineStack = new Stack<PrimitiveRenderEvent>( );
AreaRenderEvent areLine = new AreaRenderEvent( WrappedStructureSource.createSeriesDataPoint( ps,
dph ) );
areLine.setOutline( goFactory.createLineAttributes( getSliceOutline( cd ),
LineStyle.SOLID_LITERAL,
1 ) );
areLine.setBackground( null );
for ( int j = 0; j < i; j++ )
{
double startAngle = anglePoints[j] + MIN_DOUBLE;
double angleExtent = anglePoints[j + 1] - anglePoints[j];
startAngle = wrapAngle( startAngle );
Object[] edgeLines = getEdgeLines( startAngle,
angleExtent,
loC,
loCTop,
sz,
dph );
// CURVED PLANE 1
final ArcRenderEvent arcRE1 = new ArcRenderEvent( WrappedStructureSource.createSeriesDataPoint( ps,
dph ) );
final ArcRenderEvent arcRE2 = new ArcRenderEvent( WrappedStructureSource.createSeriesDataPoint( ps,
dph ) );
arcRE1.setBounds( topBound );
arcRE1.setStartAngle( startAngle );
arcRE1.setAngleExtent( angleExtent );
arcRE1.setStyle( ArcRenderEvent.OPEN );
arcRE2.setBounds( bottomBound );
arcRE2.setStartAngle( wrapAngle( anglePoints[j + 1] ) );
arcRE2.setAngleExtent( -angleExtent );
arcRE2.setStyle( ArcRenderEvent.OPEN );
// Fill pie slice.
AreaRenderEvent are = new AreaRenderEvent( WrappedStructureSource.createSeriesDataPoint( ps,
dph ) );
are.add( (LineRenderEvent) edgeLines[0] );
are.add( arcRE1 );
are.add( (LineRenderEvent) edgeLines[1] );
are.add( arcRE2 );
are.setOutline( null );
are.setBackground( getDepthGradient( cd,
wrapAngle( anglePoints[j] ),
wrapAngle( anglePoints[j + 1] ) ) );
deferCurvedPlane( selectPlanesList( startAngle ),
startAngle,
are,
( (LineRenderEvent) edgeLines[0] ).getStart( ).getX( ),
( (LineRenderEvent) edgeLines[1] ).getStart( ).getX( ) );
// Arrange pie slice outline.
if ( j == 0 ) // It is first sector of pie slice.
{
areLine.add( (LineRenderEvent) edgeLines[0] );
areLine.add( arcRE1 );
lineStack.push( arcRE2 );
}
else if ( j == ( i - 1 ) ) // It is last sector of pie slice.
{
areLine.add( arcRE1 );
areLine.add( (LineRenderEvent) edgeLines[1] );
areLine.add( arcRE2 );
}
else
{
areLine.add( arcRE1 );
lineStack.push( arcRE2 );
}
}
// Arrange pie slice outline.
while ( !lineStack.empty( ) )
{
areLine.add( lineStack.pop( ) );
}
double mid = dStartAngle + dAngleExtent / 2;
mid = wrapAngle( mid );
// Draw pie slice outline.
deferCurvedOutline( selectPlanesList( mid ), dStartAngle, areLine );
}
}
/**
* Select a planes list by specified start angle of pie slice, the selected
* list will curved rendering sides.
* <p>
* Saving curved rendering sides to different list is to ensure the correct
* rendering order.
*
* @param startAngle
* the start angle of pie slice.
* @return the list contains curved rendering sides.
*/
private List selectPlanesList( double startAngle )
{
if ( startAngle < 180 )
{
return backCurvedPlanes;
}
return frontCurvedPlanes;
}
/**
* @param startAngle
* @param extentAngle
* @param loC
* @param loCTop
* @param sz
* @param dph
* @return
*/
private final Object[] getEdgeLines( double startAngle, double extentAngle,
Location loC, Location loCTop, Size sz, DataPointHints dph )
{
double dAngleInRadians = Math.toRadians( startAngle );
double dSineThetaStart = Math.sin( dAngleInRadians );
double dCosThetaStart = Math.cos( dAngleInRadians );
dAngleInRadians = Math.toRadians( startAngle + extentAngle );
double dSineThetaEnd = Math.sin( dAngleInRadians );
double dCosThetaEnd = Math.cos( dAngleInRadians );
double xE = ( sz.getWidth( ) * dCosThetaEnd );
double yE = ( sz.getHeight( ) * dSineThetaEnd );
double xS = ( sz.getWidth( ) * dCosThetaStart );
double yS = ( sz.getHeight( ) * dSineThetaStart );
final LineRenderEvent lreStartB2T = new LineRenderEvent( WrappedStructureSource.createSeriesDataPoint( ps,
dph ) );
lreStartB2T.setStart( goFactory.createLocation( loC.getX( ) + xS,
loC.getY( )
- yS ) );
lreStartB2T.setEnd( goFactory.createLocation( loCTop.getX( ) + xS,
loCTop.getY( ) - yS ) );
final LineRenderEvent lreEndT2B = new LineRenderEvent( WrappedStructureSource.createSeriesDataPoint( ps,
dph ) );
lreEndT2B.setStart( goFactory.createLocation( loCTop.getX( ) + xE,
loCTop.getY( ) - yE ) );
lreEndT2B.setEnd( goFactory.createLocation( loC.getX( ) + xE,
loC.getY( )
- yE ) );
return new Object[]{
lreStartB2T, lreEndT2B
};
}
/**
*
* @param iIndex
* @return
*/
private final Fill getPaletteColor( int iIndex, DataPointHints dph )
{
Fill fiClone = FillUtil.getPaletteFill( pa.getEntries( ), iIndex );
pie.updateTranslucency( fiClone, ps );
// Convert Fill for negative value
if ( dph != null && dph.getOrthogonalValue( ) instanceof Double )
{
fiClone = FillUtil.convertFill( fiClone,
( (Double) dph.getOrthogonalValue( ) ).doubleValue( ),
null );
}
return fiClone;
}
/**
* CurvedPlane
*/
private final class CurvedPlane implements Comparable, IDrawable
{
private final AreaRenderEvent _are;
private final Bounds _bo;
private final double _angle;
/**
* Constructor of the class.
*
*
*/
CurvedPlane( double angle, AreaRenderEvent are )
{
_are = are;
_bo = are.getBounds( );
_angle = angle;
}
public final Bounds getBounds( )
{
return _bo;
}
/*
* (non-Javadoc)
*
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
public final int compareTo( Object o ) // Z-ORDER TEST
{
final CurvedPlane cp1 = this;
if ( o instanceof CurvedPlane )
{
final CurvedPlane cp2 = (CurvedPlane) o;
final double dMinY1 = cp1.getMinY( );
final double dMinY2 = cp2.getMinY( );
double dDiff = dMinY1 - dMinY2;
if ( !ChartUtil.mathEqual( dDiff, 0 ) )
{
return ( dDiff < 0 ) ? LESS : ( dDiff > 0 ) ? MORE : EQUAL;
}
else
{
final double dMaxY1 = cp1.getMaxY( );
final double dMaxY2 = cp2.getMaxY( );
dDiff = dMaxY1 - dMaxY2;
if ( !ChartUtil.mathEqual( dDiff, 0 ) )
{
return ( dDiff < 0 ) ? LESS : MORE;
}
else
{
final double dMinX1 = cp1.getMinX( );
final double dMinX2 = cp2.getMinX( );
dDiff = dMinX1 - dMinX2;
if ( !ChartUtil.mathEqual( dDiff, 0 ) )
{
return ( dDiff < 0 ) ? LESS : MORE;
}
else
{
final double dMaxX1 = cp1.getMaxX( );
final double dMaxX2 = cp2.getMaxX( );
dDiff = dMaxX1 - dMaxX2;
if ( !ChartUtil.mathEqual( dDiff, 0 ) )
{
return ( dDiff < 0 ) ? LESS : MORE;
}
else
{
return EQUAL;
}
}
}
}
}
else if ( o instanceof FlatPlane )
{
final FlatPlane pi2 = (FlatPlane) o;
return pi2.compareTo( cp1 ) * -1; // DELEGATE AND INVERT
// RESULT
}
return EQUAL;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.chart.prototype.Pie.IDrawable#draw(java.awt.Graphics2D)
*/
public final void draw( ) throws ChartException
{
idr.fillArea( _are );
idr.drawArea( _are );
/*
* GradientPaint gp = new GradientPaint( (float)dGradientStart2D, 0,
* Color.black, (float)(dGradientStart2D + (dGradientEnd2D -
* dGradientStart2D)/2), 0, _c, true); g2d.setPaint(gp);
* g2d.fill(_sh); g2d.setColor(_c.darker()); g2d.draw(_sh);
*/
}
private final double getMinY( )
{
return _bo.getTop( );
}
private final double getMinX( )
{
return _bo.getLeft( );
}
private final double getMaxX( )
{
return _bo.getLeft( ) + _bo.getWidth( );
}
private final double getMaxY( )
{
return _bo.getTop( ) + _bo.getHeight( );
}
public double getAngle( )
{
return _angle;
}
}
/**
* FlatPlane
*/
private final class FlatPlane implements Comparable, IDrawable
{
private final double[] _daXPoints, _daYPoints;
private final Fill _cd;
private final Bounds _bo;
private final DataPointHints _dph;
private final double _angle;
/**
* Constructor of the class.
*
* @param angle
* the start angle will be used to decide the painting order.
* @param daXPoints
* @param daYPoints
* @param cd
* @param dph
*/
FlatPlane( double angle, double[] daXPoints, double[] daYPoints,
Fill cd, DataPointHints dph )
{
_angle = angle;
_daXPoints = daXPoints;
_daYPoints = daYPoints;
_dph = dph;
// COMPUTE THE BOUNDS
final int n = _daXPoints.length;
double dMinX = 0, dMinY = 0, dMaxX = 0, dMaxY = 0;
for ( int i = 0; i < n; i++ )
{
if ( i == 0 )
{
dMinX = _daXPoints[i];
dMinY = _daYPoints[i];
dMaxX = dMinX;
dMaxY = dMinY;
}
else
{
if ( dMinX > _daXPoints[i] )
{
dMinX = _daXPoints[i];
}
if ( dMinY > _daYPoints[i] )
{
dMinY = _daYPoints[i];
}
if ( dMaxX < _daXPoints[i] )
{
dMaxX = _daXPoints[i];
}
if ( dMaxY < _daYPoints[i] )
{
dMaxY = _daYPoints[i];
}
}
}
_bo = goFactory.createBounds( dMinX, dMinY, dMaxX - dMinX, dMaxY
- dMinY );
_cd = cd;
int nPoints = _daXPoints.length;
int[] iaX = new int[nPoints];
int[] iaY = new int[nPoints];
for ( int i = 0; i < nPoints; i++ )
{
iaX[i] = (int) daXPoints[i];
iaY[i] = (int) daYPoints[i];
}
// _p = new Polygon(iaX, iaY, nPoints);
}
public Bounds getBounds( )
{
return _bo;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.chart.prototype.Pie.IDrawable#draw(java.awt.Graphics2D)
*/
public final void draw( ) throws ChartException
{
PolygonRenderEvent pre = ( (EventObjectCache) idr ).getEventObject( WrappedStructureSource.createSeriesDataPoint( ps,
_dph ),
PolygonRenderEvent.class );
pre.setPoints( toLocationArray( ) );
liaEdges.setColor( getSliceOutline( _cd ) );
pre.setOutline( liaEdges );
pre.setBackground( getDepthGradient( _cd ) );
idr.fillPolygon( pre );
idr.drawPolygon( pre );
}
/*
* (non-Javadoc)
*
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
public final int compareTo( Object o ) // Z-ORDER TEST
{
final FlatPlane pi1 = this;
if ( o instanceof FlatPlane )
{
final FlatPlane pi2 = (FlatPlane) o;
final double dMinY1 = pi1.getMinY( );
final double dMinY2 = pi2.getMinY( );
double dDiff = dMinY1 - dMinY2;
if ( !ChartUtil.mathEqual( dDiff, 0 ) )
{
return ( dDiff < 0 ) ? LESS : ( dDiff > 0 ) ? MORE : EQUAL;
}
else
{
final double dMaxY1 = pi1.getMaxY( );
final double dMaxY2 = pi2.getMaxY( );
dDiff = dMaxY1 - dMaxY2;
if ( !ChartUtil.mathEqual( dDiff, 0 ) )
{
return ( dDiff < 0 ) ? LESS : MORE;
}
else
{
final double dMinX1 = pi1.getMinX( );
final double dMinX2 = pi2.getMinX( );
dDiff = dMinX1 - dMinX2;
if ( !ChartUtil.mathEqual( dDiff, 0 ) )
{
return ( dDiff < 0 ) ? LESS : MORE;
}
else
{
final double dMaxX1 = pi1.getMaxX( );
final double dMaxX2 = pi2.getMaxX( );
dDiff = dMaxX1 - dMaxX2;
if ( !ChartUtil.mathEqual( dDiff, 0 ) )
{
return ( dDiff < 0 ) ? LESS : MORE;
}
else
{
return EQUAL;
}
}
}
}
}
else if ( o instanceof CurvedPlane )
{
final CurvedPlane pi2 = (CurvedPlane) o;
final double dMinY1 = pi1.getMinY( );
final double dMinY2 = pi2.getMinY( );
double dDiff = dMinY1 - dMinY2;
if ( !ChartUtil.mathEqual( dDiff, 0 ) )
{
return ( dDiff < 0 ) ? LESS : MORE;
}
else
{
final double dMaxY1 = pi1.getMaxY( );
final double dMaxY2 = pi2.getMaxY( );
dDiff = dMaxY1 - dMaxY2;
if ( !ChartUtil.mathEqual( dDiff, 0 ) )
{
return ( dDiff < 0 ) ? LESS : MORE;
}
else
{
final double dMinX1 = pi1.getMinX( );
final double dMinX2 = pi2.getMinX( );
dDiff = dMinX1 - dMinX2;
if ( !ChartUtil.mathEqual( dDiff, 0 ) )
{
return ( dDiff < 0 ) ? LESS : MORE;
}
else
{
final double dMaxX1 = pi1.getMaxX( );
final double dMaxX2 = pi2.getMaxX( );
dDiff = dMaxX1 - dMaxX2;
if ( !ChartUtil.mathEqual( dDiff, 0 ) )
{
return ( dDiff < 0 ) ? LESS : MORE;
}
else
{
return EQUAL;
}
}
}
}
}
return EQUAL;
}
private final double getMinY( )
{
return _bo.getTop( );
}
private final double getMinX( )
{
return _bo.getLeft( );
}
private final double getMaxX( )
{
return _bo.getLeft( ) + _bo.getWidth( );
}
private final double getMaxY( )
{
return _bo.getTop( ) + _bo.getHeight( );
}
private final Location[] toLocationArray( )
{
final int n = _daXPoints.length;
Location[] loa = new Location[n];
for ( int i = 0; i < n; i++ )
{
loa[i] = goFactory.createLocation( _daXPoints[i], _daYPoints[i] );
}
return loa;
}
public double getAngle( )
{
return _angle;
}
}
/**
* IDrawable
*/
private interface IDrawable
{
void draw( ) throws ChartException;
Bounds getBounds( );
}
private static class OutsideLabelBoundCache
{
public int iLL = 0;
public BoundingBox bb = null;
public void reset( )
{
iLL = 0;
bb = null;
}
}
public class PieSlice implements Cloneable
{
private boolean isExploded = true;
private double originalStartAngle;
private double startAngle;
private double sliceLength;
private double slicePecentage;
private int categoryIndex;
private DataPointHints dataPointHints;
private double primitiveValue;
private int quadrant = -1;
private Location loPie;
private Location loStart;
private Location loEnd;
private BoundingBox labelBounding = null;
private Label la;
private Bounds bounds = null;
private double w, h, xc, yc;
private double xDock, yDock;
PieSlice( double primitiveValue, DataPointHints dataPointHints,
int categroyIndex ) throws ChartException
{
this.primitiveValue = primitiveValue;
this.dataPointHints = dataPointHints;
this.categoryIndex = categroyIndex;
createSliceLabel();
}
public void createSliceLabel( ) throws ChartException
{
if ( this.la != null )
{
return; // can only create once
}
this.la = goFactory.copyOf( ps.getLabel( ) );
la.getCaption( ).setValue( getDisplayValue( ) );
final AbstractScriptHandler sh = pie.getRunTimeContext( ).getScriptHandler( );
ScriptHandler.callFunction( sh,
ScriptHandler.BEFORE_DRAW_DATA_POINT_LABEL,
getDataPointHints( ),
la,
pie.getRunTimeContext( ).getScriptContext( ) );
pie.getRunTimeContext( )
.notifyStructureChange( IStructureDefinitionListener.BEFORE_DRAW_DATA_POINT_LABEL,
la );
}
private PieSlice( )
{
// Used to clone
}
public Label getLabel( )
{
return la;
}
/* (non-Javadoc)
* @see java.lang.Object#clone()
*/
@Override
public Object clone( )
{
PieSlice slice;
try
{
slice = (PieSlice) super.clone( );
}
catch ( CloneNotSupportedException e )
{
slice = new PieSlice( );
}
copyTo( slice );
return slice;
}
public void copyTo( PieSlice slice )
{
slice.primitiveValue = primitiveValue;
slice.dataPointHints = dataPointHints;
slice.categoryIndex = this.categoryIndex;
slice.setLabelLocation( loPie, loStart, loEnd );
slice.setExploded( isExploded );
slice.setStartAngle( startAngle );
slice.setSliceLength( sliceLength );
slice.setPercentage( slicePecentage );
slice.setBounds( bounds );
slice.labelBounding = labelBounding;
slice.quadrant = quadrant;
}
public double getPrimitiveValue( )
{
return primitiveValue;
}
public DataPointHints getDataPointHints( )
{
return dataPointHints;
}
public String getDisplayValue( )
{
return dataPointHints.getDisplayValue( );
}
public double getOriginalStartAngle( )
{
return originalStartAngle;
}
public double getStartAngle( )
{
return startAngle;
}
public double getSliceLength( )
{
return sliceLength;
}
public double getdMidAngle( )
{
return startAngle + sliceLength / 2;
}
public double getOriginalMidAngle( )
{
return originalStartAngle + sliceLength / 2;
}
public double getSlicePercentage( )
{
return slicePecentage;
}
public int getCategoryIndex( )
{
return categoryIndex;
}
public int getQuadrant( )
{
return quadrant;
}
public void setLabelLocation( double dX0, double dY0, double dX1,
double dY1, double dX2, double dY2 )
{
setLabelLocation( goFactory.createLocation( dX0, dY0 ),
goFactory.createLocation( dX1, dY1 ),
goFactory.createLocation( dX2, dY2 ) );
}
public void setLabelLocation( Location loPie, Location loStart,
Location loEnd )
{
this.loPie = loPie;
this.loStart = loStart;
this.loEnd = loEnd;
}
public void setExploded( boolean isExploded )
{
this.isExploded = isExploded;
}
public void setOriginalStartAngle( double originalStartAngle )
{
this.originalStartAngle = originalStartAngle;
}
public void setStartAngle( double startAngle )
{
this.startAngle = startAngle;
}
public void setSliceLength( double newLength )
{
sliceLength = newLength;
}
public void setPercentage( double newPercentage )
{
slicePecentage = newPercentage;
}
public final BoundingBox getLabelBounding( )
{
return labelBounding;
}
public void removeLabelBounding( )
{
// Added to resolve empty category stacking (Bugzilla 197128)
labelBounding = null;
}
/**
* @param loC
* center coordinates of pie slice.
* @param loOffset
* pie slice officeset for multiple dimension.
* @param sz
* the width and height of pie slice.
* @param fi
* the fill properties.
* @param iPieceType
* @throws ChartException
*/
private final void render( Location loC, Location loOffset, Size sz,
Fill fi, int iPieceType ) throws ChartException
{
loC.translate( loOffset.getX( ) / 2d, loOffset.getY( ) / 2d );
if ( isExploded && dExplosion != 0 )
{
// double dRatio = (double) d.width / d.height;
double dMidAngleInRadians = Math.toRadians( getStartAngle( )
+ getSliceLength( )
/ 2d );
double dSineThetaMid = ( Math.sin( dMidAngleInRadians ) );
double dCosThetaMid = ( Math.cos( dMidAngleInRadians ) );
double xDelta = ( dExplosion * dCosThetaMid );
double yDelta = ( dExplosion * dSineThetaMid );
if ( ratio < 1 )
{
yDelta = yDelta * ratio;
}
else
{
xDelta = xDelta / ratio;
}
loC.translate( xDelta, -yDelta );
}
Location loCTop = goFactory.createLocation( loC.getX( )
- loOffset.getX( ), loC.getY( ) - loOffset.getY( ) );
double dAngleInRadians = Math.toRadians( getStartAngle( ) );
double dSineThetaStart = Math.sin( dAngleInRadians );
double dCosThetaStart = Math.cos( dAngleInRadians );
dAngleInRadians = Math.toRadians( getStartAngle( )
+ getSliceLength( ) );
double dSineThetaEnd = Math.sin( dAngleInRadians );
double dCosThetaEnd = Math.cos( dAngleInRadians );
double xE = ( sz.getWidth( ) * dCosThetaEnd );
double yE = ( sz.getHeight( ) * dSineThetaEnd );
double xS = ( sz.getWidth( ) * dCosThetaStart );
double yS = ( sz.getHeight( ) * dSineThetaStart );
ArcRenderEvent are = null;
if ( iPieceType == LOWER )
{
are = new ArcRenderEvent( WrappedStructureSource.createSeriesDataPoint( ps,
dataPointHints ) );
}
else
{
are = ( (EventObjectCache) idr ).getEventObject( WrappedStructureSource.createSeriesDataPoint( ps,
getDataPointHints( ) ),
ArcRenderEvent.class );
}
are.setBackground( fi );
liaEdges.setColor( getSliceOutline( fi ) );
are.setOutline( liaEdges );
are.setTopLeft( goFactory.createLocation( loCTop.getX( )
- sz.getWidth( ),
loCTop.getY( )
- sz.getHeight( )
+ ( iPieceType == LOWER ? dThickness : 0 ) ) );
are.setWidth( sz.getWidth( ) * 2 );
are.setHeight( sz.getHeight( ) * 2 );
are.setStartAngle( startAngle );
are.setAngleExtent( sliceLength );
are.setStyle( ArcRenderEvent.SECTOR );
idr.fillArc( are ); // Fill the top side of pie slice.
if ( iPieceType == LOWER )
{
// DRAWN INTO A BUFFER FOR DEFERRED RENDERING
double[] daXPoints = {
loC.getX( ),
loCTop.getX( ),
loCTop.getX( ) + xE,
loC.getX( ) + xE
};
double[] daYPoints = {
loC.getY( ),
loCTop.getY( ),
loCTop.getY( ) - yE,
loC.getY( ) - yE
};
deferFlatPlane( flatPlanes,
getStartAngle( ) + getSliceLength( ),
daXPoints,
daYPoints,
fi,
dataPointHints );
daXPoints = new double[]{
loC.getX( ),
loC.getX( ) + xS,
loCTop.getX( ) + xS,
loCTop.getX( )
};
daYPoints = new double[]{
loC.getY( ),
loC.getY( ) - yS,
loCTop.getY( ) - yS,
loCTop.getY( )
};
deferFlatPlane( flatPlanes,
getStartAngle( ),
daXPoints,
daYPoints,
fi,
dataPointHints );
daXPoints = new double[]{
loC.getX( ) + xS,
loCTop.getX( ) + xS,
loCTop.getX( ) + xE,
loC.getX( ) + xE
};
daYPoints = new double[]{
loC.getY( ) - yS,
loCTop.getY( ) - yS,
loCTop.getY( ) - yE,
loC.getY( ) - yE
};
final LineRenderEvent lreStartB2T = new LineRenderEvent( WrappedStructureSource.createSeriesDataPoint( ps,
dataPointHints ) );
lreStartB2T.setStart( goFactory.createLocation( loC.getX( )
+ xS,
loC.getY( ) - yS ) );
lreStartB2T.setEnd( goFactory.createLocation( loCTop.getX( )
+ xS,
loCTop.getY( ) - yS ) );
final LineRenderEvent lreEndT2B = new LineRenderEvent( WrappedStructureSource.createSeriesDataPoint( ps,
dataPointHints ) );
lreEndT2B.setStart( goFactory.createLocation( loCTop.getX( )
+ xE,
loCTop.getY( ) - yE ) );
lreEndT2B.setEnd( goFactory.createLocation( loC.getX( ) + xE,
loC.getY( ) - yE ) );
Bounds r2ddTop = goFactory.createBounds( loCTop.getX( )
- sz.getWidth( ),
loCTop.getY( ) - sz.getHeight( ),
sz.getWidth( ) * 2,
sz.getHeight( ) * 2 );
Bounds r2ddBottom = goFactory.createBounds( loC.getX( )
- sz.getWidth( ),
loC.getY( ) - sz.getHeight( ),
sz.getWidth( ) * 2,
sz.getHeight( ) * 2 );
registerCurvedSurface( r2ddTop,
r2ddBottom,
getStartAngle( ),
getSliceLength( ),
lreStartB2T,
lreEndT2B,
fi,
dataPointHints,
loC,
loCTop,
sz );
}
else if ( iPieceType == UPPER ) // DRAWN IMMEDIATELY
{
if ( ps.getSliceOutline( ) != null )
{
idr.drawArc( are );
}
if ( pie.isInteractivityEnabled( ) )
{
final EList<Trigger> elTriggers = ps.getTriggers( );
if ( !elTriggers.isEmpty( ) )
{
final StructureSource iSource = WrappedStructureSource.createSeriesDataPoint( ps,
dataPointHints );
final InteractionEvent iev = ( (EventObjectCache) idr ).getEventObject( iSource,
InteractionEvent.class );
iev.setCursor( ps.getCursor( ) );
Trigger tg;
for ( int t = 0; t < elTriggers.size( ); t++ )
{
tg = goFactory.copyOf( elTriggers.get( t ) );
pie.processTrigger( tg, iSource );
iev.addTrigger( tg );
}
iev.setHotSpot( are );
idr.enableInteraction( iev );
}
}
}
}
private void renderOneLine( IDeviceRenderer idr, Location lo1,
Location lo2 ) throws ChartException
{
LineRenderEvent lre = ( (EventObjectCache) idr ).getEventObject( WrappedStructureSource.createSeriesDataPoint( ps,
dataPointHints ),
LineRenderEvent.class );
lre.setLineAttributes( liaLL );
lre.setStart( lo1 );
lre.setEnd( lo2 );
idr.drawLine( lre );
}
private final void renderLabel( IDeviceRenderer idr, int iTextRenderType )
throws ChartException
{
if ( labelBounding == null )
{// Do not render if no bounding
return;
}
if ( quadrant != -1 )
{
if ( iTextRenderType == TextRenderEvent.RENDER_TEXT_AT_LOCATION )
{
renderOneLine( idr, loPie, loStart );
renderOneLine( idr, loStart, loEnd );
}
pie.renderLabel( WrappedStructureSource.createSeriesDataPoint( ps,
dataPointHints ),
TextRenderEvent.RENDER_TEXT_IN_BLOCK,
getLabel( ),
( quadrant == 1 || quadrant == 4 ) ? Position.RIGHT_LITERAL
: Position.LEFT_LITERAL,
loEnd,
goFactory.createBounds( labelBounding.getLeft( ),
labelBounding.getTop( ),
labelBounding.getWidth( ),
labelBounding.getHeight( ) ) );
}
else
{
pie.renderLabel( StructureSource.createSeries( ps ),
TextRenderEvent.RENDER_TEXT_IN_BLOCK,
getLabel( ),
null,
null,
goFactory.createBounds( labelBounding.getLeft( ),
labelBounding.getTop( ),
labelBounding.getWidth( ),
labelBounding.getHeight( ) ) );
}
}
public boolean isLabelClipped( Bounds bo )
{
if ( labelBounding != null )
{
if ( labelBounding.getTop( ) < bo.getTop( ) )
{
return true;
}
if ( labelBounding.getLeft( ) < bo.getLeft( ) )
{
return true;
}
if ( labelBounding.getTop( ) + labelBounding.getHeight( ) > bo.getTop( )
+ bo.getHeight( ) )
{
return true;
}
if ( labelBounding.getLeft( ) + labelBounding.getWidth( ) > bo.getLeft( )
+ bo.getWidth( ) )
{
return true;
}
}
return false;
}
public boolean isLabelOverlap( PieSlice sliceToCompare )
{
if ( sliceToCompare == null
|| sliceToCompare == this
|| sliceToCompare.labelBounding == null )
{
return false;
}
BoundingBox bb1 = labelBounding, bb2 = sliceToCompare.labelBounding;
BoundingBox dHigh, dLow;
// check which one is higher
if ( bb1.getTop( ) < bb2.getTop( ) )
{
dHigh = bb1;
dLow = bb2;
}
else
{
dHigh = bb2;
dLow = bb1;
}
double dXHigh, dXLow, dYHigh, dYLow;
if ( dHigh.getLeft( ) < dLow.getLeft( ) )
{
dXHigh = dHigh.getLeft( ) + dHigh.getWidth( );
dYHigh = dHigh.getTop( ) + dHigh.getHeight( );
dXLow = dLow.getLeft( );
dYLow = dLow.getTop( );
if ( dXHigh > dXLow && dYHigh > dYLow )
{
return true;
}
}
else
{
dXHigh = dHigh.getLeft( );
dYHigh = dHigh.getTop( ) + dHigh.getHeight( );
dXLow = dLow.getLeft( ) + dLow.getWidth( );
dYLow = dLow.getTop( );
if ( dXHigh < dXLow && dYHigh > dYLow )
{
return true;
}
}
return false;
}
public void setBounds( Bounds bo )
{
bounds = bo;
w = bounds.getWidth( ) / 2 - dExplosion;
h = bounds.getHeight( ) / 2 - dExplosion - dThickness / 2;
xc = bounds.getLeft( ) + w + dExplosion;
yc = bounds.getTop( ) + h + dExplosion + dThickness / 2;
if ( ratio > 0 && w > 0 )
{
if ( h / w > ratio )
{
h = w * ratio;
}
else if ( h / w < ratio )
{
w = h / ratio;
}
}
// detect invalid size.
if ( w <= 0 || h <= 0 )
{
w = h = 1;
}
}
private void computeLabelBoundOutside( LeaderLineStyle lls,
double dLeaderLength, OutsideLabelBoundCache bbCache )
throws ChartException
{
int iLL = 0;
double dLeaderTick = Math.max( dLeaderLength / 4,
LEADER_TICK_MIN_SIZE * pie.getDeviceScale( ) );
double dLeaderW = 0, dLeaderH = 0, dBottomLeaderW = 0, dBottomLeaderH = 0, dTopLeaderW = 0, dTopLeaderH = 0;
Location center = goFactory.createLocation( xc, yc - dThickness / 2 );
Location depthCenter = goFactory.createLocation( xc, yc ); // center
// in
// the
// middle of the depth
double dX = 0;
double dLeftSide = xc - dExplosion - w;
double dRightSide = xc + dExplosion + w;
if ( w > h )
{
dTopLeaderW = dLeaderTick;
dTopLeaderH = dLeaderTick * ratio;
}
else
{
dTopLeaderH = dLeaderTick;
dTopLeaderW = dLeaderTick / ratio;
}
double dMidAngleInDegrees = getOriginalMidAngle( ) % 360;
double dMidAngleInRadians = Math.toRadians( -dMidAngleInDegrees );
double dSineThetaMid = Math.sin( dMidAngleInRadians );
double dCosThetaMid = Math.cos( dMidAngleInRadians );
if ( dThickness > 0
&& dMidAngleInDegrees > 180
&& dMidAngleInDegrees < 360 )
{
double dTmpLeaderTick = Math.max( dThickness
* dSineThetaMid
+ 8
* pie.getDeviceScale( ), dLeaderTick );
if ( w > h )
{
dBottomLeaderW = dTmpLeaderTick;
dBottomLeaderH = dTmpLeaderTick * ratio;
}
else
{
dBottomLeaderH = dTmpLeaderTick;
dBottomLeaderW = dTmpLeaderTick / ratio;
}
dLeaderW = dBottomLeaderW;
dLeaderH = dBottomLeaderH;
}
else
{
dLeaderW = dTopLeaderW;
dLeaderH = dTopLeaderH;
}
double xDelta1, yDelta1, xDelta2, yDelta2;
if ( isExploded )
{
xDelta1 = ( w + dExplosion ) * dCosThetaMid;
yDelta1 = ( h + dExplosion ) * dSineThetaMid;
xDelta2 = ( w + dLeaderW + dExplosion ) * dCosThetaMid;
yDelta2 = ( h + dLeaderH + dExplosion ) * dSineThetaMid;
}
else
{
xDelta1 = ( w ) * dCosThetaMid;
yDelta1 = ( h ) * dSineThetaMid;
xDelta2 = ( w + dLeaderW ) * dCosThetaMid;
yDelta2 = ( h + dLeaderH ) * dSineThetaMid;
}
if ( lls == LeaderLineStyle.STRETCH_TO_SIDE_LITERAL )
{
if ( dMidAngleInDegrees >= 90 && dMidAngleInDegrees < 270 )
{
dX = dLeftSide - dLeaderW * 1.5;
iLL = IConstants.LEFT;
}
else
{
dX = dRightSide + dLeaderW * 1.5;
iLL = IConstants.RIGHT;
}
}
else if ( lls == LeaderLineStyle.FIXED_LENGTH_LITERAL )
{
if ( dMidAngleInDegrees > 90 && dMidAngleInDegrees < 270 )
{
dX = center.getX( ) + xDelta2 - dLeaderLength;
if ( dLeaderLength > 0 )
{
iLL = IConstants.LEFT;
}
else
{
if ( dMidAngleInDegrees < 135 )
{
iLL = IConstants.TOP;
}
else if ( dMidAngleInDegrees < 225 )
{
iLL = IConstants.LEFT;
}
else if ( dMidAngleInDegrees < 270 )
{
iLL = IConstants.BOTTOM;
}
else
assert false;
}
}
else
{
dX = center.getX( ) + xDelta2 + dLeaderLength;
if ( dLeaderLength > 0 )
{
iLL = IConstants.RIGHT;
}
else
{
if ( dMidAngleInDegrees <= 45 )
{
iLL = IConstants.RIGHT;
}
else if ( dMidAngleInDegrees > 45
&& dMidAngleInDegrees <= 90 )
{
iLL = IConstants.TOP;
}
else if ( dMidAngleInDegrees <= 315
&& dMidAngleInDegrees >= 270 )
{
iLL = IConstants.BOTTOM;
}
else if ( dMidAngleInDegrees > 315 )
{
iLL = IConstants.RIGHT;
}
else
assert false;
}
}
}
else
{
// SHOULD'VE ALREADY THROWN THIS EXCEPTION PREVIOUSLY
}
Location relativeCenter;
if ( dMidAngleInDegrees > 0 && dMidAngleInDegrees < 180 )
{
relativeCenter = center;
}
else
{
relativeCenter = depthCenter;
}
xDock = relativeCenter.getX( ) + xDelta1;
yDock = relativeCenter.getY( ) + yDelta1;
setLabelLocation( xDock,
yDock,
relativeCenter.getX( ) + xDelta2,
relativeCenter.getY( ) + yDelta2,
dX,
relativeCenter.getY( ) + yDelta2 );
if ( bbCache != null && bbCache.iLL == iLL && bbCache.bb != null )
{
labelBounding = bbCache.bb.clone( );
}
else
{
labelBounding = cComp.computeBox( xs, iLL, getLabel( ), 0, 0 );
if ( bbCache != null && bbCache.iLL == 0 )
{
bbCache.iLL = iLL;
bbCache.bb = labelBounding.clone( );
}
}
labelBounding.setLeft( labelBounding.getLeft( ) + dX );
labelBounding.setTop( labelBounding.getTop( )
+ relativeCenter.getY( )
+ yDelta2 );
// NEEDED FOR COMPUTING DYNAMIC REPOSITIONING LIMITS
if ( dMidAngleInDegrees >= 0 && dMidAngleInDegrees < 90 )
{
quadrant = 1;
}
if ( dMidAngleInDegrees >= 90 && dMidAngleInDegrees < 180 )
{
quadrant = 2;
}
if ( dMidAngleInDegrees >= 180 && dMidAngleInDegrees < 270 )
{
quadrant = 3;
}
else
{
quadrant = 4;
}
}
private void computeLabelBoundInside( ) throws ChartException
{
double dMidAngleInRadians = Math.toRadians( -getdMidAngle( ) );
double dSineThetaMid = Math.sin( dMidAngleInRadians );
double dCosThetaMid = Math.cos( dMidAngleInRadians );
double xDelta, yDelta;
if ( isExploded )
{
xDelta = ( ( w / 1.5d + dExplosion ) * dCosThetaMid );
yDelta = ( ( h / 1.5d + dExplosion ) * dSineThetaMid );
}
else
{
xDelta = ( ( w / 1.5d ) * dCosThetaMid );
yDelta = ( ( h / 1.5d ) * dSineThetaMid );
}
labelBounding = cComp.computeBox( xs,
IConstants.LEFT/* DONT-CARE */,
getLabel( ),
0,
0 );
labelBounding.setLeft( xc + xDelta - labelBounding.getWidth( ) / 2 );
labelBounding.setTop( yc
- dThickness
/ 2
+ yDelta
- labelBounding.getHeight( )
/ 2 );
}
}
} | chart/org.eclipse.birt.chart.engine.extension/src/org/eclipse/birt/chart/extension/render/PieRenderer.java | /***********************************************************************
* Copyright (c) 2004,2005,2006,2007 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
***********************************************************************/
package org.eclipse.birt.chart.extension.render;
import java.awt.Color;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;
import org.eclipse.birt.chart.computation.BoundingBox;
import org.eclipse.birt.chart.computation.DataPointHints;
import org.eclipse.birt.chart.computation.GObjectFactory;
import org.eclipse.birt.chart.computation.IChartComputation;
import org.eclipse.birt.chart.computation.IConstants;
import org.eclipse.birt.chart.computation.IGObjectFactory;
import org.eclipse.birt.chart.device.IDeviceRenderer;
import org.eclipse.birt.chart.device.IDisplayServer;
import org.eclipse.birt.chart.device.IStructureDefinitionListener;
import org.eclipse.birt.chart.engine.extension.i18n.Messages;
import org.eclipse.birt.chart.event.ArcRenderEvent;
import org.eclipse.birt.chart.event.AreaRenderEvent;
import org.eclipse.birt.chart.event.EventObjectCache;
import org.eclipse.birt.chart.event.InteractionEvent;
import org.eclipse.birt.chart.event.LineRenderEvent;
import org.eclipse.birt.chart.event.PolygonRenderEvent;
import org.eclipse.birt.chart.event.PrimitiveRenderEvent;
import org.eclipse.birt.chart.event.StructureSource;
import org.eclipse.birt.chart.event.TextRenderEvent;
import org.eclipse.birt.chart.event.WrappedStructureSource;
import org.eclipse.birt.chart.exception.ChartException;
import org.eclipse.birt.chart.factory.RunTimeContext.StateKey;
import org.eclipse.birt.chart.log.ILogger;
import org.eclipse.birt.chart.log.Logger;
import org.eclipse.birt.chart.model.ChartWithoutAxes;
import org.eclipse.birt.chart.model.attribute.Bounds;
import org.eclipse.birt.chart.model.attribute.ChartDimension;
import org.eclipse.birt.chart.model.attribute.ColorDefinition;
import org.eclipse.birt.chart.model.attribute.Fill;
import org.eclipse.birt.chart.model.attribute.Gradient;
import org.eclipse.birt.chart.model.attribute.Insets;
import org.eclipse.birt.chart.model.attribute.LeaderLineStyle;
import org.eclipse.birt.chart.model.attribute.LegendItemType;
import org.eclipse.birt.chart.model.attribute.LineAttributes;
import org.eclipse.birt.chart.model.attribute.LineStyle;
import org.eclipse.birt.chart.model.attribute.Location;
import org.eclipse.birt.chart.model.attribute.Palette;
import org.eclipse.birt.chart.model.attribute.Position;
import org.eclipse.birt.chart.model.attribute.Size;
import org.eclipse.birt.chart.model.attribute.impl.SizeImpl;
import org.eclipse.birt.chart.model.component.Label;
import org.eclipse.birt.chart.model.data.Trigger;
import org.eclipse.birt.chart.model.type.PieSeries;
import org.eclipse.birt.chart.plugin.ChartEngineExtensionPlugin;
import org.eclipse.birt.chart.script.AbstractScriptHandler;
import org.eclipse.birt.chart.script.ScriptHandler;
import org.eclipse.birt.chart.util.ChartUtil;
import org.eclipse.birt.chart.util.FillUtil;
import org.eclipse.emf.common.util.EList;
/**
* PieRenderer
*/
public final class PieRenderer
{
static final int UNKNOWN = 0;
protected static final IGObjectFactory goFactory = GObjectFactory.instance( );
private static final int LOWER = 1;
private static final int UPPER = 2;
private static final double LEADER_TICK_MIN_SIZE = 10; // POINTS
private static final int LESS = -1;
private static final int MORE = 1;
private static final int EQUAL = 0;
private final Position lpDataPoint;
private final Position lpSeriesTitle;
private transient double dLeaderLength;
private final LeaderLineStyle lls;
/**
* Series thickness
*/
private transient final double dThickness;
private transient double dExplosion = 0;
private transient String sExplosionExpression = null;
private final Pie pie;
private final PieSeries ps;
private final List<PieSlice> pieSliceList = new ArrayList<PieSlice>( );
/**
* Holds list of deferred planes (flat and curved) to be sorted before
* rendering
*/
/**
* The list stores back curved planes whose angle are between 0 to 180 and
* will be drown before drawing flat planes and front curved planes.
*/
private final List backCurvedPlanes = new ArrayList( );
/**
* The list stores front curved planes whose angle are between 180 to 360
* and will be drown after drawing back planes and front planes.
*/
private final List frontCurvedPlanes = new ArrayList( );
/** The list stores all flat planes of pie slices. */
private final List flatPlanes = new ArrayList( );
private final Palette pa;
private final Label laSeriesTitle;
private final LineAttributes liaLL;
private final LineAttributes liaEdges;
private transient IDisplayServer xs = null;
private transient IDeviceRenderer idr = null;
private transient Bounds boTitleContainer = null;
private transient Bounds boSeriesNoTitle = null;
private transient Insets insCA = null;
private transient Bounds boSetDuringComputation = null;
private final boolean bPaletteByCategory;
private transient boolean bBoundsAdjustedForInsets = false;
private transient boolean bMinSliceDefined = false;
private transient double dMinSlice = 0;
private transient double dAbsoluteMinSlice = 0;
private transient boolean bPercentageMinSlice = false;
private transient boolean bMinSliceApplied = false;
private transient int orginalSliceCount = 0;
private transient double ratio = 0;
private transient double rotation = 0;
private final IChartComputation cComp;
/**
* The constant variable is used to adjust start angle of plane for getting
* correct rendering order of planes.
* <p>
*
* Note: Since its value is very little, it will not affect computing the
* coordinates of pie slice.
*/
private final double MIN_DOUBLE = 0.0000000001d;
private static ILogger logger = Logger.getLogger( "org.eclipse.birt.chart.engine.extension/render" ); //$NON-NLS-1$
/**
*
* @param cwoa
* @param pie
* @param dpha
* @param da
* @param pa
*/
PieRenderer( ChartWithoutAxes cwoa, Pie pie, DataPointHints[] dpha,
double[] da, Palette pa ) throws ChartException
{
this.pa = pa;
this.pie = pie;
this.cComp = pie.getRunTimeContext( )
.getState( StateKey.CHART_COMPUTATION_KEY );
ps = (PieSeries) pie.getSeries( );
sExplosionExpression = ps.getExplosionExpression( );
dExplosion = ps.getExplosion( ) * pie.getDeviceScale( );
dThickness = ( ( cwoa.getDimension( ) == ChartDimension.TWO_DIMENSIONAL_LITERAL ) ? 0
: cwoa.getSeriesThickness( ) )
* pie.getDeviceScale( );
ratio = ps.isSetRatio( ) ? ps.getRatio( ) : 1;
rotation = ps.isSetRotation( ) ? ps.getRotation( ) : 0;
liaLL = ps.getLeaderLineAttributes( );
if ( ps.getLeaderLineAttributes( ).isVisible( ) )
{
dLeaderLength = ps.getLeaderLineLength( ) * pie.getDeviceScale( );
}
else
{
dLeaderLength = 0;
}
liaEdges = goFactory.createLineAttributes( goFactory.BLACK( ),
LineStyle.SOLID_LITERAL,
1 );
bPaletteByCategory = ( cwoa.getLegend( ).getItemType( ) == LegendItemType.CATEGORIES_LITERAL );
lpDataPoint = ps.getLabelPosition( );
lpSeriesTitle = ps.getTitlePosition( );
laSeriesTitle = goFactory.copyOf( ps.getTitle( ) );
laSeriesTitle.getCaption( )
.setValue( pie.getRunTimeContext( )
.externalizedMessage( String.valueOf( ps.getSeriesIdentifier( ) ) ) ); // TBD:
laSeriesTitle.getCaption( )
.getFont( )
.setAlignment( pie.switchTextAlignment( laSeriesTitle.getCaption( )
.getFont( )
.getAlignment( ) ) );
// call script BEFORE_DRAW_SERIES_TITLE
final AbstractScriptHandler sh = pie.getRunTimeContext( ).getScriptHandler( );
ScriptHandler.callFunction( sh,
ScriptHandler.BEFORE_DRAW_SERIES_TITLE,
ps,
laSeriesTitle,
pie.getRunTimeContext( ).getScriptContext( ) );
pie.getRunTimeContext( )
.notifyStructureChange( IStructureDefinitionListener.BEFORE_DRAW_SERIES_TITLE,
laSeriesTitle );
// APPLY
// FORMAT
// SPECIFIER
lls = ps.getLeaderLineStyle( );
bMinSliceDefined = cwoa.isSetMinSlice( );
dMinSlice = cwoa.getMinSlice( );
bPercentageMinSlice = cwoa.isMinSlicePercent( );
double dTotal = 0;
orginalSliceCount = da.length;
for ( int i = 0; i < da.length; i++ )
{
if ( da[i] < 0 )
{
dTotal -= da[i]; // use negative values as absolute
}
else if ( !Double.isNaN( da[i] ) )
{
dTotal += da[i];
}
}
if ( bMinSliceDefined )
{
if ( bPercentageMinSlice )
{
dAbsoluteMinSlice = dMinSlice * dTotal / 100d;
}
else
{
dAbsoluteMinSlice = dMinSlice;
}
double residualPos = 0;
double residualNeg = 0;
DataPointHints dphPos = null;
DataPointHints dphNeg = null;
for ( int i = 0; i < da.length; i++ )
{
// filter null values.
if ( Double.isNaN( da[i] ) )
{
continue;
}
if ( Math.abs( da[i] ) >= Math.abs( dAbsoluteMinSlice ) )
{
pieSliceList.add( new PieSlice( da[i], dpha[i], i ) );
}
else
{
if ( da[i] >= 0 )
{
residualPos += da[i];
if ( dphPos == null )
{
dphPos = dpha[i].getVirtualCopy( );
}
else
{
dphPos.accumulate( dpha[i].getBaseValue( ),
dpha[i].getOrthogonalValue( ),
dpha[i].getSeriesValue( ),
dpha[i].getPercentileOrthogonalValue( ) );
}
}
else
{
residualNeg += da[i];
if ( dphNeg == null )
{
dphNeg = dpha[i].getVirtualCopy( );
}
else
{
dphNeg.accumulate( dpha[i].getBaseValue( ),
dpha[i].getOrthogonalValue( ),
dpha[i].getSeriesValue( ),
dpha[i].getPercentileOrthogonalValue( ) );
}
}
}
}
String extSliceLabel = pie.getRunTimeContext( )
.externalizedMessage( cwoa.getMinSliceLabel( ) );
if ( dphPos != null )
{
dphPos.setBaseValue( extSliceLabel );
dphPos.setIndex( orginalSliceCount );
// neg and pos "other" slice share the same palette color
pieSliceList.add( new PieSlice( residualPos,
dphPos,
orginalSliceCount ) );
bMinSliceApplied = true;
}
if ( dphNeg != null )
{
dphNeg.setBaseValue( extSliceLabel );
dphNeg.setIndex( orginalSliceCount );
pieSliceList.add( new PieSlice( residualNeg,
dphNeg,
orginalSliceCount ) );
bMinSliceApplied = true;
}
}
else
{
for ( int i = 0; i < da.length; i++ )
{
// filter null values.
if ( Double.isNaN( da[i] ) )
{
continue;
}
pieSliceList.add( new PieSlice( da[i], dpha[i], i ) );
}
}
double startAngle = rotation;
double originalStartAngle = rotation;
if ( dTotal == 0 )
{
dTotal = 1;
}
if ( ps.isClockwise( ) )
{
Collections.reverse( pieSliceList );
}
PieSlice slice = null;
double totalAngle = 0d;
for ( Iterator iter = pieSliceList.iterator( ); iter.hasNext( ); )
{
slice = (PieSlice) iter.next( );
double length = ( Math.abs( slice.getPrimitiveValue( ) ) / dTotal ) * 360d;
double percentage = ( slice.getPrimitiveValue( ) / dTotal ) * 100d;
slice.setStartAngle( startAngle );
slice.setOriginalStartAngle( originalStartAngle );
slice.setSliceLength( length );
slice.setPercentage( percentage );
startAngle += length + MIN_DOUBLE;
originalStartAngle += length;
startAngle = wrapAngle( startAngle );
originalStartAngle = wrapAngle( originalStartAngle );
totalAngle += length;
}
// complement the last slice with residual angle
// TODO What is this for?
if ( totalAngle > 0 && 360 - totalAngle > 0.001 ) // handle precision
// loss during
// computations
{
slice.setSliceLength( 360 - slice.getStartAngle( ) );
}
initExploded( );
}
private double wrapAngle( double angle )
{
return angle > 360 ? angle - 360 : angle;
}
/**
*
* @param idr
* @throws ChartException
*/
private final void renderDataPoints( IDeviceRenderer idr )
throws ChartException
{
final AbstractScriptHandler sh = pie.getRunTimeContext( ).getScriptHandler( );
int iTextRenderType = TextRenderEvent.RENDER_TEXT_IN_BLOCK;
if ( lpDataPoint.getValue( ) == Position.OUTSIDE )
{
// RENDER SHADOWS (IF ANY) FIRST
for ( PieSlice slice : pieSliceList )
{
if ( slice.getLabel( ).getShadowColor( ) != null )
{
slice.renderLabel( idr,
TextRenderEvent.RENDER_SHADOW_AT_LOCATION );
}
}
iTextRenderType = TextRenderEvent.RENDER_TEXT_AT_LOCATION;
}
// RENDER ACTUAL TEXT CAPTIONS ON DATA POINTS
for ( PieSlice slice : pieSliceList )
{
if ( slice.getLabel( ).isVisible( ) )
{
slice.renderLabel( idr, iTextRenderType );
}
ScriptHandler.callFunction( sh,
ScriptHandler.AFTER_DRAW_DATA_POINT_LABEL,
slice.getDataPointHints( ),
slice.getLabel( ),
pie.getRunTimeContext( ).getScriptContext( ) );
pie.getRunTimeContext( )
.notifyStructureChange( IStructureDefinitionListener.AFTER_DRAW_DATA_POINT_LABEL,
slice.getLabel( ) );
}
}
/**
*
* @param bo
*/
/**
*
* @param bo
*/
private final void computeLabelBounds( Bounds bo, boolean isOutside )
throws ChartException
{
// compute additional bottom tick size due to series thickness.
for ( PieSlice slice : pieSliceList )
{
slice.setBounds( bo );
if ( isOutside )
{
slice.computeLabelBoundOutside( lls, dLeaderLength, null );
}
else
{
slice.computeLabelBoundInside( );
}
}
}
/**
*
* LabelOverlapResover
*/
private static class LabelOverlapResover
{
// min distance (x) from label to pie
private static final double DMINDIST = 5;
// min space between labels
private static final double HSPACE = 3;
private static final double VSPACE = 3;
private final LeaderLineStyle lls;
private double dLeadLineLen = 0; // length of the lead line
private final List<PieSlice> src_sliceList;
private final double dLeftEdge, dRightEdge, dTopEdge, dBottomEdge;
private int idRightFirst, idLeftFirst, idRightLast, idLeftLast;
public LabelOverlapResover( LeaderLineStyle lls, List<PieSlice> sliceList, Bounds bo, double dLeaderLength )
{
this.dLeftEdge = bo.getLeft( );
this.dRightEdge = bo.getLeft( ) + bo.getWidth( );
this.dTopEdge = bo.getTop( );
this.dBottomEdge = bo.getTop( ) + bo.getHeight( );
this.src_sliceList = sliceList;
this.lls = lls;
if (lls == LeaderLineStyle.FIXED_LENGTH_LITERAL)
{
this.dLeadLineLen = dLeaderLength;
}
}
private void seekForIndexes( )
{
int len = src_sliceList.size( );
if ( len == 0 )
{
return;
}
else if ( len == 1 )
{
if (isLeftSideSlice( src_sliceList.get( 0 ) ))
{
this.idLeftFirst = 0;
this.idLeftLast = 0;
this.idRightLast = -1;
}
else
{
this.idRightFirst = 0;
this.idLeftLast = -1;
}
// this.idLeftLast
// this.idLeftLast
return;
}
boolean bCurrentIsLeft = isLeftSideSlice( src_sliceList.get( 0 ) );
boolean bLastFound = false;
boolean bFirstFound = false;
for ( int i = 1; i < len; i++ )
{
if ( bCurrentIsLeft )
{
if ( !isLeftSideSlice( src_sliceList.get( i ) ) )
{
this.idLeftLast = i - 1;
this.idRightLast = i;
bCurrentIsLeft = false;
bLastFound = true;
}
}
else
{
if ( isLeftSideSlice( src_sliceList.get( i ) ) )
{
this.idRightFirst = i - 1;
this.idLeftFirst = i;
bCurrentIsLeft = true;
bFirstFound = true;
}
}
}
if (!bFirstFound)
{
this.idLeftFirst = 0;
this.idRightFirst = len - 1;
}
if (!bLastFound)
{
idRightLast = 0;
idLeftLast = len - 1;
}
}
private void processLeftSideLoop( LabelGroupList lList, int id0, int id1 )
{
for (int i = id0; i <= id1; i++ )
{
PieSlice slice = src_sliceList.get( i );
if (!lList.isFull)
{
SliceLabel sLabel = new SliceLabel( slice, false );
lList.addSliceLabel( sLabel, false );
}
else
{
break;
}
}
}
private void processLeftSide( int len )
{
LabelGroupList lList = new LabelGroupList(false);
if ( idLeftLast < 0 )
{
return;
}
if (idLeftLast >= idLeftFirst)
{
processLeftSideLoop( lList, idLeftFirst, idLeftLast );
}
else
{
processLeftSideLoop( lList, idLeftFirst, len - 1 );
processLeftSideLoop( lList, 0, idLeftLast );
}
//
LabelGroup lg = lList.head.lgNext;
for (; !lg.isTail( ); lg = lg.lgNext)
{
lg.updateSlices();
}
}
private void processRightSideLoop( LabelGroupList rList, int id0, int id1 )
{
for (int i = id0; i >= id1; i-- )
{
PieSlice slice = src_sliceList.get( i );
if (!rList.isFull)
{
SliceLabel sLabel = new SliceLabel( slice, true );
rList.addSliceLabel( sLabel, true );
}
else
{
break;
}
}
}
private void processRightSide( int len )
{
LabelGroupList rList = new LabelGroupList(true);
if ( idRightLast < 0 )
{
return;
}
if (idRightLast <= idRightFirst)
{
processRightSideLoop( rList, idRightFirst, idRightLast );
}
else
{
processRightSideLoop( rList, idRightFirst, 0 );
processRightSideLoop( rList, len - 1, idRightLast );
}
//
LabelGroup lg = rList.head.lgNext;
for (; !lg.isTail( ); lg = lg.lgNext)
{
lg.updateSlices();
}
}
public void resolve( )
{
int len = src_sliceList.size( );
if ( len > 0 )
{
// search the start and end index
seekForIndexes( );
// process the slices on the left side
processLeftSide( len );
// process the slices on the right side
processRightSide( len );
}
}
private static boolean isLeftSideSlice( PieSlice slice )
{
double angle = slice.getOriginalMidAngle( ) % 360;
return ( angle >= 90 && angle < 270 );
}
/**
* a vertical list of label groups, from top to bottom
* LabelGroupList
*/
private class LabelGroupList
{
private boolean isFull = false;
private LabelGroup head;
private LabelGroup tail;
LabelGroupList( boolean bRight )
{
if (bRight)
{
head = new RightLabelGroup( 1 );
tail = new RightLabelGroup( 2 );
}
else
{
head = new LeftLabelGroup( 1 );
tail = new LeftLabelGroup( 2 );
}
head.lgNext = tail;
tail.lgLast = head;
}
private void append_simply( LabelGroup lg )
{
tail.lgLast.lgNext = lg;
lg.lgLast = tail.lgLast;
lg.lgNext = tail;
tail.lgLast = lg;
}
private boolean limitLgTop( LabelGroup lg )
{
double minTop = lg.computeMinTop( );
double maxTop = lg.computeMaxTop( );
if ( minTop > maxTop )
{
return false;
}
else
{
lg.top = Math.max( lg.top, lg.computeMinTop( ) );
lg.top = Math.min( lg.top, lg.computeMaxTop( ) );
return true;
}
}
/**
* add a slice label to the bottom of the list
* @param sLabel
* @param bRight
* @return
*/
public boolean addSliceLabel( SliceLabel sLabel, boolean bRight )
{
// create a label group with the label
LabelGroup lg = createLabelGroup(sLabel, bRight);
if ( tail.lgLast == head )
{
// the first
append_simply( lg );
if ( !limitLgTop( lg ) )
{
return false;
}
lg.xStart = lg.getXStartClosestToPie( );
return true;
}
else
{
if ( !limitLgTop( lg ) )
{
return false;
}
limitLgTop( lg );
lg.xStart = lg.getXStartClosestToPie( );
double last_bottom = tail.lgLast.top
+ tail.lgLast.height + VSPACE;
double dy = last_bottom - lg.top;
if ( dy > 0 )
{
double lg_top_old = lg.top;
lg.top = last_bottom;
append_simply( lg );
double dMaxTop = lg.computeMaxTop( );
if (lg.top <= dMaxTop)
{
return true;
}
if (tail.lgLast.pushUp( lg.top - dMaxTop ) )
{
return true;
}
else
{
tail.lgLast.delete( );
lg.top = lg_top_old;
this.isFull = true;
return false;
}
}
else
{
// no overlapping
append_simply( lg );
return true;
}
}
}
}
private LabelGroup createLabelGroup( SliceLabel sLabel, boolean bRight )
{
LabelGroup lg = bRight ? new RightLabelGroup(sLabel) : new LeftLabelGroup(sLabel);
return lg;
}
/*
* a row of slice label on the right side of the pie
*/
private class RightLabelGroup extends LabelGroup
{
public RightLabelGroup( SliceLabel sLabel )
{
super(sLabel);
}
public RightLabelGroup( int type )
{
super(type);
}
@Override
protected double getXStartLimit( )
{
return dRightEdge - width - dLeadLineLen - DMINDIST;
}
protected double getPrefferredXStart( )
{
double x1 = getXStartLimit( );
double x0 = getXStartClosestToPie( );
double dx = x1 - x0;
double len = 0;
if (dx > 0)
{
len = Math.abs( dx );
len = Math.min( len, dLeadLineLen + DMINDIST );
}
return x0 + len * Math.signum( dx );
}
@Override
public boolean addSliceLabel( SliceLabel sLabel )
{
double width_new = ( label_list.size( ) == 0 ) ? 0 : width
+ HSPACE;
width_new += sLabel.width;
double height_new = Math.max( height, sLabel.height );
label_list.add( sLabel );
double xStart_new = this.getXStartClosestToPie( );
if ( width_new > dRightEdge - xStart_new || height_new > dBottomEdge - top )
{
label_list.remove( label_list.size( ) - 1 );
return false;
}
this.width = width_new;
this.xStart = xStart_new;
this.height = height_new;
return true;
}
@Override
public double getXStartClosestToPie( )
{
int len = label_list.size( );
double lspace = this.height / ( len + 1 );
double y = top + lspace;
double xStart = label_list.get( 0 ).getXStartClosestToPie( y );
for (int i=1; i<len; i++ )
{
xStart = Math.max( xStart, label_list.get( i ).getXStartClosestToPie( y ) );
}
return xStart;
}
@Override
public void updateSlices()
{
this.top = Math.min( this.top, dBottomEdge - this.height );
int len = label_list.size();
double lspace = this.height / ( len + 1 );
double dYLeadLine = this.top + lspace;
xStart = getPrefferredXStart( );
if (lls == LeaderLineStyle.FIXED_LENGTH_LITERAL)
{
double dLeft = this.xStart;
for ( int i = 0; i < len; i++ )
{
SliceLabel sLabel = label_list.get(i);
// update the label bounding
sLabel.slice.labelBounding.setTop(top);
sLabel.slice.labelBounding.setLeft(dLeft);
// update the lead line
sLabel.slice.loEnd.setX( dLeft );
sLabel.slice.loEnd.setY( dYLeadLine );
sLabel.slice.loStart.setX( this.xStart - dLeadLineLen );
sLabel.slice.loStart.setY( dYLeadLine );
dLeft += sLabel.width + HSPACE;
dYLeadLine += lspace;
}
}
else
{
double dRight = dRightEdge;
for ( int i = 0; i < len; i++ )
{
SliceLabel sLabel = label_list.get(i);
// update the label bounding
sLabel.slice.labelBounding.setTop(top);
sLabel.slice.labelBounding.setLeft(dRight - sLabel.width);
// update the lead line
sLabel.slice.loEnd.setX( dRight - sLabel.width );
sLabel.slice.loEnd.setY( dYLeadLine );
sLabel.slice.loStart.setX( this.xStart - dLeadLineLen );
sLabel.slice.loStart.setY( dYLeadLine );
dRight -= sLabel.width + HSPACE;
dYLeadLine += lspace;
}
}
}
}
/*
* a row of slice label on the left side of the pie
*/
private class LeftLabelGroup extends LabelGroup
{
public LeftLabelGroup( SliceLabel sLabel )
{
super(sLabel);
}
public LeftLabelGroup( int type )
{
super(type);
}
@Override
protected double getXStartLimit( )
{
return dLeftEdge + width + dLeadLineLen + DMINDIST;
}
protected double getPrefferredXStart( )
{
double x1 = getXStartLimit( );
double x0 = getXStartClosestToPie( );
double dx = x1 - x0;
double len = 0;
if ( dx < 0 )
{
len = Math.abs( dx );
len = Math.min( len, dLeadLineLen + DMINDIST );
}
return x0 + len * Math.signum( dx );
}
@Override
public boolean addSliceLabel( SliceLabel sLabel )
{
double height_new = Math.max( this.height, sLabel.height );
double width_new = ( label_list.size( ) == 0 ) ? 0 : width
+ HSPACE;
width_new += sLabel.width;
label_list.add( sLabel );
double xStart_new = this.getXStartClosestToPie( );
if ( width_new > xStart_new - dLeftEdge || sLabel.height > dBottomEdge - this.top )
{
label_list.remove( label_list.size( ) - 1 );
return false;
}
this.width = width_new;
this.xStart = xStart_new;
this.height = height_new;
return true;
}
@Override
public double getXStartClosestToPie( )
{
int len = label_list.size( );
double lspace = this.height / ( len + 1 );
double y = top + lspace;
double xStart = label_list.get( 0 ).getXStartClosestToPie( y );
for (int i=1; i<len; i++ )
{
xStart = Math.min( xStart, label_list.get( i ).getXStartClosestToPie( y ) );
}
return xStart;
}
@Override
public void updateSlices()
{
this.top = Math.min( this.top, dBottomEdge - this.height );
int len = label_list.size();
double lspace = this.height / ( len + 1 );
double dYLeadLine = this.top + lspace;
xStart = getPrefferredXStart( );
if (lls == LeaderLineStyle.FIXED_LENGTH_LITERAL)
{
double dRight = xStart;
for ( int i = 0; i < len; i++ )
{
SliceLabel sLabel = label_list.get( i );
// update the label bounding
sLabel.slice.labelBounding.setTop( top );
sLabel.slice.labelBounding.setLeft( dRight
- sLabel.width );
// update the lead line
sLabel.slice.loEnd.setX( dRight );
sLabel.slice.loEnd.setY( dYLeadLine );
sLabel.slice.loStart.setX( this.xStart + dLeadLineLen );
sLabel.slice.loStart.setY( dYLeadLine );
dRight -= sLabel.width + HSPACE;
dYLeadLine += lspace;
}
}
else
{
//STRETCH_TO_SIDE
double dLeft = dLeftEdge;
for (int i = 0; i<len; i++)
{
SliceLabel sLabel = label_list.get( i );
// update the label bounding
sLabel.slice.labelBounding.setTop( top );
sLabel.slice.labelBounding.setLeft( dLeft );
// update the lead line
sLabel.slice.loEnd.setX( dLeft + sLabel.width );
sLabel.slice.loEnd.setY( dYLeadLine );
sLabel.slice.loStart.setX( this.xStart );
sLabel.slice.loStart.setY( dYLeadLine );
dLeft += sLabel.width + HSPACE;
dYLeadLine += lspace;
}
}
}
}
/*
* a row of slice label
*/
private abstract class LabelGroup
{
private int type = 0; // 0 normal, 1 head, 2 tail
private LabelGroup lgLast = null;
private LabelGroup lgNext = null;
protected List<SliceLabel> label_list = new ArrayList<SliceLabel>();
protected double xStart, width = 0, top, height = 0;
private boolean isFull = false;
public LabelGroup( SliceLabel sLabel )
{
label_list.add( sLabel );
this.top = sLabel.top_init;
this.width = sLabel.width;
this.xStart = sLabel.xStart;
this.height = sLabel.height;
}
public LabelGroup( int type )
{
this.type = type;
}
public boolean isHead()
{
return ( type == 1 );
}
public boolean isTail()
{
return ( type == 2 );
}
private void recomputeHeight()
{
int len = label_list.size( );
height = label_list.get( 0 ).height;
for (int i=1; i<len; i++)
{
height = Math.max( height, label_list.get( i ).height );
}
}
private void removeLastLabel()
{
int len = label_list.size( );
if ( len < 2 )
{
return;
}
SliceLabel sLabel = label_list.get( len - 1 );
label_list.remove( len - 1 );
width -= sLabel.width + HSPACE;
recomputeHeight( );
xStart = getXStartClosestToPie( );
}
public void setTop(double top)
{
this.top = top;
}
public abstract double getXStartClosestToPie( );
public double computeMinTop( )
{
double dMinTop = dTopEdge;
int len = label_list.size();
if ( len > 0 )
{
SliceLabel sLabel = label_list.get( label_list.size( ) - 1 );
if ( !sLabel.bUp )
{
double dx = getXStartLimit( ) - sLabel.slice.xDock;
double dy = 0;
if ( dx != 0 )
{
dy = dx / sLabel.dRampRate;
}
double lspace = height / ( len + 1 );
dMinTop = sLabel.slice.yDock + dy - height + lspace;
}
}
return dMinTop;
}
protected abstract double getXStartLimit( );
public double computeMaxTop( )
{
double dMaxTop = dBottomEdge - height;
int len = label_list.size();
if ( len > 0 )
{
SliceLabel sLabel = label_list.get( 0 );
if ( sLabel.bUp )
{
double dx = getXStartLimit( ) - sLabel.slice.xDock;
double dy = 0;
if ( dx != 0 )
{
dy = dx / sLabel.dRampRate;
}
double lspace = height / ( len + 1 );
dMaxTop = sLabel.slice.yDock + dy - lspace;
}
}
return dMaxTop;
}
private double getBottomLast( )
{
double dBottomLast = dTopEdge;
if (lgLast!=null)
{
dBottomLast = lgLast.top + lgLast.height + VSPACE;
}
return dBottomLast;
}
public boolean pushUp( double dy )
{
if ( this.isFull )
{
return false;
}
double top_new = top - dy;
double dTopMin = this.computeMinTop( );
double bottom_last = getBottomLast( );
if( lgLast == null || top_new >= bottom_last )
{
// head of the list || no overlapping
top = Math.max( top_new, dTopMin );
return ( top_new >= dTopMin );
}
else
{
// top_new < bottom_last
if ( lgLast.pushUp( bottom_last - top_new ) )
{
// push succeeded
top = Math.max( top_new, dTopMin );
return ( top_new >= dTopMin );
}
else
{
// push failed
bottom_last = getBottomLast( ); // lgLast may have changed
if ( top - lgLast.top >= dy)
{
// if possible, merge myself to the last one
if ( lgLast.merge( this ) )
{
return true;
}
else
{
top = Math.max( bottom_last, dTopMin );
return false;
}
}
else
{
if (!lgLast.merge( this ))
{
top = Math.max( bottom_last, dTopMin );
}
return false;
}
}
}
}
public boolean merge( LabelGroup lg )
{
if ( lg.label_list.size( ) > 1 )
{
// only merge lg contains one label
return false;
}
else if ( lg.label_list.size( ) > 0 )
{
SliceLabel sLabel = lg.label_list.get( 0 );
if (!addSliceLabel( sLabel ))
{
this.isFull = true;
return false;
}
else
{
if (this.top < this.computeMinTop( ) || this.top > this.computeMaxTop( ))
{
removeLastLabel( );
this.isFull = true;
return false;
}
}
}
// success
lg.delete( );
return true;
}
// delete myself from the list
public void delete( )
{
if (this.type==0)
{
this.lgLast.lgNext = this.lgNext;
this.lgNext.lgLast = this.lgLast;
}
// if ( this.lgLast != null )
// {
// this.lgLast.lgNext = this.lgNext;
// }
//
// if (this.lgNext!=null)
// {
// this.lgNext.lgLast = this.lgLast;
// }
}
public abstract boolean addSliceLabel( SliceLabel sLabel );
public abstract void updateSlices();
@Override
public String toString( )
{
StringBuffer sBuf = new StringBuffer();
Iterator<SliceLabel> it = label_list.iterator( );
while (it.hasNext( ) )
{
SliceLabel sLabel = it.next( );
sBuf.append( sLabel.slice.categoryIndex );
if (it.hasNext( ))
{
sBuf.append( ", " ); //$NON-NLS-1$
}
}
StringBuilder sb = new StringBuilder( "{ " ); //$NON-NLS-1$
sb.append( sBuf.toString( ) );
sb.append( " }" ); //$NON-NLS-1$
return sb.toString( );
}
}
/*
* wrapping class of slice label
*/
private class SliceLabel
{
private boolean bRight = true;
private boolean bUp = true;
private final PieSlice slice;
private double xStart;
private final double width;
private final double height;
private final double top_init;
private double dRampRate;
public SliceLabel( PieSlice slice, boolean bRight )
{
this.slice = slice;
this.bRight = bRight;
this.width = slice.labelBounding.getWidth( );
this.height = slice.labelBounding.getHeight( );
this.top_init = slice.labelBounding.getTop( );
computeRampRate();
if ( !bRight )
{
xStart = slice.xDock - DMINDIST - dLeadLineLen;
}
else
{
xStart = slice.xDock + DMINDIST + dLeadLineLen;
}
}
public double getXStartClosestToPie( double y )
{
double dy = y - slice.yDock;
double dx = dy * dRampRate;
if ( ( bUp && dy <= 0 ) || ( !bUp && dy >= 0 ) )
{
dx = 0;
}
if ( !bRight )
{
return slice.xDock - DMINDIST - dLeadLineLen + dx;
}
else
{
return slice.xDock + DMINDIST + dLeadLineLen + dx;
}
}
private void computeRampRate( )
{
double angle = slice.getdMidAngle( ) % 360;
dRampRate = Math.tan( Math.toRadians( angle ) );
if (angle>180 && angle < 360)
{
bUp = false;
}
}
}
}
private void resolveOverlap( )
{
new LabelOverlapResover( lls, pieSliceList, boSeriesNoTitle, dLeaderLength ).resolve();
}
/**
*
* @param bo
* @param boAdjusted
* @param ins
* @return
* @throws IllegalArgumentException
*/
private final Insets adjust( Bounds bo, Bounds boAdjusted, Insets ins )
throws ChartException
{
computeLabelBounds( boAdjusted, true );
ins.set( 0, 0, 0, 0 );
double dDelta = 0;
for ( Iterator<PieSlice> iter = pieSliceList.iterator( ); iter.hasNext( ); )
{
PieSlice slice = iter.next( );
BoundingBox bb = slice.getLabelBounding( );
if ( bb.getLeft( ) < bo.getLeft( ) )
{
dDelta = bo.getLeft( ) - bb.getLeft( );
if ( ins.getLeft( ) < dDelta )
{
ins.setLeft( dDelta );
}
}
if ( bb.getTop( ) < bo.getTop( ) )
{
dDelta = bo.getTop( ) - bb.getTop( );
if ( ins.getTop( ) < dDelta )
{
ins.setTop( dDelta );
}
}
if ( bb.getLeft( ) + bb.getWidth( ) > bo.getLeft( ) + bo.getWidth( ) )
{
dDelta = bb.getLeft( )
+ bb.getWidth( )
- bo.getLeft( )
- bo.getWidth( );
if ( ins.getRight( ) < dDelta )
{
ins.setRight( dDelta );
}
}
if ( bb.getTop( ) + bb.getHeight( ) > bo.getTop( ) + bo.getHeight( ) )
{
dDelta = bb.getTop( )
+ bb.getHeight( )
- bo.getTop( )
- bo.getHeight( );
if ( ins.getBottom( ) < dDelta )
{
ins.setBottom( dDelta );
}
}
}
return ins;
}
/**
*
* @param bo
* @throws ChartException
* @throws IllegalArgumentException
*/
final void computeInsets( Bounds bo ) throws ChartException
{
boSetDuringComputation = goFactory.copyOf( bo );
xs = pie.getXServer( );
// ALLOCATE SPACE FOR THE SERIES TITLE
boTitleContainer = null;
if ( laSeriesTitle.isVisible( ) )
{
if ( lpSeriesTitle == null )
{
throw new ChartException( ChartEngineExtensionPlugin.ID,
ChartException.UNDEFINED_VALUE,
"exception.unspecified.visible.series.title", //$NON-NLS-1$
Messages.getResourceBundle( pie.getRunTimeContext( )
.getULocale( ) ) );
}
final BoundingBox bb = cComp.computeBox( xs,
IConstants.BELOW,
laSeriesTitle,
0,
0 );
boTitleContainer = goFactory.createBounds( 0, 0, 0, 0 );
switch ( lpSeriesTitle.getValue( ) )
{
case Position.BELOW :
bo.setHeight( bo.getHeight( ) - bb.getHeight( ) );
boTitleContainer.set( bo.getLeft( ), bo.getTop( )
+ bo.getHeight( ), bo.getWidth( ), bb.getHeight( ) );
break;
case Position.ABOVE :
boTitleContainer.set( bo.getLeft( ),
bo.getTop( ),
bo.getWidth( ),
bb.getHeight( ) );
bo.setTop( bo.getTop( ) + bb.getHeight( ) );
bo.setHeight( bo.getHeight( ) - bb.getHeight( ) );
break;
case Position.LEFT :
bo.setWidth( bo.getWidth( ) - bb.getWidth( ) );
boTitleContainer.set( bo.getLeft( ),
bo.getTop( ),
bb.getWidth( ),
bo.getHeight( ) );
bo.setLeft( bo.getLeft( ) + bb.getWidth( ) );
break;
case Position.RIGHT :
bo.setWidth( bo.getWidth( ) - bb.getWidth( ) );
boTitleContainer.set( bo.getLeft( ) + bo.getWidth( ),
bo.getTop( ),
bb.getWidth( ),
bo.getHeight( ) );
break;
default :
throw new IllegalArgumentException( Messages.getString( "exception.illegal.pie.series.title.position", //$NON-NLS-1$
new Object[]{
lpSeriesTitle
},
pie.getRunTimeContext( ).getULocale( ) ) );
}
}
boSeriesNoTitle = goFactory.copyOf( bo );
ChartWithoutAxes cwa = (ChartWithoutAxes) pie.getModel( );
if ( cwa.isSetCoverage( ) )
{
double rate = cwa.getCoverage( );
double ww = 0.5 * ( 1d - rate ) * bo.getWidth( );
double hh = 0.5 * ( 1d - rate ) * bo.getHeight( );
insCA = goFactory.createInsets( hh, ww, hh, ww );
}
else
{
if ( lpDataPoint == Position.OUTSIDE_LITERAL )
{
if ( ps.getLabel( ).isVisible( ) ) // FILTERED FOR PERFORMANCE
// GAIN
{
// ADJUST THE BOUNDS TO ACCOMODATE THE DATA POINT LABELS +
// LEADER LINES RENDERED OUTSIDE
// Bounds boBeforeAdjusted = BoundsImpl.copyInstance( bo );
Bounds boAdjusted = goFactory.copyOf( bo );
Insets insTrim = goFactory.createInsets( 0, 0, 0, 0 );
do
{
adjust( bo, boAdjusted, insTrim );
boAdjusted.adjust( insTrim );
} while ( !insTrim.areLessThan( 0.5 )
&& boAdjusted.getWidth( ) > 0
&& boAdjusted.getHeight( ) > 0 );
bo = boAdjusted;
}
}
else if ( lpDataPoint == Position.INSIDE_LITERAL )
{
if ( ps.getLabel( ).isVisible( ) ) // FILTERED FOR PERFORMANCE
// GAIN
{
computeLabelBounds( bo, false );
}
}
else
{
throw new IllegalArgumentException( MessageFormat.format( Messages.getResourceBundle( pie.getRunTimeContext( )
.getULocale( ) )
.getString( "exception.invalid.datapoint.position.pie" ), //$NON-NLS-1$
new Object[]{
lpDataPoint
} )
);
}
insCA = goFactory.createInsets( bo.getTop( )
- boSetDuringComputation.getTop( ),
bo.getLeft( ) - boSetDuringComputation.getLeft( ),
boSetDuringComputation.getTop( )
+ boSetDuringComputation.getHeight( )
- ( bo.getTop( ) + bo.getHeight( ) ),
boSetDuringComputation.getLeft( )
+ boSetDuringComputation.getWidth( )
- ( bo.getLeft( ) + bo.getWidth( ) ) );
}
bBoundsAdjustedForInsets = false;
}
/**
*
* @return
*/
final Insets getFittingInsets( )
{
return insCA;
}
/**
*
* @param insCA
*/
final void setFittingInsets( Insets insCA ) throws ChartException
{
this.insCA = insCA;
if ( !bBoundsAdjustedForInsets ) // CHECK IF PREVIOUSLY ADJUSTED
{
bBoundsAdjustedForInsets = true;
boSetDuringComputation.adjust( insCA );
}
if ( lpDataPoint == Position.OUTSIDE_LITERAL )
{
if ( ps.getLabel( ).isVisible( ) ) // FILTERED FOR PERFORMANCE GAIN
{
computeLabelBounds( boSetDuringComputation, true );
}
}
else if ( lpDataPoint == Position.INSIDE_LITERAL )
{
if ( ps.getLabel( ).isVisible( ) ) // FILTERED FOR PERFORMANCE GAIN
{
computeLabelBounds( boSetDuringComputation, false );
}
}
}
/**
*
* @param idr
* @param bo
* @throws ChartException
*/
public final void render( IDeviceRenderer idr, Bounds bo )
throws ChartException
{
bo.adjust( insCA );
xs = idr.getDisplayServer( );
this.idr = idr;
final AbstractScriptHandler sh = pie.getRunTimeContext( ).getScriptHandler( );
double w = bo.getWidth( ) / 2d - dExplosion;
double h = bo.getHeight( ) / 2d - dExplosion - dThickness / 2d;
double xc = bo.getLeft( ) + bo.getWidth( ) / 2d;
double yc = bo.getTop( ) + bo.getHeight( ) / 2d;
if ( ratio > 0 && w > 0 )
{
if ( h / w > ratio )
{
h = w * ratio;
}
else if ( h / w < ratio )
{
w = h / ratio;
}
}
// detect invalid rendering size.
if ( w > 0 && h > 0 )
{
// RENDER THE INSIDE OF THE PIE SLICES AS DEFERRED PLANES (FLAT AND
// CURVED)
if ( dThickness > 0 )
{
for ( Iterator<PieSlice> iter = pieSliceList.iterator( ); iter.hasNext( ); )
{
PieSlice slice = iter.next( );
Fill fPaletteEntry = null;
if ( bPaletteByCategory )
{
fPaletteEntry = getPaletteColor( slice.getCategoryIndex( ) );
}
else
{
fPaletteEntry = getPaletteColor( pie.getSeriesDefinition( )
.getRunTimeSeries( )
.indexOf( ps ) );
}
ScriptHandler.callFunction( sh,
ScriptHandler.BEFORE_DRAW_ELEMENT,
slice.getDataPointHints( ),
fPaletteEntry );
ScriptHandler.callFunction( sh,
ScriptHandler.BEFORE_DRAW_DATA_POINT,
slice.getDataPointHints( ),
fPaletteEntry,
pie.getRunTimeContext( ).getScriptContext( ) );
pie.getRunTimeContext( )
.notifyStructureChange( IStructureDefinitionListener.BEFORE_DRAW_ELEMENT,
slice.getDataPointHints( ) );
pie.getRunTimeContext( )
.notifyStructureChange( IStructureDefinitionListener.BEFORE_DRAW_DATA_POINT,
slice.getDataPointHints( ) );
slice.render( goFactory.createLocation( xc, yc ),
goFactory.createLocation( 0, dThickness ),
SizeImpl.create( w, h ),
fPaletteEntry,
LOWER );
ScriptHandler.callFunction( sh,
ScriptHandler.AFTER_DRAW_ELEMENT,
slice.getDataPointHints( ),
fPaletteEntry );
ScriptHandler.callFunction( sh,
ScriptHandler.AFTER_DRAW_DATA_POINT,
slice.getDataPointHints( ),
fPaletteEntry,
pie.getRunTimeContext( ).getScriptContext( ) );
pie.getRunTimeContext( )
.notifyStructureChange( IStructureDefinitionListener.AFTER_DRAW_ELEMENT,
slice.getDataPointHints( ) );
pie.getRunTimeContext( )
.notifyStructureChange( IStructureDefinitionListener.AFTER_DRAW_DATA_POINT,
slice.getDataPointHints( ) );
}
// SORT AND ACTUALLY RENDER THE PLANES PREVIOUSLY WRITTEN AS
// DEFERRED
sortAndRenderPlanes( );
}
// RENDER THE UPPER SECTORS ON THE PIE SLICES (DON'T CARE ABOUT
// THE ORDER)
for ( Iterator<PieSlice> iter = pieSliceList.iterator( ); iter.hasNext( ); )
{
PieSlice slice = iter.next( );
Fill fPaletteEntry = null;
if ( bPaletteByCategory )
{
fPaletteEntry = getPaletteColor( slice.getCategoryIndex( ) );
}
else
{
fPaletteEntry = getPaletteColor( pie.getSeriesDefinition( )
.getRunTimeSeries( )
.indexOf( ps ) );
}
ScriptHandler.callFunction( sh,
ScriptHandler.BEFORE_DRAW_DATA_POINT,
slice.getDataPointHints( ),
fPaletteEntry,
pie.getRunTimeContext( ).getScriptContext( ) );
pie.getRunTimeContext( )
.notifyStructureChange( IStructureDefinitionListener.BEFORE_DRAW_DATA_POINT,
slice.getDataPointHints( ) );
slice.render( goFactory.createLocation( xc, yc ),
goFactory.createLocation( 0, dThickness ),
SizeImpl.create( w, h ),
fPaletteEntry,
UPPER );
ScriptHandler.callFunction( sh,
ScriptHandler.AFTER_DRAW_DATA_POINT,
slice.getDataPointHints( ),
fPaletteEntry,
pie.getRunTimeContext( ).getScriptContext( ) );
pie.getRunTimeContext( )
.notifyStructureChange( IStructureDefinitionListener.AFTER_DRAW_DATA_POINT,
slice.getDataPointHints( ) );
}
}
// RENDER THE SERIES TITLE NOW
// ScriptHandler.callFunction( sh,
// ScriptHandler.BEFORE_DRAW_SERIES_TITLE,
// ps,
// laSeriesTitle,
// pie.getRunTimeContext( ).getScriptContext( ) );
// pie.getRunTimeContext( )
// .notifyStructureChange( IStructureDefinitionListener.BEFORE_DRAW_SERIES_TITLE,
// laSeriesTitle );
// laDataPoint = LabelImpl.copyInstance( ps.getLabel( ) );
if ( laSeriesTitle.isVisible( ) )
{
final TextRenderEvent tre = ( (EventObjectCache) idr ).getEventObject( WrappedStructureSource.createSeriesTitle( ps,
laSeriesTitle ),
TextRenderEvent.class );
tre.setLabel( laSeriesTitle );
tre.setBlockBounds( boTitleContainer );
tre.setBlockAlignment( null );
tre.setAction( TextRenderEvent.RENDER_TEXT_IN_BLOCK );
idr.drawText( tre );
}
ScriptHandler.callFunction( sh,
ScriptHandler.AFTER_DRAW_SERIES_TITLE,
ps,
laSeriesTitle,
pie.getRunTimeContext( ).getScriptContext( ) );
pie.getRunTimeContext( )
.notifyStructureChange( IStructureDefinitionListener.AFTER_DRAW_SERIES_TITLE,
laSeriesTitle );
// LASTLY, RENDER THE DATA POINTS
if ( ps.getLabel( ).isVisible( ) )
{ // IF NOT VISIBLE, DON'T DO ANYTHING
try
{
if ( ps.getLabel( ).getCaption( ).getFont( ).getRotation( ) == 0 )
{
if ( lpDataPoint == Position.OUTSIDE_LITERAL )
{
resolveOverlap( );
}
}
renderDataPoints( idr );
}
catch ( ChartException rex )
{
logger.log( rex );
// Throw the exception to engine at runtime and engine will
// display the exception to user.
throw rex;
}
}
}
/**
* Add curved planes to a list for deferring to draw them.
*
* @param planesList
* the list is used to receive the planes.
* @param angle
* angle of pie slice, normally it should be the start angle of
* pie slice.
* @param areBentOrTwistedCurve
* @param dX1
* @param dX2
*/
private final void deferCurvedPlane( List list, double angle,
AreaRenderEvent areBentOrTwistedCurve, double dX1, double dX2 )
{
double newAngle = convertAngleForRenderingOrder( angle );
list.add( new CurvedPlane( newAngle, areBentOrTwistedCurve ) );
}
/**
* Defer to draw curved outline.
*
* @param planesList
* the list is used to receive the planes.
* @param angle
* angle of pie slice, normally it should be the start angle of
* pie slice.
* @param areBentOrTwistedCurve
* outline group.
*/
private final void deferCurvedOutline( List list, double angle,
AreaRenderEvent areBentOrTwistedCurve )
{
double newAngle = convertAngleForRenderingOrder( angle );
list.add( new CurvedPlane( newAngle, areBentOrTwistedCurve ) );
}
/**
* Add flat planes to a list for deferring to draw them.
*
* @param planesList
* the list is used to receive the planes.
* @param angle
* angle of pie slice, normally it should be the start angle of
* pie slice.
* @param daXPoints
* @param daYPoints
* @param cd
*/
private final void deferFlatPlane( List planesList, double angle,
double[] daXPoints, double[] daYPoints, Fill cd, DataPointHints dph )
{
double newAngle = convertAngleForRenderingOrder( angle );
planesList.add( new FlatPlane( newAngle, daXPoints, daYPoints, cd, dph ) );
}
/**
* Convert angle of pie slice for getting correct rendering order before
* rendering each pie slice.
*
* @param angle
* angle of pie slice, normally it should be the start angle of
* pie slice.
* @return adjusted angle.
*/
private double convertAngleForRenderingOrder( double angle )
{
double newAngle = angle;
newAngle = wrapAngle( newAngle );
if ( newAngle < 180 )
{
newAngle = Math.abs( newAngle - 90 );
}
else
{
newAngle = ( 90 - Math.abs( newAngle - 270 ) ) + 180;
}
return newAngle;
}
/**
* Sort all planes and draw them.
*
* @throws ChartException
*/
private final void sortAndRenderPlanes( ) throws ChartException
{
// Draw each planes, first draw the back curved planes of view, second
// draw the flat planes, last to draw the front curved planes of view.
renderPlanes( backCurvedPlanes );
backCurvedPlanes.clear( );
renderPlanes( flatPlanes );
flatPlanes.clear( );
renderPlanes( frontCurvedPlanes );
frontCurvedPlanes.clear( );
}
/**
* Render planes.
*
* @param planesList
* the list contains plane objects.
* @throws ChartException
*/
private void renderPlanes( List planesList ) throws ChartException
{
Object[] planes = planesList.toArray( );
Arrays.sort( planes, new Comparator( ) {
/**
*
* @param arg0
* @param arg1
* @return
*/
public int compare( Object arg0, Object arg1 )
{
double angleA = 0d;
double angleB = 0d;
if ( arg0 instanceof FlatPlane )
{
angleA = ( (FlatPlane) arg0 ).getAngle( );
}
else if ( arg0 instanceof CurvedPlane )
{
angleA = ( (CurvedPlane) arg0 ).getAngle( );
}
if ( arg1 instanceof FlatPlane )
{
angleB = ( (FlatPlane) arg1 ).getAngle( );
}
else if ( arg0 instanceof CurvedPlane )
{
angleB = ( (CurvedPlane) arg1 ).getAngle( );
}
return Double.compare( angleA, angleB );
}
} );
for ( int i = 0; i < planes.length; i++ )
{
IDrawable id = (IDrawable) planes[i];
id.draw( );
}
}
private final ColorDefinition getSliceOutline( Fill f )
{
if ( ps.getSliceOutline( ) == null )
{
if ( f instanceof ColorDefinition )
{
return goFactory.darker( (ColorDefinition) f );
}
else
{
return goFactory.TRANSPARENT( );
}
}
return goFactory.copyOf( ps.getSliceOutline( ) );
}
private void initExploded( )
{
if ( sExplosionExpression == null )
{
return;
}
for ( PieSlice slice : pieSliceList )
{
try
{
pie.getRunTimeContext( )
.getScriptHandler( )
.registerVariable( ScriptHandler.BASE_VALUE,
slice.getDataPointHints( ).getBaseValue( ) );
pie.getRunTimeContext( )
.getScriptHandler( )
.registerVariable( ScriptHandler.ORTHOGONAL_VALUE,
slice.getDataPointHints( ).getOrthogonalValue( ) );
pie.getRunTimeContext( )
.getScriptHandler( )
.registerVariable( ScriptHandler.SERIES_VALUE,
slice.getDataPointHints( ).getSeriesValue( ) );
Object obj = pie.getRunTimeContext( )
.getScriptHandler( )
.evaluate( sExplosionExpression );
if ( obj instanceof Boolean )
{
slice.setExploded( ( (Boolean) obj ).booleanValue( ) );
}
pie.getRunTimeContext( )
.getScriptHandler( )
.unregisterVariable( ScriptHandler.BASE_VALUE );
pie.getRunTimeContext( )
.getScriptHandler( )
.unregisterVariable( ScriptHandler.ORTHOGONAL_VALUE );
pie.getRunTimeContext( )
.getScriptHandler( )
.unregisterVariable( ScriptHandler.SERIES_VALUE );
}
catch ( ChartException e )
{
logger.log( e );
}
}
}
// HANDLE ELEVATION COMPUTATION FOR SOLID
// COLORS,
// GRADIENTS AND IMAGES
protected Gradient getDepthGradient( Fill cd )
{
if ( cd instanceof Gradient )
{
return goFactory.createGradient( goFactory.darker( ( (Gradient) cd ).getStartColor( ) ),
goFactory.darker( ( (Gradient) cd ).getEndColor( ) ),
( (Gradient) cd ).getDirection( ),
( (Gradient) cd ).isCyclic( ) );
}
else
return goFactory.createGradient( ( cd instanceof ColorDefinition ) ? goFactory.darker( (ColorDefinition) cd )
: goFactory.GREY( ),
goFactory.BLACK( ),
0,
true );
}
/**
* @param cd
* @param startAngle
* @param endAngle
* @return
*/
protected Gradient getDepthGradient( Fill cd, double startAngle,
double endAngle )
{
if ( cd instanceof Gradient )
{
return goFactory.createGradient( goFactory.darker( ( (Gradient) cd ).getStartColor( ) ),
goFactory.darker( ( (Gradient) cd ).getEndColor( ) ),
( (Gradient) cd ).getDirection( ),
( (Gradient) cd ).isCyclic( ) );
}
else
{
ColorDefinition standCD = ( cd instanceof ColorDefinition ) ? goFactory.darker( (ColorDefinition) cd )
: goFactory.GREY( );
float[] hsbvals = Color.RGBtoHSB( standCD.getRed( ),
standCD.getGreen( ),
standCD.getBlue( ),
null );
float[] startHSB = new float[3];
startHSB[0] = hsbvals[0];
startHSB[1] = hsbvals[1];
startHSB[2] = hsbvals[2];
float[] endHSB = new float[3];
endHSB[0] = hsbvals[0];
endHSB[1] = hsbvals[1];
endHSB[2] = hsbvals[2];
float brightAlpha = 1f / 180;
if ( startAngle < 180 )
{
startHSB[2] = (float) ( startAngle * brightAlpha );
}
else
{
startHSB[2] = (float) ( 1 - ( startAngle - 180 ) * brightAlpha );
}
if ( endAngle < 180 )
{
endHSB[2] = (float) ( endAngle * brightAlpha );
}
else
{
endHSB[2] = (float) ( 1 - ( endAngle - 180 ) * brightAlpha );
}
Color startColor = new Color( Color.HSBtoRGB( startHSB[0],
startHSB[1],
startHSB[2] ) );
Color endColor = new Color( Color.HSBtoRGB( endHSB[0],
endHSB[1],
endHSB[2] ) );
ColorDefinition startCD = goFactory.copyOf( standCD );
startCD.set( startColor.getRed( ),
startColor.getGreen( ),
startColor.getBlue( ) );
ColorDefinition endCD = goFactory.copyOf( standCD );
endCD.set( endColor.getRed( ),
endColor.getGreen( ),
endColor.getBlue( ) );
if ( endAngle <= 180 )
{
return goFactory.createGradient( endCD, startCD, 0, true );
}
else
{
return goFactory.createGradient( startCD, endCD, 0, true );
}
}
}
/**
* Used for deferred rendering
*
* @param topBound
* The top round bounds of pie slice.
* @param bottomBound
* The bottom round bounds of pie slice.
* @param dStartAngle
* The start agnle of pie slice.
* @param dAngleExtent
* The extent angle of pie slice.
* @param lreStartB2T
* The bottom to top line rendering event in start location of
* pie slice.
* @param lreEndB2T
* The top to bottom line rendering event in end location of pie
* slice.
* @param cd
* @param dph
* data point hints.
* @param loC
* center point of bottom cycle.
* @param loCTop
* center point of top cycle.
* @param sz
* width and height of cycle.
*/
private final void registerCurvedSurface( Bounds topBound,
Bounds bottomBound, double dStartAngle, double dAngleExtent,
LineRenderEvent lreStartB2T, LineRenderEvent lreEndB2T, Fill cd,
DataPointHints dph, Location loC, Location loCTop, Size sz )
{
// 1. Get all splited angles.
double[] anglePoints = new double[4];
double endAngle = dStartAngle + dAngleExtent;
int i = 0;
anglePoints[i++] = dStartAngle;
if ( endAngle > 180 && dStartAngle < 180 )
{
anglePoints[i++] = 180;
}
if ( endAngle > 360 && dStartAngle < 360 )
{
anglePoints[i++] = 360;
if ( endAngle > 540 )
{
anglePoints[i++] = 540;
}
}
anglePoints[i] = endAngle;
// 2. Do Render.
if ( i == 1 ) // The simple case, only has one curved plane.
{
// CURVED PLANE 1
final ArcRenderEvent arcRE1 = new ArcRenderEvent( WrappedStructureSource.createSeriesDataPoint( ps,
dph ) );
final ArcRenderEvent arcRE2 = new ArcRenderEvent( WrappedStructureSource.createSeriesDataPoint( ps,
dph ) );
arcRE1.setBounds( topBound );
arcRE1.setStartAngle( dStartAngle );
arcRE1.setAngleExtent( dAngleExtent );
arcRE1.setStyle( ArcRenderEvent.OPEN );
arcRE2.setBounds( bottomBound );
arcRE2.setStartAngle( dStartAngle + dAngleExtent );
arcRE2.setAngleExtent( -dAngleExtent );
arcRE2.setStyle( ArcRenderEvent.OPEN );
AreaRenderEvent areRE = new AreaRenderEvent( WrappedStructureSource.createSeriesDataPoint( ps,
dph ) );
areRE.add( lreStartB2T );
areRE.add( arcRE1 );
areRE.add( lreEndB2T );
areRE.add( arcRE2 );
areRE.setOutline( goFactory.createLineAttributes( getSliceOutline( cd ),
LineStyle.SOLID_LITERAL,
1 ) );
areRE.setBackground( getDepthGradient( cd, dStartAngle, dStartAngle
+ dAngleExtent ) );
deferCurvedPlane( selectPlanesList( dStartAngle ),
dStartAngle,
areRE,
lreStartB2T.getStart( ).getX( ),
lreEndB2T.getStart( ).getX( ) );
}
else
// The multiple case, should be more curved plane.
{
Stack<PrimitiveRenderEvent> lineStack = new Stack<PrimitiveRenderEvent>( );
AreaRenderEvent areLine = new AreaRenderEvent( WrappedStructureSource.createSeriesDataPoint( ps,
dph ) );
areLine.setOutline( goFactory.createLineAttributes( getSliceOutline( cd ),
LineStyle.SOLID_LITERAL,
1 ) );
areLine.setBackground( null );
for ( int j = 0; j < i; j++ )
{
double startAngle = anglePoints[j] + MIN_DOUBLE;
double angleExtent = anglePoints[j + 1] - anglePoints[j];
startAngle = wrapAngle( startAngle );
Object[] edgeLines = getEdgeLines( startAngle,
angleExtent,
loC,
loCTop,
sz,
dph );
// CURVED PLANE 1
final ArcRenderEvent arcRE1 = new ArcRenderEvent( WrappedStructureSource.createSeriesDataPoint( ps,
dph ) );
final ArcRenderEvent arcRE2 = new ArcRenderEvent( WrappedStructureSource.createSeriesDataPoint( ps,
dph ) );
arcRE1.setBounds( topBound );
arcRE1.setStartAngle( startAngle );
arcRE1.setAngleExtent( angleExtent );
arcRE1.setStyle( ArcRenderEvent.OPEN );
arcRE2.setBounds( bottomBound );
arcRE2.setStartAngle( wrapAngle( anglePoints[j + 1] ) );
arcRE2.setAngleExtent( -angleExtent );
arcRE2.setStyle( ArcRenderEvent.OPEN );
// Fill pie slice.
AreaRenderEvent are = new AreaRenderEvent( WrappedStructureSource.createSeriesDataPoint( ps,
dph ) );
are.add( (LineRenderEvent) edgeLines[0] );
are.add( arcRE1 );
are.add( (LineRenderEvent) edgeLines[1] );
are.add( arcRE2 );
are.setOutline( null );
are.setBackground( getDepthGradient( cd,
wrapAngle( anglePoints[j] ),
wrapAngle( anglePoints[j + 1] ) ) );
deferCurvedPlane( selectPlanesList( startAngle ),
startAngle,
are,
( (LineRenderEvent) edgeLines[0] ).getStart( ).getX( ),
( (LineRenderEvent) edgeLines[1] ).getStart( ).getX( ) );
// Arrange pie slice outline.
if ( j == 0 ) // It is first sector of pie slice.
{
areLine.add( (LineRenderEvent) edgeLines[0] );
areLine.add( arcRE1 );
lineStack.push( arcRE2 );
}
else if ( j == ( i - 1 ) ) // It is last sector of pie slice.
{
areLine.add( arcRE1 );
areLine.add( (LineRenderEvent) edgeLines[1] );
areLine.add( arcRE2 );
}
else
{
areLine.add( arcRE1 );
lineStack.push( arcRE2 );
}
}
// Arrange pie slice outline.
while ( !lineStack.empty( ) )
{
areLine.add( lineStack.pop( ) );
}
double mid = dStartAngle + dAngleExtent / 2;
mid = wrapAngle( mid );
// Draw pie slice outline.
deferCurvedOutline( selectPlanesList( mid ), dStartAngle, areLine );
}
}
/**
* Select a planes list by specified start angle of pie slice, the selected
* list will curved rendering sides.
* <p>
* Saving curved rendering sides to different list is to ensure the correct
* rendering order.
*
* @param startAngle
* the start angle of pie slice.
* @return the list contains curved rendering sides.
*/
private List selectPlanesList( double startAngle )
{
if ( startAngle < 180 )
{
return backCurvedPlanes;
}
return frontCurvedPlanes;
}
/**
* @param startAngle
* @param extentAngle
* @param loC
* @param loCTop
* @param sz
* @param dph
* @return
*/
private final Object[] getEdgeLines( double startAngle, double extentAngle,
Location loC, Location loCTop, Size sz, DataPointHints dph )
{
double dAngleInRadians = Math.toRadians( startAngle );
double dSineThetaStart = Math.sin( dAngleInRadians );
double dCosThetaStart = Math.cos( dAngleInRadians );
dAngleInRadians = Math.toRadians( startAngle + extentAngle );
double dSineThetaEnd = Math.sin( dAngleInRadians );
double dCosThetaEnd = Math.cos( dAngleInRadians );
double xE = ( sz.getWidth( ) * dCosThetaEnd );
double yE = ( sz.getHeight( ) * dSineThetaEnd );
double xS = ( sz.getWidth( ) * dCosThetaStart );
double yS = ( sz.getHeight( ) * dSineThetaStart );
final LineRenderEvent lreStartB2T = new LineRenderEvent( WrappedStructureSource.createSeriesDataPoint( ps,
dph ) );
lreStartB2T.setStart( goFactory.createLocation( loC.getX( ) + xS,
loC.getY( )
- yS ) );
lreStartB2T.setEnd( goFactory.createLocation( loCTop.getX( ) + xS,
loCTop.getY( ) - yS ) );
final LineRenderEvent lreEndT2B = new LineRenderEvent( WrappedStructureSource.createSeriesDataPoint( ps,
dph ) );
lreEndT2B.setStart( goFactory.createLocation( loCTop.getX( ) + xE,
loCTop.getY( ) - yE ) );
lreEndT2B.setEnd( goFactory.createLocation( loC.getX( ) + xE,
loC.getY( )
- yE ) );
return new Object[]{
lreStartB2T, lreEndT2B
};
}
/**
*
* @param iIndex
* @return
*/
private final Fill getPaletteColor( int iIndex )
{
final Fill fiClone = FillUtil.getPaletteFill( pa.getEntries( ), iIndex );
pie.updateTranslucency( fiClone, ps );
return fiClone;
}
/**
* CurvedPlane
*/
private final class CurvedPlane implements Comparable, IDrawable
{
private final AreaRenderEvent _are;
private final Bounds _bo;
private final double _angle;
/**
* Constructor of the class.
*
*
*/
CurvedPlane( double angle, AreaRenderEvent are )
{
_are = are;
_bo = are.getBounds( );
_angle = angle;
}
public final Bounds getBounds( )
{
return _bo;
}
/*
* (non-Javadoc)
*
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
public final int compareTo( Object o ) // Z-ORDER TEST
{
final CurvedPlane cp1 = this;
if ( o instanceof CurvedPlane )
{
final CurvedPlane cp2 = (CurvedPlane) o;
final double dMinY1 = cp1.getMinY( );
final double dMinY2 = cp2.getMinY( );
double dDiff = dMinY1 - dMinY2;
if ( !ChartUtil.mathEqual( dDiff, 0 ) )
{
return ( dDiff < 0 ) ? LESS : ( dDiff > 0 ) ? MORE : EQUAL;
}
else
{
final double dMaxY1 = cp1.getMaxY( );
final double dMaxY2 = cp2.getMaxY( );
dDiff = dMaxY1 - dMaxY2;
if ( !ChartUtil.mathEqual( dDiff, 0 ) )
{
return ( dDiff < 0 ) ? LESS : MORE;
}
else
{
final double dMinX1 = cp1.getMinX( );
final double dMinX2 = cp2.getMinX( );
dDiff = dMinX1 - dMinX2;
if ( !ChartUtil.mathEqual( dDiff, 0 ) )
{
return ( dDiff < 0 ) ? LESS : MORE;
}
else
{
final double dMaxX1 = cp1.getMaxX( );
final double dMaxX2 = cp2.getMaxX( );
dDiff = dMaxX1 - dMaxX2;
if ( !ChartUtil.mathEqual( dDiff, 0 ) )
{
return ( dDiff < 0 ) ? LESS : MORE;
}
else
{
return EQUAL;
}
}
}
}
}
else if ( o instanceof FlatPlane )
{
final FlatPlane pi2 = (FlatPlane) o;
return pi2.compareTo( cp1 ) * -1; // DELEGATE AND INVERT
// RESULT
}
return EQUAL;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.chart.prototype.Pie.IDrawable#draw(java.awt.Graphics2D)
*/
public final void draw( ) throws ChartException
{
idr.fillArea( _are );
idr.drawArea( _are );
/*
* GradientPaint gp = new GradientPaint( (float)dGradientStart2D, 0,
* Color.black, (float)(dGradientStart2D + (dGradientEnd2D -
* dGradientStart2D)/2), 0, _c, true); g2d.setPaint(gp);
* g2d.fill(_sh); g2d.setColor(_c.darker()); g2d.draw(_sh);
*/
}
private final double getMinY( )
{
return _bo.getTop( );
}
private final double getMinX( )
{
return _bo.getLeft( );
}
private final double getMaxX( )
{
return _bo.getLeft( ) + _bo.getWidth( );
}
private final double getMaxY( )
{
return _bo.getTop( ) + _bo.getHeight( );
}
public double getAngle( )
{
return _angle;
}
}
/**
* FlatPlane
*/
private final class FlatPlane implements Comparable, IDrawable
{
private final double[] _daXPoints, _daYPoints;
private final Fill _cd;
private final Bounds _bo;
private final DataPointHints _dph;
private final double _angle;
/**
* Constructor of the class.
*
* @param angle
* the start angle will be used to decide the painting order.
* @param daXPoints
* @param daYPoints
* @param cd
* @param dph
*/
FlatPlane( double angle, double[] daXPoints, double[] daYPoints,
Fill cd, DataPointHints dph )
{
_angle = angle;
_daXPoints = daXPoints;
_daYPoints = daYPoints;
_dph = dph;
// COMPUTE THE BOUNDS
final int n = _daXPoints.length;
double dMinX = 0, dMinY = 0, dMaxX = 0, dMaxY = 0;
for ( int i = 0; i < n; i++ )
{
if ( i == 0 )
{
dMinX = _daXPoints[i];
dMinY = _daYPoints[i];
dMaxX = dMinX;
dMaxY = dMinY;
}
else
{
if ( dMinX > _daXPoints[i] )
{
dMinX = _daXPoints[i];
}
if ( dMinY > _daYPoints[i] )
{
dMinY = _daYPoints[i];
}
if ( dMaxX < _daXPoints[i] )
{
dMaxX = _daXPoints[i];
}
if ( dMaxY < _daYPoints[i] )
{
dMaxY = _daYPoints[i];
}
}
}
_bo = goFactory.createBounds( dMinX, dMinY, dMaxX - dMinX, dMaxY
- dMinY );
_cd = cd;
int nPoints = _daXPoints.length;
int[] iaX = new int[nPoints];
int[] iaY = new int[nPoints];
for ( int i = 0; i < nPoints; i++ )
{
iaX[i] = (int) daXPoints[i];
iaY[i] = (int) daYPoints[i];
}
// _p = new Polygon(iaX, iaY, nPoints);
}
public Bounds getBounds( )
{
return _bo;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.chart.prototype.Pie.IDrawable#draw(java.awt.Graphics2D)
*/
public final void draw( ) throws ChartException
{
PolygonRenderEvent pre = ( (EventObjectCache) idr ).getEventObject( WrappedStructureSource.createSeriesDataPoint( ps,
_dph ),
PolygonRenderEvent.class );
pre.setPoints( toLocationArray( ) );
liaEdges.setColor( getSliceOutline( _cd ) );
pre.setOutline( liaEdges );
pre.setBackground( getDepthGradient( _cd ) );
idr.fillPolygon( pre );
idr.drawPolygon( pre );
}
/*
* (non-Javadoc)
*
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
public final int compareTo( Object o ) // Z-ORDER TEST
{
final FlatPlane pi1 = this;
if ( o instanceof FlatPlane )
{
final FlatPlane pi2 = (FlatPlane) o;
final double dMinY1 = pi1.getMinY( );
final double dMinY2 = pi2.getMinY( );
double dDiff = dMinY1 - dMinY2;
if ( !ChartUtil.mathEqual( dDiff, 0 ) )
{
return ( dDiff < 0 ) ? LESS : ( dDiff > 0 ) ? MORE : EQUAL;
}
else
{
final double dMaxY1 = pi1.getMaxY( );
final double dMaxY2 = pi2.getMaxY( );
dDiff = dMaxY1 - dMaxY2;
if ( !ChartUtil.mathEqual( dDiff, 0 ) )
{
return ( dDiff < 0 ) ? LESS : MORE;
}
else
{
final double dMinX1 = pi1.getMinX( );
final double dMinX2 = pi2.getMinX( );
dDiff = dMinX1 - dMinX2;
if ( !ChartUtil.mathEqual( dDiff, 0 ) )
{
return ( dDiff < 0 ) ? LESS : MORE;
}
else
{
final double dMaxX1 = pi1.getMaxX( );
final double dMaxX2 = pi2.getMaxX( );
dDiff = dMaxX1 - dMaxX2;
if ( !ChartUtil.mathEqual( dDiff, 0 ) )
{
return ( dDiff < 0 ) ? LESS : MORE;
}
else
{
return EQUAL;
}
}
}
}
}
else if ( o instanceof CurvedPlane )
{
final CurvedPlane pi2 = (CurvedPlane) o;
final double dMinY1 = pi1.getMinY( );
final double dMinY2 = pi2.getMinY( );
double dDiff = dMinY1 - dMinY2;
if ( !ChartUtil.mathEqual( dDiff, 0 ) )
{
return ( dDiff < 0 ) ? LESS : MORE;
}
else
{
final double dMaxY1 = pi1.getMaxY( );
final double dMaxY2 = pi2.getMaxY( );
dDiff = dMaxY1 - dMaxY2;
if ( !ChartUtil.mathEqual( dDiff, 0 ) )
{
return ( dDiff < 0 ) ? LESS : MORE;
}
else
{
final double dMinX1 = pi1.getMinX( );
final double dMinX2 = pi2.getMinX( );
dDiff = dMinX1 - dMinX2;
if ( !ChartUtil.mathEqual( dDiff, 0 ) )
{
return ( dDiff < 0 ) ? LESS : MORE;
}
else
{
final double dMaxX1 = pi1.getMaxX( );
final double dMaxX2 = pi2.getMaxX( );
dDiff = dMaxX1 - dMaxX2;
if ( !ChartUtil.mathEqual( dDiff, 0 ) )
{
return ( dDiff < 0 ) ? LESS : MORE;
}
else
{
return EQUAL;
}
}
}
}
}
return EQUAL;
}
private final double getMinY( )
{
return _bo.getTop( );
}
private final double getMinX( )
{
return _bo.getLeft( );
}
private final double getMaxX( )
{
return _bo.getLeft( ) + _bo.getWidth( );
}
private final double getMaxY( )
{
return _bo.getTop( ) + _bo.getHeight( );
}
private final Location[] toLocationArray( )
{
final int n = _daXPoints.length;
Location[] loa = new Location[n];
for ( int i = 0; i < n; i++ )
{
loa[i] = goFactory.createLocation( _daXPoints[i], _daYPoints[i] );
}
return loa;
}
public double getAngle( )
{
return _angle;
}
}
/**
* IDrawable
*/
private interface IDrawable
{
void draw( ) throws ChartException;
Bounds getBounds( );
}
private static class OutsideLabelBoundCache
{
public int iLL = 0;
public BoundingBox bb = null;
public void reset( )
{
iLL = 0;
bb = null;
}
}
public class PieSlice implements Cloneable
{
private boolean isExploded = true;
private double originalStartAngle;
private double startAngle;
private double sliceLength;
private double slicePecentage;
private int categoryIndex;
private DataPointHints dataPointHints;
private double primitiveValue;
private int quadrant = -1;
private Location loPie;
private Location loStart;
private Location loEnd;
private BoundingBox labelBounding = null;
private Label la;
private Bounds bounds = null;
private double w, h, xc, yc;
private double xDock, yDock;
PieSlice( double primitiveValue, DataPointHints dataPointHints,
int categroyIndex ) throws ChartException
{
this.primitiveValue = primitiveValue;
this.dataPointHints = dataPointHints;
this.categoryIndex = categroyIndex;
createSliceLabel();
}
public void createSliceLabel( ) throws ChartException
{
if ( this.la != null )
{
return; // can only create once
}
this.la = goFactory.copyOf( ps.getLabel( ) );
la.getCaption( ).setValue( getDisplayValue( ) );
final AbstractScriptHandler sh = pie.getRunTimeContext( ).getScriptHandler( );
ScriptHandler.callFunction( sh,
ScriptHandler.BEFORE_DRAW_DATA_POINT_LABEL,
getDataPointHints( ),
la,
pie.getRunTimeContext( ).getScriptContext( ) );
pie.getRunTimeContext( )
.notifyStructureChange( IStructureDefinitionListener.BEFORE_DRAW_DATA_POINT_LABEL,
la );
}
private PieSlice( )
{
// Used to clone
}
public Label getLabel( )
{
return la;
}
/* (non-Javadoc)
* @see java.lang.Object#clone()
*/
@Override
public Object clone( )
{
PieSlice slice;
try
{
slice = (PieSlice) super.clone( );
}
catch ( CloneNotSupportedException e )
{
slice = new PieSlice( );
}
copyTo( slice );
return slice;
}
public void copyTo( PieSlice slice )
{
slice.primitiveValue = primitiveValue;
slice.dataPointHints = dataPointHints;
slice.categoryIndex = this.categoryIndex;
slice.setLabelLocation( loPie, loStart, loEnd );
slice.setExploded( isExploded );
slice.setStartAngle( startAngle );
slice.setSliceLength( sliceLength );
slice.setPercentage( slicePecentage );
slice.setBounds( bounds );
slice.labelBounding = labelBounding;
slice.quadrant = quadrant;
}
public double getPrimitiveValue( )
{
return primitiveValue;
}
public DataPointHints getDataPointHints( )
{
return dataPointHints;
}
public String getDisplayValue( )
{
return dataPointHints.getDisplayValue( );
}
public double getOriginalStartAngle( )
{
return originalStartAngle;
}
public double getStartAngle( )
{
return startAngle;
}
public double getSliceLength( )
{
return sliceLength;
}
public double getdMidAngle( )
{
return startAngle + sliceLength / 2;
}
public double getOriginalMidAngle( )
{
return originalStartAngle + sliceLength / 2;
}
public double getSlicePercentage( )
{
return slicePecentage;
}
public int getCategoryIndex( )
{
return categoryIndex;
}
public int getQuadrant( )
{
return quadrant;
}
public void setLabelLocation( double dX0, double dY0, double dX1,
double dY1, double dX2, double dY2 )
{
setLabelLocation( goFactory.createLocation( dX0, dY0 ),
goFactory.createLocation( dX1, dY1 ),
goFactory.createLocation( dX2, dY2 ) );
}
public void setLabelLocation( Location loPie, Location loStart,
Location loEnd )
{
this.loPie = loPie;
this.loStart = loStart;
this.loEnd = loEnd;
}
public void setExploded( boolean isExploded )
{
this.isExploded = isExploded;
}
public void setOriginalStartAngle( double originalStartAngle )
{
this.originalStartAngle = originalStartAngle;
}
public void setStartAngle( double startAngle )
{
this.startAngle = startAngle;
}
public void setSliceLength( double newLength )
{
sliceLength = newLength;
}
public void setPercentage( double newPercentage )
{
slicePecentage = newPercentage;
}
public final BoundingBox getLabelBounding( )
{
return labelBounding;
}
public void removeLabelBounding( )
{
// Added to resolve empty category stacking (Bugzilla 197128)
labelBounding = null;
}
/**
* @param loC
* center coordinates of pie slice.
* @param loOffset
* pie slice officeset for multiple dimension.
* @param sz
* the width and height of pie slice.
* @param fi
* the fill properties.
* @param iPieceType
* @throws ChartException
*/
private final void render( Location loC, Location loOffset, Size sz,
Fill fi, int iPieceType ) throws ChartException
{
loC.translate( loOffset.getX( ) / 2d, loOffset.getY( ) / 2d );
if ( isExploded && dExplosion != 0 )
{
// double dRatio = (double) d.width / d.height;
double dMidAngleInRadians = Math.toRadians( getStartAngle( )
+ getSliceLength( )
/ 2d );
double dSineThetaMid = ( Math.sin( dMidAngleInRadians ) );
double dCosThetaMid = ( Math.cos( dMidAngleInRadians ) );
double xDelta = ( dExplosion * dCosThetaMid );
double yDelta = ( dExplosion * dSineThetaMid );
if ( ratio < 1 )
{
yDelta = yDelta * ratio;
}
else
{
xDelta = xDelta / ratio;
}
loC.translate( xDelta, -yDelta );
}
Location loCTop = goFactory.createLocation( loC.getX( )
- loOffset.getX( ), loC.getY( ) - loOffset.getY( ) );
double dAngleInRadians = Math.toRadians( getStartAngle( ) );
double dSineThetaStart = Math.sin( dAngleInRadians );
double dCosThetaStart = Math.cos( dAngleInRadians );
dAngleInRadians = Math.toRadians( getStartAngle( )
+ getSliceLength( ) );
double dSineThetaEnd = Math.sin( dAngleInRadians );
double dCosThetaEnd = Math.cos( dAngleInRadians );
double xE = ( sz.getWidth( ) * dCosThetaEnd );
double yE = ( sz.getHeight( ) * dSineThetaEnd );
double xS = ( sz.getWidth( ) * dCosThetaStart );
double yS = ( sz.getHeight( ) * dSineThetaStart );
ArcRenderEvent are = null;
if ( iPieceType == LOWER )
{
are = new ArcRenderEvent( WrappedStructureSource.createSeriesDataPoint( ps,
dataPointHints ) );
}
else
{
are = ( (EventObjectCache) idr ).getEventObject( WrappedStructureSource.createSeriesDataPoint( ps,
getDataPointHints( ) ),
ArcRenderEvent.class );
}
are.setBackground( fi );
liaEdges.setColor( getSliceOutline( fi ) );
are.setOutline( liaEdges );
are.setTopLeft( goFactory.createLocation( loCTop.getX( )
- sz.getWidth( ),
loCTop.getY( )
- sz.getHeight( )
+ ( iPieceType == LOWER ? dThickness : 0 ) ) );
are.setWidth( sz.getWidth( ) * 2 );
are.setHeight( sz.getHeight( ) * 2 );
are.setStartAngle( startAngle );
are.setAngleExtent( sliceLength );
are.setStyle( ArcRenderEvent.SECTOR );
idr.fillArc( are ); // Fill the top side of pie slice.
if ( iPieceType == LOWER )
{
// DRAWN INTO A BUFFER FOR DEFERRED RENDERING
double[] daXPoints = {
loC.getX( ),
loCTop.getX( ),
loCTop.getX( ) + xE,
loC.getX( ) + xE
};
double[] daYPoints = {
loC.getY( ),
loCTop.getY( ),
loCTop.getY( ) - yE,
loC.getY( ) - yE
};
deferFlatPlane( flatPlanes,
getStartAngle( ) + getSliceLength( ),
daXPoints,
daYPoints,
fi,
dataPointHints );
daXPoints = new double[]{
loC.getX( ),
loC.getX( ) + xS,
loCTop.getX( ) + xS,
loCTop.getX( )
};
daYPoints = new double[]{
loC.getY( ),
loC.getY( ) - yS,
loCTop.getY( ) - yS,
loCTop.getY( )
};
deferFlatPlane( flatPlanes,
getStartAngle( ),
daXPoints,
daYPoints,
fi,
dataPointHints );
daXPoints = new double[]{
loC.getX( ) + xS,
loCTop.getX( ) + xS,
loCTop.getX( ) + xE,
loC.getX( ) + xE
};
daYPoints = new double[]{
loC.getY( ) - yS,
loCTop.getY( ) - yS,
loCTop.getY( ) - yE,
loC.getY( ) - yE
};
final LineRenderEvent lreStartB2T = new LineRenderEvent( WrappedStructureSource.createSeriesDataPoint( ps,
dataPointHints ) );
lreStartB2T.setStart( goFactory.createLocation( loC.getX( )
+ xS,
loC.getY( ) - yS ) );
lreStartB2T.setEnd( goFactory.createLocation( loCTop.getX( )
+ xS,
loCTop.getY( ) - yS ) );
final LineRenderEvent lreEndT2B = new LineRenderEvent( WrappedStructureSource.createSeriesDataPoint( ps,
dataPointHints ) );
lreEndT2B.setStart( goFactory.createLocation( loCTop.getX( )
+ xE,
loCTop.getY( ) - yE ) );
lreEndT2B.setEnd( goFactory.createLocation( loC.getX( ) + xE,
loC.getY( ) - yE ) );
Bounds r2ddTop = goFactory.createBounds( loCTop.getX( )
- sz.getWidth( ),
loCTop.getY( ) - sz.getHeight( ),
sz.getWidth( ) * 2,
sz.getHeight( ) * 2 );
Bounds r2ddBottom = goFactory.createBounds( loC.getX( )
- sz.getWidth( ),
loC.getY( ) - sz.getHeight( ),
sz.getWidth( ) * 2,
sz.getHeight( ) * 2 );
registerCurvedSurface( r2ddTop,
r2ddBottom,
getStartAngle( ),
getSliceLength( ),
lreStartB2T,
lreEndT2B,
fi,
dataPointHints,
loC,
loCTop,
sz );
}
else if ( iPieceType == UPPER ) // DRAWN IMMEDIATELY
{
if ( ps.getSliceOutline( ) != null )
{
idr.drawArc( are );
}
if ( pie.isInteractivityEnabled( ) )
{
final EList<Trigger> elTriggers = ps.getTriggers( );
if ( !elTriggers.isEmpty( ) )
{
final StructureSource iSource = WrappedStructureSource.createSeriesDataPoint( ps,
dataPointHints );
final InteractionEvent iev = ( (EventObjectCache) idr ).getEventObject( iSource,
InteractionEvent.class );
iev.setCursor( ps.getCursor( ) );
Trigger tg;
for ( int t = 0; t < elTriggers.size( ); t++ )
{
tg = goFactory.copyOf( elTriggers.get( t ) );
pie.processTrigger( tg, iSource );
iev.addTrigger( tg );
}
iev.setHotSpot( are );
idr.enableInteraction( iev );
}
}
}
}
private void renderOneLine( IDeviceRenderer idr, Location lo1,
Location lo2 ) throws ChartException
{
LineRenderEvent lre = ( (EventObjectCache) idr ).getEventObject( WrappedStructureSource.createSeriesDataPoint( ps,
dataPointHints ),
LineRenderEvent.class );
lre.setLineAttributes( liaLL );
lre.setStart( lo1 );
lre.setEnd( lo2 );
idr.drawLine( lre );
}
private final void renderLabel( IDeviceRenderer idr, int iTextRenderType )
throws ChartException
{
if ( labelBounding == null )
{// Do not render if no bounding
return;
}
if ( quadrant != -1 )
{
if ( iTextRenderType == TextRenderEvent.RENDER_TEXT_AT_LOCATION )
{
renderOneLine( idr, loPie, loStart );
renderOneLine( idr, loStart, loEnd );
}
pie.renderLabel( WrappedStructureSource.createSeriesDataPoint( ps,
dataPointHints ),
TextRenderEvent.RENDER_TEXT_IN_BLOCK,
getLabel( ),
( quadrant == 1 || quadrant == 4 ) ? Position.RIGHT_LITERAL
: Position.LEFT_LITERAL,
loEnd,
goFactory.createBounds( labelBounding.getLeft( ),
labelBounding.getTop( ),
labelBounding.getWidth( ),
labelBounding.getHeight( ) ) );
}
else
{
pie.renderLabel( StructureSource.createSeries( ps ),
TextRenderEvent.RENDER_TEXT_IN_BLOCK,
getLabel( ),
null,
null,
goFactory.createBounds( labelBounding.getLeft( ),
labelBounding.getTop( ),
labelBounding.getWidth( ),
labelBounding.getHeight( ) ) );
}
}
public boolean isLabelClipped( Bounds bo )
{
if ( labelBounding != null )
{
if ( labelBounding.getTop( ) < bo.getTop( ) )
{
return true;
}
if ( labelBounding.getLeft( ) < bo.getLeft( ) )
{
return true;
}
if ( labelBounding.getTop( ) + labelBounding.getHeight( ) > bo.getTop( )
+ bo.getHeight( ) )
{
return true;
}
if ( labelBounding.getLeft( ) + labelBounding.getWidth( ) > bo.getLeft( )
+ bo.getWidth( ) )
{
return true;
}
}
return false;
}
public boolean isLabelOverlap( PieSlice sliceToCompare )
{
if ( sliceToCompare == null
|| sliceToCompare == this
|| sliceToCompare.labelBounding == null )
{
return false;
}
BoundingBox bb1 = labelBounding, bb2 = sliceToCompare.labelBounding;
BoundingBox dHigh, dLow;
// check which one is higher
if ( bb1.getTop( ) < bb2.getTop( ) )
{
dHigh = bb1;
dLow = bb2;
}
else
{
dHigh = bb2;
dLow = bb1;
}
double dXHigh, dXLow, dYHigh, dYLow;
if ( dHigh.getLeft( ) < dLow.getLeft( ) )
{
dXHigh = dHigh.getLeft( ) + dHigh.getWidth( );
dYHigh = dHigh.getTop( ) + dHigh.getHeight( );
dXLow = dLow.getLeft( );
dYLow = dLow.getTop( );
if ( dXHigh > dXLow && dYHigh > dYLow )
{
return true;
}
}
else
{
dXHigh = dHigh.getLeft( );
dYHigh = dHigh.getTop( ) + dHigh.getHeight( );
dXLow = dLow.getLeft( ) + dLow.getWidth( );
dYLow = dLow.getTop( );
if ( dXHigh < dXLow && dYHigh > dYLow )
{
return true;
}
}
return false;
}
public void setBounds( Bounds bo )
{
bounds = bo;
w = bounds.getWidth( ) / 2 - dExplosion;
h = bounds.getHeight( ) / 2 - dExplosion - dThickness / 2;
xc = bounds.getLeft( ) + w + dExplosion;
yc = bounds.getTop( ) + h + dExplosion + dThickness / 2;
if ( ratio > 0 && w > 0 )
{
if ( h / w > ratio )
{
h = w * ratio;
}
else if ( h / w < ratio )
{
w = h / ratio;
}
}
// detect invalid size.
if ( w <= 0 || h <= 0 )
{
w = h = 1;
}
}
private void computeLabelBoundOutside( LeaderLineStyle lls,
double dLeaderLength, OutsideLabelBoundCache bbCache )
throws ChartException
{
int iLL = 0;
double dLeaderTick = Math.max( dLeaderLength / 4,
LEADER_TICK_MIN_SIZE * pie.getDeviceScale( ) );
double dLeaderW = 0, dLeaderH = 0, dBottomLeaderW = 0, dBottomLeaderH = 0, dTopLeaderW = 0, dTopLeaderH = 0;
Location center = goFactory.createLocation( xc, yc - dThickness / 2 );
Location depthCenter = goFactory.createLocation( xc, yc ); // center
// in
// the
// middle of the depth
double dX = 0;
double dLeftSide = xc - dExplosion - w;
double dRightSide = xc + dExplosion + w;
if ( w > h )
{
dTopLeaderW = dLeaderTick;
dTopLeaderH = dLeaderTick * ratio;
}
else
{
dTopLeaderH = dLeaderTick;
dTopLeaderW = dLeaderTick / ratio;
}
double dMidAngleInDegrees = getOriginalMidAngle( ) % 360;
double dMidAngleInRadians = Math.toRadians( -dMidAngleInDegrees );
double dSineThetaMid = Math.sin( dMidAngleInRadians );
double dCosThetaMid = Math.cos( dMidAngleInRadians );
if ( dThickness > 0
&& dMidAngleInDegrees > 180
&& dMidAngleInDegrees < 360 )
{
double dTmpLeaderTick = Math.max( dThickness
* dSineThetaMid
+ 8
* pie.getDeviceScale( ), dLeaderTick );
if ( w > h )
{
dBottomLeaderW = dTmpLeaderTick;
dBottomLeaderH = dTmpLeaderTick * ratio;
}
else
{
dBottomLeaderH = dTmpLeaderTick;
dBottomLeaderW = dTmpLeaderTick / ratio;
}
dLeaderW = dBottomLeaderW;
dLeaderH = dBottomLeaderH;
}
else
{
dLeaderW = dTopLeaderW;
dLeaderH = dTopLeaderH;
}
double xDelta1, yDelta1, xDelta2, yDelta2;
if ( isExploded )
{
xDelta1 = ( w + dExplosion ) * dCosThetaMid;
yDelta1 = ( h + dExplosion ) * dSineThetaMid;
xDelta2 = ( w + dLeaderW + dExplosion ) * dCosThetaMid;
yDelta2 = ( h + dLeaderH + dExplosion ) * dSineThetaMid;
}
else
{
xDelta1 = ( w ) * dCosThetaMid;
yDelta1 = ( h ) * dSineThetaMid;
xDelta2 = ( w + dLeaderW ) * dCosThetaMid;
yDelta2 = ( h + dLeaderH ) * dSineThetaMid;
}
if ( lls == LeaderLineStyle.STRETCH_TO_SIDE_LITERAL )
{
if ( dMidAngleInDegrees >= 90 && dMidAngleInDegrees < 270 )
{
dX = dLeftSide - dLeaderW * 1.5;
iLL = IConstants.LEFT;
}
else
{
dX = dRightSide + dLeaderW * 1.5;
iLL = IConstants.RIGHT;
}
}
else if ( lls == LeaderLineStyle.FIXED_LENGTH_LITERAL )
{
if ( dMidAngleInDegrees > 90 && dMidAngleInDegrees < 270 )
{
dX = center.getX( ) + xDelta2 - dLeaderLength;
if ( dLeaderLength > 0 )
{
iLL = IConstants.LEFT;
}
else
{
if ( dMidAngleInDegrees < 135 )
{
iLL = IConstants.TOP;
}
else if ( dMidAngleInDegrees < 225 )
{
iLL = IConstants.LEFT;
}
else if ( dMidAngleInDegrees < 270 )
{
iLL = IConstants.BOTTOM;
}
else
assert false;
}
}
else
{
dX = center.getX( ) + xDelta2 + dLeaderLength;
if ( dLeaderLength > 0 )
{
iLL = IConstants.RIGHT;
}
else
{
if ( dMidAngleInDegrees <= 45 )
{
iLL = IConstants.RIGHT;
}
else if ( dMidAngleInDegrees > 45
&& dMidAngleInDegrees <= 90 )
{
iLL = IConstants.TOP;
}
else if ( dMidAngleInDegrees <= 315
&& dMidAngleInDegrees >= 270 )
{
iLL = IConstants.BOTTOM;
}
else if ( dMidAngleInDegrees > 315 )
{
iLL = IConstants.RIGHT;
}
else
assert false;
}
}
}
else
{
// SHOULD'VE ALREADY THROWN THIS EXCEPTION PREVIOUSLY
}
Location relativeCenter;
if ( dMidAngleInDegrees > 0 && dMidAngleInDegrees < 180 )
{
relativeCenter = center;
}
else
{
relativeCenter = depthCenter;
}
xDock = relativeCenter.getX( ) + xDelta1;
yDock = relativeCenter.getY( ) + yDelta1;
setLabelLocation( xDock,
yDock,
relativeCenter.getX( ) + xDelta2,
relativeCenter.getY( ) + yDelta2,
dX,
relativeCenter.getY( ) + yDelta2 );
if ( bbCache != null && bbCache.iLL == iLL && bbCache.bb != null )
{
labelBounding = bbCache.bb.clone( );
}
else
{
labelBounding = cComp.computeBox( xs, iLL, getLabel( ), 0, 0 );
if ( bbCache != null && bbCache.iLL == 0 )
{
bbCache.iLL = iLL;
bbCache.bb = labelBounding.clone( );
}
}
labelBounding.setLeft( labelBounding.getLeft( ) + dX );
labelBounding.setTop( labelBounding.getTop( )
+ relativeCenter.getY( )
+ yDelta2 );
// NEEDED FOR COMPUTING DYNAMIC REPOSITIONING LIMITS
if ( dMidAngleInDegrees >= 0 && dMidAngleInDegrees < 90 )
{
quadrant = 1;
}
if ( dMidAngleInDegrees >= 90 && dMidAngleInDegrees < 180 )
{
quadrant = 2;
}
if ( dMidAngleInDegrees >= 180 && dMidAngleInDegrees < 270 )
{
quadrant = 3;
}
else
{
quadrant = 4;
}
}
private void computeLabelBoundInside( ) throws ChartException
{
double dMidAngleInRadians = Math.toRadians( -getdMidAngle( ) );
double dSineThetaMid = Math.sin( dMidAngleInRadians );
double dCosThetaMid = Math.cos( dMidAngleInRadians );
double xDelta, yDelta;
if ( isExploded )
{
xDelta = ( ( w / 1.5d + dExplosion ) * dCosThetaMid );
yDelta = ( ( h / 1.5d + dExplosion ) * dSineThetaMid );
}
else
{
xDelta = ( ( w / 1.5d ) * dCosThetaMid );
yDelta = ( ( h / 1.5d ) * dSineThetaMid );
}
labelBounding = cComp.computeBox( xs,
IConstants.LEFT/* DONT-CARE */,
getLabel( ),
0,
0 );
labelBounding.setLeft( xc + xDelta - labelBounding.getWidth( ) / 2 );
labelBounding.setTop( yc
- dThickness
/ 2
+ yDelta
- labelBounding.getHeight( )
/ 2 );
}
}
} | Fixed Bugzilla #310061 - Positive/Negative color does not work in pie chart.[13].
| chart/org.eclipse.birt.chart.engine.extension/src/org/eclipse/birt/chart/extension/render/PieRenderer.java | Fixed Bugzilla #310061 - Positive/Negative color does not work in pie chart.[13]. |
|
Java | mpl-2.0 | 1df9d5767b3222cace051a75259dea5d951cbfaf | 0 | JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core | /*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* 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 .
*/
package org.openoffice.netbeans.modules.office.options;
import java.util.Hashtable;
import java.util.Enumeration;
import java.io.File;
import java.io.IOException;
import org.openide.options.SystemOption;
import org.openide.util.HelpCtx;
import org.openide.util.NbBundle;
import org.openoffice.idesupport.SVersionRCFile;
import org.openoffice.idesupport.OfficeInstallation;
/** Options for something or other.
*/
public class OfficeSettings extends SystemOption {
public static final String OFFICE_DIRECTORY = "OfficeDirectory";
public static final String WARN_BEFORE_DOC_DEPLOY = "WarnBeforeDocDeploy";
public static final String WARN_BEFORE_PARCEL_DELETE = "WarnBeforeParcelDelete";
public static final String WARN_AFTER_DIR_DEPLOY = "WarnAfterDirDeploy";
public static final String WARN_BEFORE_MOUNT = "WarnBeforeMount";
protected void initialize() {
super.initialize();
setWarnBeforeDocDeploy(true);
setWarnBeforeParcelDelete(true);
setWarnAfterDirDeploy(true);
setWarnBeforeMount(true);
if (getOfficeDirectory() == null) {
SVersionRCFile sversion = SVersionRCFile.createInstance();
try {
Enumeration enumeration = sversion.getVersions();
OfficeInstallation oi;
while (enumeration.hasMoreElements()) {
oi = (OfficeInstallation)enumeration.nextElement();
setOfficeDirectory(oi);
return;
}
} catch (IOException ioe) {
}
}
}
public String displayName() {
return "Office Settings";
}
public HelpCtx getHelpCtx() {
return HelpCtx.DEFAULT_HELP;
}
public static OfficeSettings getDefault() {
return (OfficeSettings)findObject(OfficeSettings.class, true);
}
public OfficeInstallation getOfficeDirectory() {
return (OfficeInstallation)getProperty(OFFICE_DIRECTORY);
}
public void setOfficeDirectory(OfficeInstallation oi) {
putProperty(OFFICE_DIRECTORY, oi, true);
}
public boolean getWarnBeforeDocDeploy() {
return ((Boolean)getProperty(WARN_BEFORE_DOC_DEPLOY)).booleanValue();
}
public void setWarnBeforeDocDeploy(boolean value) {
putProperty(WARN_BEFORE_DOC_DEPLOY, Boolean.valueOf(value), true);
}
public boolean getWarnBeforeParcelDelete() {
return ((Boolean)getProperty(WARN_BEFORE_PARCEL_DELETE)).booleanValue();
}
public void setWarnBeforeParcelDelete(boolean value) {
putProperty(WARN_BEFORE_PARCEL_DELETE, Boolean.valueOf(value), true);
}
public boolean getWarnAfterDirDeploy() {
return ((Boolean)getProperty(WARN_AFTER_DIR_DEPLOY)).booleanValue();
}
public void setWarnAfterDirDeploy(boolean value) {
putProperty(WARN_AFTER_DIR_DEPLOY, Boolean.valueOf(value), true);
}
public boolean getWarnBeforeMount() {
return ((Boolean)getProperty(WARN_BEFORE_MOUNT)).booleanValue();
}
public void setWarnBeforeMount(boolean value) {
putProperty(WARN_BEFORE_MOUNT, Boolean.valueOf(value), true);
}
}
| scripting/java/org/openoffice/netbeans/modules/office/options/OfficeSettings.java | /*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* 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 .
*/
package org.openoffice.netbeans.modules.office.options;
import java.util.Hashtable;
import java.util.Enumeration;
import java.io.File;
import java.io.IOException;
import org.openide.options.SystemOption;
import org.openide.util.HelpCtx;
import org.openide.util.NbBundle;
import org.openoffice.idesupport.SVersionRCFile;
import org.openoffice.idesupport.OfficeInstallation;
/** Options for something or other.
*/
public class OfficeSettings extends SystemOption {
public static final String OFFICE_DIRECTORY = "OfficeDirectory";
public static final String WARN_BEFORE_DOC_DEPLOY = "WarnBeforeDocDeploy";
public static final String WARN_BEFORE_PARCEL_DELETE = "WarnBeforeParcelDelete";
public static final String WARN_AFTER_DIR_DEPLOY = "WarnAfterDirDeploy";
public static final String WARN_BEFORE_MOUNT = "WarnBeforeMount";
protected void initialize() {
super.initialize();
setWarnBeforeDocDeploy(true);
setWarnBeforeParcelDelete(true);
setWarnAfterDirDeploy(true);
setWarnBeforeMount(true);
if (getOfficeDirectory() == null) {
SVersionRCFile sversion = SVersionRCFile.createInstance();
try {
Enumeration enum = sversion.getVersions();
OfficeInstallation oi;
while (enum.hasMoreElements()) {
oi = (OfficeInstallation)enum.nextElement();
setOfficeDirectory(oi);
return;
}
} catch (IOException ioe) {
}
}
}
public String displayName() {
return "Office Settings";
}
public HelpCtx getHelpCtx() {
return HelpCtx.DEFAULT_HELP;
}
public static OfficeSettings getDefault() {
return (OfficeSettings)findObject(OfficeSettings.class, true);
}
public OfficeInstallation getOfficeDirectory() {
return (OfficeInstallation)getProperty(OFFICE_DIRECTORY);
}
public void setOfficeDirectory(OfficeInstallation oi) {
putProperty(OFFICE_DIRECTORY, oi, true);
}
public boolean getWarnBeforeDocDeploy() {
return ((Boolean)getProperty(WARN_BEFORE_DOC_DEPLOY)).booleanValue();
}
public void setWarnBeforeDocDeploy(boolean value) {
putProperty(WARN_BEFORE_DOC_DEPLOY, Boolean.valueOf(value), true);
}
public boolean getWarnBeforeParcelDelete() {
return ((Boolean)getProperty(WARN_BEFORE_PARCEL_DELETE)).booleanValue();
}
public void setWarnBeforeParcelDelete(boolean value) {
putProperty(WARN_BEFORE_PARCEL_DELETE, Boolean.valueOf(value), true);
}
public boolean getWarnAfterDirDeploy() {
return ((Boolean)getProperty(WARN_AFTER_DIR_DEPLOY)).booleanValue();
}
public void setWarnAfterDirDeploy(boolean value) {
putProperty(WARN_AFTER_DIR_DEPLOY, Boolean.valueOf(value), true);
}
public boolean getWarnBeforeMount() {
return ((Boolean)getProperty(WARN_BEFORE_MOUNT)).booleanValue();
}
public void setWarnBeforeMount(boolean value) {
putProperty(WARN_BEFORE_MOUNT, Boolean.valueOf(value), true);
}
}
| scripting: as of release 5, 'enum' is a keyword
Change-Id: Ia45890892f3a0fa89b4c1f97a4c169de5e25c593
Reviewed-on: https://gerrit.libreoffice.org/11860
Reviewed-by: Samuel Mehrbrodt <[email protected]>
Tested-by: Samuel Mehrbrodt <[email protected]>
| scripting/java/org/openoffice/netbeans/modules/office/options/OfficeSettings.java | scripting: as of release 5, 'enum' is a keyword |
|
Java | agpl-3.0 | 239a3c6beb1a28985742ffe90cc243b3cab28ff0 | 0 | ow2-proactive/scheduling-portal,laurianed/scheduling-portal,ShatalovYaroslav/scheduling-portal,paraita/scheduling-portal,ow2-proactive/scheduling-portal,laurianed/scheduling-portal,paraita/scheduling-portal,lpellegr/scheduling-portal,ShatalovYaroslav/scheduling-portal,laurianed/scheduling-portal,lpellegr/scheduling-portal,ShatalovYaroslav/scheduling-portal,paraita/scheduling-portal,ow2-proactive/scheduling-portal,lpellegr/scheduling-portal | /*
* *
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2014 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: [email protected] or [email protected]
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; version 3 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
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero 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
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* * $$PROACTIVE_INITIAL_DEV$$
*/
package org.ow2.proactive_grid_cloud_portal.scheduler.client.view.grid.jobs;
import java.util.ArrayList;
import java.util.Map;
import org.ow2.proactive_grid_cloud_portal.scheduler.client.Job;
import org.ow2.proactive_grid_cloud_portal.scheduler.client.JobPriority;
import org.ow2.proactive_grid_cloud_portal.scheduler.client.JobStatus;
import org.ow2.proactive_grid_cloud_portal.scheduler.client.SchedulerImages;
import org.ow2.proactive_grid_cloud_portal.scheduler.client.SchedulerListeners.JobsUpdatedListener;
import org.ow2.proactive_grid_cloud_portal.scheduler.client.controller.JobsController;
import org.ow2.proactive_grid_cloud_portal.scheduler.client.view.grid.GridColumns;
import org.ow2.proactive_grid_cloud_portal.scheduler.client.view.grid.ItemsListGrid;
import com.smartgwt.client.data.DSCallback;
import com.smartgwt.client.data.DSRequest;
import com.smartgwt.client.data.DSResponse;
import com.smartgwt.client.data.RecordList;
import com.smartgwt.client.data.SortSpecifier;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.ListGridFieldType;
import com.smartgwt.client.types.SortDirection;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.grid.CellFormatter;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.grid.SortNormalizer;
import com.smartgwt.client.widgets.grid.events.SelectionEvent;
import com.smartgwt.client.widgets.menu.Menu;
import com.smartgwt.client.widgets.menu.MenuItem;
import com.smartgwt.client.widgets.menu.events.ClickHandler;
import com.smartgwt.client.widgets.menu.events.MenuItemClickEvent;
import static org.ow2.proactive_grid_cloud_portal.scheduler.client.view.grid.jobs.JobsColumnsFactory.*;
import static org.ow2.proactive_grid_cloud_portal.scheduler.client.view.grid.jobs.JobsColumnsFactory.ISSUES_ATTR;
/**
* A list grid that shows jobs.
*
* @author The activeeon team.
*/
public class JobsListGrid extends ItemsListGrid<Job> implements JobsUpdatedListener {
private static final SortSpecifier[] DEFAULT_SORT = new SortSpecifier[] {
new SortSpecifier(STATE_ATTR.getName(), SortDirection.ASCENDING),
new SortSpecifier(ID_ATTR.getName(), SortDirection.DESCENDING) };
/**
* The controller for the jobs grid.
*/
protected JobsController controller;
public JobsListGrid(final JobsController controller) {
super(new JobsColumnsFactory(), "jobsDS_");
this.emptyMessage = "No jobs to show. You can find workflows to submit in the samples/workflows folder where the Scheduler is installed.";
this.controller = controller;
this.controller.getModel().addJobsUpdatedListener(this);
}
@Override
public void build() {
super.build();
this.setSelectionProperty("isSelected");
this.setSort(DEFAULT_SORT);
}
protected void selectionChangedHandler(SelectionEvent event) {
if (event.getState() && !fetchingData) {
ListGridRecord record = event.getRecord();
Job job = JobRecord.getJob(record);
controller.selectJob(job);
}
}
@Override
public void jobsUpdated(Map<Integer, Job> jobs, long totalJobs) {
Job selectedJob = this.controller.getModel().getSelectedJob();
RecordList data = new RecordList();
for (Job j : jobs.values()) {
JobRecord jobRecord = new JobRecord(j);
this.columnsFactory.buildRecord(j, jobRecord);
data.add(jobRecord);
if (j.equals(selectedJob)) {
jobRecord.setAttribute("isSelected", true);
}
}
this.ds.setTestData(data.toArray());
applyCurrentLocalFilter();
}
@Override
public void jobsUpdating() {
// TODO Auto-generated method stub
}
@Override
public void jobSubmitted(Job j) {
JobRecord jr = new JobRecord(j);
DSRequest customErrorHandling = new DSRequest();
customErrorHandling.setWillHandleError(true);
this.ds.addData(jr, new DSCallback() {
@Override
public void execute(DSResponse dsResponse, Object o, DSRequest dsRequest) {
if (dsResponse.getStatus() < 0) {
// it could fail because results from the server with the new job are already displayed
// failed silently since the new job is already displayed or will be anyway with next call
SC.logWarn(dsResponse.getDataAsString());
}
}
}, customErrorHandling);
applyCurrentLocalFilter();
}
@Override
protected String getCellCSSText(ListGridRecord record, int rowNum, int colNum) {
String base = super.getCellCSSText(record, rowNum, colNum);
return getJobStatusFieldColor(record, rowNum, colNum, base);
}
protected String getJobStatusFieldColor(ListGridRecord record, int rowNum, int colNum, String base) {
String fieldName = this.getFieldName(colNum);
base = highlightRowHavingIssues(rowNum, base);
/* change the color of the job status field */
if (fieldName.equals(STATE_ATTR.getName())) {
try {
switch (getJobStatus(record)) {
case KILLED:
return "color:#d37a11;font-weight:bold;" + base;
case CANCELED:
case FAILED:
case IN_ERROR:
return "color:#c50000;font-weight:bold;" + base;
case RUNNING:
return "color:#176925;font-weight:bold;" + base;
case PENDING:
return "color:#1a8bba;" + base;
case STALLED:
case PAUSED:
return "font-weight:bold;" + base;
case FINISHED:
return base;
}
} catch (NullPointerException npe) {
return base;
}
}
return base;
}
private String highlightRowHavingIssues(int rowNum, String base) {
Object issues = getEditedCell(rowNum, ISSUES_ATTR.getName());
if (issues instanceof Integer) {
base = "background-color: #FFDEDE;";
}
return base;
}
protected Map<GridColumns, ListGridField> buildListGridField() {
Map<GridColumns, ListGridField> fields = super.buildListGridField();
alignCells(fields);
ListGridField idField = fields.get(ID_ATTR);
idField.setType(ListGridFieldType.INTEGER);
ListGridField stateField = fields.get(STATE_ATTR);
stateField.setSortNormalizer(sortStatusAndGroup());
ListGridField progressField = fields.get(PROGRESS_ATTR);
progressField.setType(ListGridFieldType.FLOAT);
progressField.setAlign(Alignment.CENTER);
progressField.setCellFormatter(new CellFormatter() {
public String format(Object value, ListGridRecord record, int rowNum, int colNum) {
int pw = getFieldWidth(PROGRESS_ATTR.getName());
float progress = 0;
if (value != null) {
progress = Float.parseFloat(value.toString());
}
int bx = new Double(Math.ceil(pw * progress)).intValue() - 601;
String progressUrl = SchedulerImages.instance.progressbar().getSafeUri().asString();
String style = "display:block; " + //
"border: 1px solid #acbac7; " + //
"background-image:url(" + progressUrl + ");" + //
"background-position:" + bx + "px 0px;" + //
"background-repeat: no-repeat;" + //
"background-color:#a7cef6";
Job job = JobRecord.getJob(record);
String progressCounters = job.getFinishedTasks() + " / " + job.getTotalTasks();
return "<div style='" + style + "'>" + progressCounters + "</div>";
}
});
ListGridField duration = fields.get(DURATION_ATTR);
duration.setCellFormatter(new CellFormatter() {
public String format(Object value, ListGridRecord record, int rowNum, int colNum) {
if (value != null) {
long l = Long.parseLong(value.toString());
return Job.formatDuration(l);
} else {
return "";
}
}
});
return fields;
}
private void alignCells(Map<GridColumns, ListGridField> fields) {
GridColumns[] columnsToAlignCenter =
new GridColumns[] { ID_ATTR, STATE_ATTR, ISSUES_ATTR, USER_ATTR,
PROGRESS_ATTR, PRIORITY_ATTR, DURATION_ATTR };
for (GridColumns column : columnsToAlignCenter) {
ListGridField listGridField = fields.get(column);
listGridField.setAlign(Alignment.CENTER);
listGridField.setCellAlign(Alignment.CENTER);
}
}
/**
* A custom sort for status:
* - pending first
* - running, stalled, paused then
* - all other status (finished, killed,...)
*/
private SortNormalizer sortStatusAndGroup() {
return new SortNormalizer() {
@Override
public Object normalize(ListGridRecord record, String fieldName) {
String status = record.getAttribute(fieldName);
if (status.equals(JobStatus.PENDING.toString())) {
return 0;
} else if (status.equals(JobStatus.RUNNING.toString()) ||
status.equals(JobStatus.STALLED.toString()) ||
status.equals(JobStatus.PAUSED.toString())) {
return 1;
} else {
return 2;
}
}
};
}
protected void buildCellContextualMenu(Menu menu) {
boolean selPause = true; // ALL selected jobs are paused
boolean selRunning = true; // ALL selected jobs are running/stalled/pending
boolean selFinished = true; // ALL selected jobs are finished
boolean selPauseOrRunning = true; // ALL selected jobs are running/pending/paused/stalled
boolean selPausedOnError = false;
final ArrayList<String> ids = new ArrayList<String>(this.getSelectedRecords().length);
for (ListGridRecord rec : this.getSelectedRecords()) {
JobStatus status = getJobStatus(rec);
switch (status) {
case PENDING:
case STALLED:
selPause = false;
selFinished = false;
break;
case RUNNING:
selPause = false;
selFinished = false;
selPausedOnError = true;
break;
case PAUSED:
selFinished = false;
selPausedOnError = true;
selRunning = false;
break;
case IN_ERROR:
selFinished = false;
selPausedOnError = true;
selRunning = true;
break;
default:
selPauseOrRunning = false;
selRunning = false;
selPause = false;
}
ids.add(rec.getAttribute(ID_ATTR.getName()));
}
MenuItem pauseItem = new MenuItem("Pause",
SchedulerImages.instance.scheduler_pause_16().getSafeUri().asString());
pauseItem.addClickHandler(new ClickHandler() {
public void onClick(MenuItemClickEvent event) {
controller.pauseJobs(ids);
}
});
pauseItem.setEnabled(selRunning);
MenuItem restartOnErrorTaskItem = new MenuItem("Restart All In-Error Tasks",
SchedulerImages.instance.scheduler_resume_16().getSafeUri().asString());
restartOnErrorTaskItem.addClickHandler(new ClickHandler() {
public void onClick(MenuItemClickEvent event) {
controller.restartAllInErrorTasks(ids);
}
});
restartOnErrorTaskItem.setEnabled(selPausedOnError);
MenuItem resumeItem = new MenuItem("Resume",
SchedulerImages.instance.scheduler_resume_16().getSafeUri().asString());
resumeItem.addClickHandler(new ClickHandler() {
public void onClick(MenuItemClickEvent event) {
controller.resumeJobs(ids);
}
});
resumeItem.setEnabled(selPause);
MenuItem priorityItem = new MenuItem("Priority");
Menu priorityMenu = new Menu();
for (final JobPriority p : JobPriority.values()) {
MenuItem item = new MenuItem(p.toString());
if (!selPauseOrRunning) {
item.setEnabled(false);
} else {
item.addClickHandler(new ClickHandler() {
public void onClick(MenuItemClickEvent event) {
controller.setJobPriority(ids, p);
}
});
}
priorityMenu.addItem(item);
}
priorityItem.setSubmenu(priorityMenu);
MenuItem removeItem = new MenuItem("Remove",
SchedulerImages.instance.job_kill_16().getSafeUri().asString());
removeItem.addClickHandler(new ClickHandler() {
public void onClick(MenuItemClickEvent event) {
controller.removeJob(ids);
}
});
MenuItem killItem = new MenuItem("Kill",
SchedulerImages.instance.scheduler_kill_16().getSafeUri().asString());
killItem.addClickHandler(new ClickHandler() {
public void onClick(MenuItemClickEvent event) {
controller.killJob(ids);
}
});
killItem.setEnabled(selPauseOrRunning);
removeItem.setEnabled(selFinished);
menu.setItems(pauseItem, resumeItem, restartOnErrorTaskItem, priorityItem, removeItem, killItem);
}
private JobStatus getJobStatus(ListGridRecord rec) {
String jobStatusName = rec.getAttribute(STATE_ATTR.getName());
return JobStatus.from(jobStatusName);
}
}
| scheduler-portal/src/main/java/org/ow2/proactive_grid_cloud_portal/scheduler/client/view/grid/jobs/JobsListGrid.java | /*
* *
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2014 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: [email protected] or [email protected]
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; version 3 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
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero 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
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* * $$PROACTIVE_INITIAL_DEV$$
*/
package org.ow2.proactive_grid_cloud_portal.scheduler.client.view.grid.jobs;
import java.util.ArrayList;
import java.util.Map;
import org.ow2.proactive_grid_cloud_portal.scheduler.client.Job;
import org.ow2.proactive_grid_cloud_portal.scheduler.client.JobPriority;
import org.ow2.proactive_grid_cloud_portal.scheduler.client.JobStatus;
import org.ow2.proactive_grid_cloud_portal.scheduler.client.SchedulerImages;
import org.ow2.proactive_grid_cloud_portal.scheduler.client.SchedulerListeners.JobsUpdatedListener;
import org.ow2.proactive_grid_cloud_portal.scheduler.client.controller.JobsController;
import org.ow2.proactive_grid_cloud_portal.scheduler.client.view.grid.GridColumns;
import org.ow2.proactive_grid_cloud_portal.scheduler.client.view.grid.ItemsListGrid;
import com.smartgwt.client.data.DSCallback;
import com.smartgwt.client.data.DSRequest;
import com.smartgwt.client.data.DSResponse;
import com.smartgwt.client.data.RecordList;
import com.smartgwt.client.data.SortSpecifier;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.ListGridFieldType;
import com.smartgwt.client.types.SortDirection;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.grid.CellFormatter;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.grid.SortNormalizer;
import com.smartgwt.client.widgets.grid.events.SelectionEvent;
import com.smartgwt.client.widgets.menu.Menu;
import com.smartgwt.client.widgets.menu.MenuItem;
import com.smartgwt.client.widgets.menu.events.ClickHandler;
import com.smartgwt.client.widgets.menu.events.MenuItemClickEvent;
import static org.ow2.proactive_grid_cloud_portal.scheduler.client.view.grid.jobs.JobsColumnsFactory.*;
import static org.ow2.proactive_grid_cloud_portal.scheduler.client.view.grid.jobs.JobsColumnsFactory.ISSUES_ATTR;
/**
* A list grid that shows jobs.
*
* @author The activeeon team.
*/
public class JobsListGrid extends ItemsListGrid<Job>implements JobsUpdatedListener {
private static final SortSpecifier[] DEFAULT_SORT = new SortSpecifier[] {
new SortSpecifier(STATE_ATTR.getName(), SortDirection.ASCENDING),
new SortSpecifier(ID_ATTR.getName(), SortDirection.DESCENDING) };
/**
* The controller for the jobs grid.
*/
protected JobsController controller;
public JobsListGrid(final JobsController controller) {
super(new JobsColumnsFactory(), "jobsDS_");
this.emptyMessage = "No jobs to show. You can find workflows to submit in the samples/workflows folder where the Scheduler is installed.";
this.controller = controller;
this.controller.getModel().addJobsUpdatedListener(this);
}
@Override
public void build() {
super.build();
this.setSelectionProperty("isSelected");
this.setSort(DEFAULT_SORT);
}
protected void selectionChangedHandler(SelectionEvent event) {
if (event.getState() && !fetchingData) {
ListGridRecord record = event.getRecord();
Job job = JobRecord.getJob(record);
controller.selectJob(job);
}
}
@Override
public void jobsUpdated(Map<Integer, Job> jobs, long totalJobs) {
Job selectedJob = this.controller.getModel().getSelectedJob();
RecordList data = new RecordList();
for (Job j : jobs.values()) {
JobRecord jobRecord = new JobRecord(j);
this.columnsFactory.buildRecord(j, jobRecord);
data.add(jobRecord);
if (j.equals(selectedJob)) {
jobRecord.setAttribute("isSelected", true);
}
}
this.ds.setTestData(data.toArray());
applyCurrentLocalFilter();
}
@Override
public void jobsUpdating() {
// TODO Auto-generated method stub
}
@Override
public void jobSubmitted(Job j) {
JobRecord jr = new JobRecord(j);
DSRequest customErrorHandling = new DSRequest();
customErrorHandling.setWillHandleError(true);
this.ds.addData(jr, new DSCallback() {
@Override
public void execute(DSResponse dsResponse, Object o, DSRequest dsRequest) {
if (dsResponse.getStatus() < 0) {
// it could fail because results from the server with the new job are already displayed
// failed silently since the new job is already displayed or will be anyway with next call
SC.logWarn(dsResponse.getDataAsString());
}
}
}, customErrorHandling);
applyCurrentLocalFilter();
}
@Override
protected String getCellCSSText(ListGridRecord record, int rowNum, int colNum) {
String base = super.getCellCSSText(record, rowNum, colNum);
return getJobStatusFieldColor(record, rowNum, colNum, base);
}
protected String getJobStatusFieldColor(ListGridRecord record, int rowNum, int colNum, String base) {
String fieldName = this.getFieldName(colNum);
/* change the color of the job status field */
if (fieldName.equals(STATE_ATTR.getName())) {
try {
switch (getJobStatus(record)) {
case KILLED:
return "color:#d37a11;font-weight:bold;" + base;
case CANCELED:
case FAILED:
case IN_ERROR:
return "color:#c50000;font-weight:bold;" + base;
case RUNNING:
return "color:#176925;font-weight:bold;" + base;
case PENDING:
return "color:#1a8bba;" + base;
case STALLED:
case PAUSED:
return "font-weight:bold;" + base;
case FINISHED:
return base;
}
} catch (NullPointerException npe) {
return base;
}
}
return base;
}
protected Map<GridColumns, ListGridField> buildListGridField() {
Map<GridColumns, ListGridField> fields = super.buildListGridField();
alignCells(fields);
ListGridField idField = fields.get(ID_ATTR);
idField.setType(ListGridFieldType.INTEGER);
ListGridField stateField = fields.get(STATE_ATTR);
stateField.setSortNormalizer(sortStatusAndGroup());
ListGridField progressField = fields.get(PROGRESS_ATTR);
progressField.setType(ListGridFieldType.FLOAT);
progressField.setAlign(Alignment.CENTER);
progressField.setCellFormatter(new CellFormatter() {
public String format(Object value, ListGridRecord record, int rowNum, int colNum) {
int pw = getFieldWidth(PROGRESS_ATTR.getName());
float progress = 0;
if (value != null) {
progress = Float.parseFloat(value.toString());
}
int bx = new Double(Math.ceil(pw * progress)).intValue() - 601;
String progressUrl = SchedulerImages.instance.progressbar().getSafeUri().asString();
String style = "display:block; " + //
"border: 1px solid #acbac7; " + //
"background-image:url(" + progressUrl + ");" + //
"background-position:" + bx + "px 0px;" + //
"background-repeat: no-repeat;" + //
"background-color:#a7cef6";
Job job = JobRecord.getJob(record);
String progressCounters = job.getFinishedTasks() + " / " + job.getTotalTasks();
return "<div style='" + style + "'>" + progressCounters + "</div>";
}
});
ListGridField duration = fields.get(DURATION_ATTR);
duration.setCellFormatter(new CellFormatter() {
public String format(Object value, ListGridRecord record, int rowNum, int colNum) {
if (value != null) {
long l = Long.parseLong(value.toString());
return Job.formatDuration(l);
} else {
return "";
}
}
});
return fields;
}
private void alignCells(Map<GridColumns, ListGridField> fields) {
GridColumns[] columnsToAlignCenter =
new GridColumns[]{ ID_ATTR, STATE_ATTR, ISSUES_ATTR, USER_ATTR,
PROGRESS_ATTR, PRIORITY_ATTR, DURATION_ATTR};
for (GridColumns column : columnsToAlignCenter) {
ListGridField listGridField = fields.get(column);
listGridField.setAlign(Alignment.CENTER);
listGridField.setCellAlign(Alignment.CENTER);
}
}
/**
* A custom sort for status:
* - pending first
* - running, stalled, paused then
* - all other status (finished, killed,...)
*/
private SortNormalizer sortStatusAndGroup() {
return new SortNormalizer() {
@Override
public Object normalize(ListGridRecord record, String fieldName) {
String status = record.getAttribute(fieldName);
if (status.equals(JobStatus.PENDING.toString())) {
return 0;
} else if (status.equals(JobStatus.RUNNING.toString()) ||
status.equals(JobStatus.STALLED.toString()) ||
status.equals(JobStatus.PAUSED.toString())) {
return 1;
} else {
return 2;
}
}
};
}
protected void buildCellContextualMenu(Menu menu) {
boolean selPause = true; // ALL selected jobs are paused
boolean selRunning = true; // ALL selected jobs are running/stalled/pending
boolean selFinished = true; // ALL selected jobs are finished
boolean selPauseOrRunning = true; // ALL selected jobs are running/pending/paused/stalled
boolean selPausedOnError = false;
final ArrayList<String> ids = new ArrayList<String>(this.getSelectedRecords().length);
for (ListGridRecord rec : this.getSelectedRecords()) {
JobStatus status = getJobStatus(rec);
switch (status) {
case PENDING:
case STALLED:
selPause = false;
selFinished = false;
break;
case RUNNING:
selPause = false;
selFinished = false;
selPausedOnError = true;
break;
case PAUSED:
selFinished = false;
selPausedOnError = true;
selRunning = false;
break;
case IN_ERROR:
selFinished = false;
selPausedOnError = true;
selRunning = true;
break;
default:
selPauseOrRunning = false;
selRunning = false;
selPause = false;
}
ids.add(rec.getAttribute(ID_ATTR.getName()));
}
MenuItem pauseItem = new MenuItem("Pause",
SchedulerImages.instance.scheduler_pause_16().getSafeUri().asString());
pauseItem.addClickHandler(new ClickHandler() {
public void onClick(MenuItemClickEvent event) {
controller.pauseJobs(ids);
}
});
pauseItem.setEnabled(selRunning);
MenuItem restartOnErrorTaskItem = new MenuItem("Restart All In-Error Tasks",
SchedulerImages.instance.scheduler_resume_16().getSafeUri().asString());
restartOnErrorTaskItem.addClickHandler(new ClickHandler() {
public void onClick(MenuItemClickEvent event) {
controller.restartAllInErrorTasks(ids);
}
});
restartOnErrorTaskItem.setEnabled(selPausedOnError);
MenuItem resumeItem = new MenuItem("Resume",
SchedulerImages.instance.scheduler_resume_16().getSafeUri().asString());
resumeItem.addClickHandler(new ClickHandler() {
public void onClick(MenuItemClickEvent event) {
controller.resumeJobs(ids);
}
});
resumeItem.setEnabled(selPause);
MenuItem priorityItem = new MenuItem("Priority");
Menu priorityMenu = new Menu();
for (final JobPriority p : JobPriority.values()) {
MenuItem item = new MenuItem(p.toString());
if (!selPauseOrRunning) {
item.setEnabled(false);
} else {
item.addClickHandler(new ClickHandler() {
public void onClick(MenuItemClickEvent event) {
controller.setJobPriority(ids, p);
}
});
}
priorityMenu.addItem(item);
}
priorityItem.setSubmenu(priorityMenu);
MenuItem removeItem = new MenuItem("Remove",
SchedulerImages.instance.job_kill_16().getSafeUri().asString());
removeItem.addClickHandler(new ClickHandler() {
public void onClick(MenuItemClickEvent event) {
controller.removeJob(ids);
}
});
MenuItem killItem = new MenuItem("Kill",
SchedulerImages.instance.scheduler_kill_16().getSafeUri().asString());
killItem.addClickHandler(new ClickHandler() {
public void onClick(MenuItemClickEvent event) {
controller.killJob(ids);
}
});
killItem.setEnabled(selPauseOrRunning);
removeItem.setEnabled(selFinished);
menu.setItems(pauseItem, resumeItem, restartOnErrorTaskItem, priorityItem, removeItem, killItem);
}
private JobStatus getJobStatus(ListGridRecord rec) {
String jobStatusName = rec.getAttribute(STATE_ATTR.getName());
return JobStatus.from(jobStatusName);
}
}
| Highlight rows that contain an issue
| scheduler-portal/src/main/java/org/ow2/proactive_grid_cloud_portal/scheduler/client/view/grid/jobs/JobsListGrid.java | Highlight rows that contain an issue |
|
Java | lgpl-2.1 | 3d1e7f1e250b15d0c585a0ba7b9b0ce63c7273fd | 0 | deegree/deegree3,deegree/deegree3,deegree/deegree3,deegree/deegree3,deegree/deegree3 | //$HeadURL$
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2010 by:
- Department of Geography, University of Bonn -
and
- lat/lon GmbH -
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
Contact information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
e-mail: [email protected]
----------------------------------------------------------------------------*/
package org.deegree.services.wms.dynamic;
import static org.deegree.commons.jdbc.ConnectionManager.getConnection;
import static org.deegree.commons.utils.ArrayUtils.splitAsIntList;
import static org.deegree.feature.utils.DBUtils.findSrid;
import static org.deegree.services.wms.MapService.fillInheritedInformation;
import static org.slf4j.LoggerFactory.getLogger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import org.deegree.commons.annotations.LoggingNotes;
import org.deegree.commons.config.DeegreeWorkspace;
import org.deegree.commons.config.ResourceInitException;
import org.deegree.commons.utils.JDBCUtils;
import org.deegree.commons.utils.Pair;
import org.deegree.commons.utils.StringPair;
import org.deegree.feature.persistence.simplesql.SimpleSQLFeatureStore;
import org.deegree.services.wms.MapService;
import org.deegree.services.wms.model.layers.DynamicSQLLayer;
import org.deegree.services.wms.model.layers.Layer;
import org.deegree.style.se.parser.PostgreSQLReader;
import org.slf4j.Logger;
/**
* <code>PostGISLayerLoader</code>
*
* @author <a href="mailto:[email protected]">Andreas Schmitz</a>
* @author last edited by: $Author$
*
* @version $Revision$, $Date$
*/
@LoggingNotes(trace = "logs stack traces")
public class PostGISUpdater extends LayerUpdater {
private static final Logger LOG = getLogger( PostGISUpdater.class );
private String connId;
private final Layer parent;
private final MapService service;
private final HashMap<StringPair, DynamicSQLLayer> layers = new HashMap<StringPair, DynamicSQLLayer>();
private final HashMap<String, SimpleSQLFeatureStore> stores = new HashMap<String, SimpleSQLFeatureStore>();
private PostgreSQLReader styles;
private final String schema;
private final DeegreeWorkspace workspace;
/**
* @param connId
* @param parent
* @param service
* @param baseSystemId
* to resolve relative references in sld blobs
*/
public PostGISUpdater( String connId, String schema, Layer parent, MapService service, String baseSystemId,
DeegreeWorkspace workspace ) {
this.connId = connId;
this.workspace = workspace;
this.schema = schema == null ? "public" : schema;
this.parent = parent;
this.service = service;
this.styles = new PostgreSQLReader( connId, schema, baseSystemId );
}
/**
* @return the connection id
*/
public String getConnectionID() {
return connId;
}
private StringPair generateSQL( String connid, String sourcetable )
throws SQLException {
Connection conn = null;
ResultSet rs = null;
try {
conn = getConnection( connid );
String tableName = sourcetable;
String schema = this.schema;
if ( tableName.indexOf( "." ) != -1 ) {
schema = tableName.substring( 0, tableName.indexOf( "." ) );
}
if ( tableName.indexOf( "." ) != -1 ) {
tableName = tableName.substring( tableName.indexOf( "." ) + 1 );
}
int srid = findSrid( connid, tableName, schema );
rs = conn.getMetaData().getColumns( null, schema, tableName, null );
StringBuilder sb = new StringBuilder( "select " );
String geom = null;
while ( rs.next() ) {
String cn = rs.getString( "COLUMN_NAME" );
int tp = rs.getInt( "DATA_TYPE" );
switch ( tp ) {
case Types.OTHER:
sb.append( "asbinary(\"" ).append( cn ).append( "\") as \"" ).append( cn ).append( "\", " );
geom = cn;
break;
default:
sb.append( "\"" ).append( cn ).append( "\", " );
}
}
sb.delete( sb.length() - 2, sb.length() );
sb.append( " from " ).append( schema ).append( "." ).append( tableName ).append( " where \"" ).append( geom );
sb.append( "\" && st_geomfromtext(?, " ).append( srid ).append( ")" );
String sourcequery = sb.toString();
String bbox = "select astext(ST_Estimated_Extent('" + schema + "', '" + tableName + "', '" + geom
+ "')) as bbox";
return new StringPair( sourcequery, bbox );
} finally {
if ( conn != null ) {
conn.close();
}
if ( rs != null ) {
rs.close();
}
}
}
@Override
public boolean update() {
boolean changed = false;
Connection conn = null;
ResultSet rs = null;
PreparedStatement stmt = null;
LinkedList<Layer> toRemove = new LinkedList<Layer>();
for ( Layer l : parent.getChildren() ) {
if ( l.getName() != null && l instanceof DynamicSQLLayer ) {
toRemove.add( l );
service.layers.remove( l.getName() );
}
}
parent.getChildren().removeAll( toRemove );
try {
conn = getConnection( connId );
stmt = conn.prepareStatement( "select name, title, connectionid, sourcetable, sourcequery, symbolcodes, symbolfield, crs, namespace, bboxquery from "
+ schema + ".layers" );
rs = stmt.executeQuery();
while ( rs.next() ) {
String name = rs.getString( "name" );
// check for existing layers
if ( name != null ) {
Layer l = service.getLayer( name );
if ( l != null && l.getParent() == parent ) {
continue;
}
}
String title = rs.getString( "title" );
if ( title == null ) {
title = name;
}
String connectionid = rs.getString( "connectionid" );
if ( connectionid == null ) {
connectionid = connId;
}
String sourcetable = rs.getString( "sourcetable" );
String sourcequery = rs.getString( "sourcequery" );
String symbolcodes = rs.getString( "symbolcodes" );
List<Integer> codes = symbolcodes == null ? Collections.<Integer> emptyList()
: splitAsIntList( symbolcodes, "," );
String symbolfield = rs.getString( "symbolfield" );
String crs = rs.getString( "crs" );
String namespace = rs.getString( "namespace" );
namespace = namespace == null ? "http://www.deegree.org/app" : namespace;
String bbox = rs.getString( "bboxquery" );
if ( sourcequery == null && sourcetable == null ) {
LOG.debug( "Skipping layer '{}' because no data source was defined.", title );
continue;
}
if ( sourcequery == null ) {
StringPair queries = generateSQL( connectionid, sourcetable );
sourcequery = queries.first;
if ( bbox == null ) {
bbox = queries.second;
}
}
SimpleSQLFeatureStore ds = stores.get( sourcequery + crs + namespace );
if ( ds == null ) {
changed = true;
layers.remove( new StringPair( name, title ) );
ds = new SimpleSQLFeatureStore( connectionid, crs, sourcequery, name == null ? title : name,
namespace, "app", bbox,
Collections.<Pair<Integer, String>> emptyList() );
try {
ds.init( workspace );
} catch ( ResourceInitException e ) {
LOG.info( "Data source of layer '{}' could not be initialized: '{}'.", title,
e.getLocalizedMessage() );
LOG.trace( "Stack trace:", e );
continue;
}
stores.put( sourcequery + crs + namespace, ds );
}
if ( name != null ) {
LOG.debug( "Creating new requestable layer with name '{}', title '{}'.", name, title );
} else {
LOG.debug( "Creating new unrequestable layer with title '{}'.", title );
}
DynamicSQLLayer layer = layers.get( new StringPair( name, title ) );
if ( layer == null ) {
changed = true;
layer = new DynamicSQLLayer( service, name, title, parent, ds, styles, codes, symbolfield );
}
if ( name != null ) {
service.layers.put( name, layer );
}
parent.getChildren().add( layer );
}
fillInheritedInformation( parent, parent.getSrs() );
changed |= cleanup( parent, service );
} catch ( SQLException e ) {
LOG.warn( "Database with connection id '{}' is not available at the moment.", connId );
LOG.trace( "Stack trace:", e );
} finally {
JDBCUtils.close( rs, stmt, conn, LOG );
}
return changed;
}
}
| deegree-services/deegree-services-wms/src/main/java/org/deegree/services/wms/dynamic/PostGISUpdater.java | //$HeadURL$
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2010 by:
- Department of Geography, University of Bonn -
and
- lat/lon GmbH -
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
Contact information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
e-mail: [email protected]
----------------------------------------------------------------------------*/
package org.deegree.services.wms.dynamic;
import static org.deegree.commons.jdbc.ConnectionManager.getConnection;
import static org.deegree.commons.utils.ArrayUtils.splitAsIntList;
import static org.deegree.feature.utils.DBUtils.findSrid;
import static org.deegree.services.wms.MapService.fillInheritedInformation;
import static org.slf4j.LoggerFactory.getLogger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import org.deegree.commons.annotations.LoggingNotes;
import org.deegree.commons.config.DeegreeWorkspace;
import org.deegree.commons.config.ResourceInitException;
import org.deegree.commons.utils.JDBCUtils;
import org.deegree.commons.utils.Pair;
import org.deegree.commons.utils.StringPair;
import org.deegree.feature.persistence.simplesql.SimpleSQLFeatureStore;
import org.deegree.services.wms.MapService;
import org.deegree.services.wms.model.layers.DynamicSQLLayer;
import org.deegree.services.wms.model.layers.Layer;
import org.deegree.style.se.parser.PostgreSQLReader;
import org.slf4j.Logger;
/**
* <code>PostGISLayerLoader</code>
*
* @author <a href="mailto:[email protected]">Andreas Schmitz</a>
* @author last edited by: $Author$
*
* @version $Revision$, $Date$
*/
@LoggingNotes(trace = "logs stack traces")
public class PostGISUpdater extends LayerUpdater {
private static final Logger LOG = getLogger( PostGISUpdater.class );
private String connId;
private final Layer parent;
private final MapService service;
private final HashMap<StringPair, DynamicSQLLayer> layers = new HashMap<StringPair, DynamicSQLLayer>();
private final HashMap<String, SimpleSQLFeatureStore> stores = new HashMap<String, SimpleSQLFeatureStore>();
private PostgreSQLReader styles;
private final String schema;
private final DeegreeWorkspace workspace;
/**
* @param connId
* @param parent
* @param service
* @param baseSystemId
* to resolve relative references in sld blobs
*/
public PostGISUpdater( String connId, String schema, Layer parent, MapService service, String baseSystemId,
DeegreeWorkspace workspace ) {
this.connId = connId;
this.workspace = workspace;
this.schema = schema == null ? "public" : schema;
this.parent = parent;
this.service = service;
this.styles = new PostgreSQLReader( connId, schema, baseSystemId );
}
/**
* @return the connection id
*/
public String getConnectionID() {
return connId;
}
private StringPair generateSQL( String connid, String sourcetable )
throws SQLException {
Connection conn = null;
ResultSet rs = null;
try {
conn = getConnection( connid );
String tableName = sourcetable;
String schema = this.schema;
if ( tableName.indexOf( "." ) != -1 ) {
schema = tableName.substring( 0, tableName.indexOf( "." ) );
}
if ( tableName.indexOf( "." ) != -1 ) {
tableName = tableName.substring( tableName.indexOf( "." ) + 1 );
}
int srid = findSrid( connid, tableName, schema );
rs = conn.getMetaData().getColumns( null, schema, tableName, null );
StringBuilder sb = new StringBuilder( "select " );
String geom = null;
while ( rs.next() ) {
String cn = rs.getString( "COLUMN_NAME" );
int tp = rs.getInt( "DATA_TYPE" );
switch ( tp ) {
case Types.OTHER:
sb.append( "asbinary(\"" ).append( cn ).append( "\") as \"" ).append( cn ).append( "\", " );
geom = cn;
break;
default:
sb.append( "\"" ).append( cn ).append( "\", " );
}
}
sb.delete( sb.length() - 2, sb.length() );
sb.append( " from " ).append( schema ).append( "." ).append( tableName ).append( " where \"" ).append( geom );
sb.append( "\" && st_geomfromtext(?, " ).append( srid ).append( ")" );
String sourcequery = sb.toString();
String bbox = "select astext(ST_Estimated_Extent('" + schema + "', '" + tableName + "', '" + geom
+ "')) as bbox";
return new StringPair( sourcequery, bbox );
} finally {
if ( conn != null ) {
conn.close();
}
if ( rs != null ) {
rs.close();
}
}
}
@Override
public boolean update() {
boolean changed = false;
Connection conn = null;
ResultSet rs = null;
PreparedStatement stmt = null;
LinkedList<Layer> toRemove = new LinkedList<Layer>();
for ( Layer l : parent.getChildren() ) {
if ( l.getName() != null && l instanceof DynamicSQLLayer ) {
toRemove.add( l );
service.layers.remove( l.getName() );
}
}
parent.getChildren().removeAll( toRemove );
try {
conn = getConnection( connId );
stmt = conn.prepareStatement( "select name, title, connectionid, sourcetable, sourcequery, symbolcodes, symbolfield, crs, namespace, bboxquery from "
+ schema + ".layers" );
rs = stmt.executeQuery();
while ( rs.next() ) {
String name = rs.getString( "name" );
// check for existing layers
if ( name != null ) {
Layer l = service.getLayer( name );
if ( l != null && l.getParent() == parent ) {
continue;
}
}
String title = rs.getString( "title" );
if ( title == null ) {
title = name;
}
String connectionid = rs.getString( "connectionid" );
if ( connectionid == null ) {
connectionid = connId;
}
String sourcetable = rs.getString( "sourcetable" );
String sourcequery = rs.getString( "sourcequery" );
String symbolcodes = rs.getString( "symbolcodes" );
List<Integer> codes = symbolcodes == null ? Collections.<Integer> emptyList()
: splitAsIntList( symbolcodes, "," );
String symbolfield = rs.getString( "symbolfield" );
String crs = rs.getString( "crs" );
String namespace = rs.getString( "namespace" );
namespace = namespace == null ? "http://www.deegree.org/app" : namespace;
String bbox = rs.getString( "bboxquery" );
if ( sourcequery == null && sourcetable == null ) {
LOG.debug( "Skipping layer '{}' because no data source was defined.", title );
continue;
}
if ( sourcequery == null ) {
StringPair queries = generateSQL( connectionid, sourcetable );
sourcequery = queries.first;
bbox = queries.second;
}
SimpleSQLFeatureStore ds = stores.get( sourcequery + crs + namespace );
if ( ds == null ) {
changed = true;
layers.remove( new StringPair( name, title ) );
ds = new SimpleSQLFeatureStore( connectionid, crs, sourcequery, name == null ? title : name,
namespace, "app", bbox,
Collections.<Pair<Integer, String>> emptyList() );
try {
ds.init( workspace );
} catch ( ResourceInitException e ) {
LOG.info( "Data source of layer '{}' could not be initialized: '{}'.", title,
e.getLocalizedMessage() );
LOG.trace( "Stack trace:", e );
continue;
}
stores.put( sourcequery + crs + namespace, ds );
}
if ( name != null ) {
LOG.debug( "Creating new requestable layer with name '{}', title '{}'.", name, title );
} else {
LOG.debug( "Creating new unrequestable layer with title '{}'.", title );
}
DynamicSQLLayer layer = layers.get( new StringPair( name, title ) );
if ( layer == null ) {
changed = true;
layer = new DynamicSQLLayer( service, name, title, parent, ds, styles, codes, symbolfield );
}
if ( name != null ) {
service.layers.put( name, layer );
}
parent.getChildren().add( layer );
}
fillInheritedInformation( parent, parent.getSrs() );
changed |= cleanup( parent, service );
} catch ( SQLException e ) {
LOG.warn( "Database with connection id '{}' is not available at the moment.", connId );
LOG.trace( "Stack trace:", e );
} finally {
JDBCUtils.close( rs, stmt, conn, LOG );
}
return changed;
}
}
| allow overriding of bbox query if sourcequery is not set
| deegree-services/deegree-services-wms/src/main/java/org/deegree/services/wms/dynamic/PostGISUpdater.java | allow overriding of bbox query if sourcequery is not set |
|
Java | lgpl-2.1 | 5af5b4c581452726ca4a30d102a69da635f7ef7e | 0 | zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform | package org.fedorahosted.flies.core.action;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Query;
import org.fedorahosted.flies.core.model.HCommunity;
import org.hibernate.search.jpa.FullTextEntityManager;
import org.hibernate.search.jpa.FullTextQuery;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.log.Log;
@Name("communitySearch")
@Scope(ScopeType.EVENT)
@AutoCreate
public class CommunitySearch {
@Logger
private Log log;
int pageSize = 5;
boolean hasMore = false;
private String searchQuery;
private List<HCommunity> searchResults;
private int currentPage = 0;
private int resultSize;
@In
EntityManager entityManager;
public String getSearchQuery() {
return searchQuery;
}
public void setSearchQuery(String searchQuery) {
this.searchQuery = searchQuery;
}
public List<HCommunity> getSearchResults() {
return searchResults;
}
public void setSearchResults(List<HCommunity> communities) {
this.searchResults = communities;
}
public int getResultSize () {
return resultSize;
}
public void setResultSize(int value) {
this.resultSize = value;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int page) {
this.currentPage = page;
}
public void doSearch() {
updateResults();
}
public void nextPage() {
if (!lastPage()) {
currentPage++;
}
}
public void prevPage() {
if (!firstPage()) {
currentPage--;
}
}
public boolean lastPage() {
return ( searchResults != null ) && !hasMore;
}
public boolean firstPage() {
return ( searchResults != null ) && ( currentPage == 0 );
}
private void updateResults() {
FullTextQuery query;
try {
query = searchQuery(searchQuery);
} catch (ParseException e) {
log.warn("Can't parse query '"+searchQuery+"'");
return;
}
resultSize = query.getResultSize();
List<HCommunity> items = query
.setMaxResults(pageSize + 1)
.setFirstResult(pageSize * currentPage)
.getResultList();
if (items.size() > pageSize) {
searchResults = new ArrayList(items.subList(0, pageSize));
hasMore = true;
} else {
searchResults = items;
hasMore = false;
}
}
private FullTextQuery searchQuery(String searchQuery) throws ParseException
{
String[] communityFields = {"name", "description"};
QueryParser parser = new MultiFieldQueryParser(communityFields, new StandardAnalyzer());
parser.setAllowLeadingWildcard(true);
Query luceneQuery = parser.parse(searchQuery);
return ( (FullTextEntityManager) entityManager ).createFullTextQuery(luceneQuery, HCommunity.class);
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
}
| flies-war/src/main/java/org/fedorahosted/flies/core/action/CommunitySearch.java | package org.fedorahosted.flies.core.action;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Query;
import org.fedorahosted.flies.core.model.HCommunity;
import org.hibernate.search.jpa.FullTextEntityManager;
import org.hibernate.search.jpa.FullTextQuery;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
@Name("communitySearch")
@Scope(ScopeType.EVENT)
@AutoCreate
public class CommunitySearch {
int pageSize = 5;
boolean hasMore = false;
private String searchQuery;
private List<HCommunity> searchResults;
private int currentPage = 0;
private int resultSize;
@In
EntityManager entityManager;
public String getSearchQuery() {
return searchQuery;
}
public void setSearchQuery(String searchQuery) {
this.searchQuery = searchQuery;
}
public List<HCommunity> getSearchResults() {
return searchResults;
}
public void setSearchResults(List<HCommunity> communities) {
this.searchResults = communities;
}
public int getResultSize () {
return resultSize;
}
public void setResultSize(int value) {
this.resultSize = value;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int page) {
this.currentPage = page;
}
public void doSearch() {
updateResults();
}
public void nextPage() {
if (!lastPage()) {
currentPage++;
}
}
public void prevPage() {
if (!firstPage()) {
currentPage--;
}
}
public boolean lastPage() {
return ( searchResults != null ) && !hasMore;
}
public boolean firstPage() {
return ( searchResults != null ) && ( currentPage == 0 );
}
private void updateResults() {
FullTextQuery query;
try {
query = searchQuery(searchQuery);
} catch (ParseException pe) {
return;
}
resultSize = query.getResultSize();
List<HCommunity> items = query
.setMaxResults(pageSize + 1)
.setFirstResult(pageSize * currentPage)
.getResultList();
if (items.size() > pageSize) {
searchResults = new ArrayList(items.subList(0, pageSize));
hasMore = true;
} else {
searchResults = items;
hasMore = false;
}
}
private FullTextQuery searchQuery(String searchQuery) throws ParseException
{
String[] communityFields = {"name", "description"};
QueryParser parser = new MultiFieldQueryParser(communityFields, new StandardAnalyzer());
parser.setAllowLeadingWildcard(true);
Query luceneQuery = parser.parse(searchQuery);
return ( (FullTextEntityManager) entityManager ).createFullTextQuery(luceneQuery, HCommunity.class);
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
}
| Added WARN logging for dodgy search strings
| flies-war/src/main/java/org/fedorahosted/flies/core/action/CommunitySearch.java | Added WARN logging for dodgy search strings |
|
Java | apache-2.0 | 07f8812957cee1257c931a88ade86a839973e730 | 0 | RanjithKumar5550/RanMifos,Vishwa1311/incubator-fineract,RanjithKumar5550/RanMifos,Vishwa1311/incubator-fineract,Vishwa1311/incubator-fineract,RanjithKumar5550/RanMifos | /**
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.mifosplatform.portfolio.client.domain;
import org.mifosplatform.organisation.office.domain.OrganisationCurrencyRepositoryWrapper;
import org.mifosplatform.portfolio.charge.exception.ChargeNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository
public class ClientChargeRepositoryWrapper {
private final ClientChargeRepository repository;
private final OrganisationCurrencyRepositoryWrapper organisationCurrencyRepository;
@Autowired
public ClientChargeRepositoryWrapper(final ClientChargeRepository repository,
final OrganisationCurrencyRepositoryWrapper organisationCurrencyRepositoryWrapper) {
this.repository = repository;
this.organisationCurrencyRepository = organisationCurrencyRepositoryWrapper;
}
public ClientCharge findOneWithNotFoundDetection(final Long id) {
final ClientCharge clientCharge = this.repository.findOne(id);
if (clientCharge == null) { throw new ChargeNotFoundException(id); }
// enrich Client charge with details of Organizational currency
clientCharge.setCurrency(organisationCurrencyRepository.findOneWithNotFoundDetection(clientCharge.getCharge().getCurrencyCode()));
return clientCharge;
}
public void save(final ClientCharge clientCharge) {
this.repository.save(clientCharge);
}
public void saveAndFlush(final ClientCharge clientCharge) {
this.repository.saveAndFlush(clientCharge);
}
public void delete(final ClientCharge clientCharge) {
this.repository.delete(clientCharge);
this.repository.flush();
}
}
| mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/domain/ClientChargeRepositoryWrapper.java | /**
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.mifosplatform.portfolio.client.domain;
import org.mifosplatform.organisation.office.domain.OrganisationCurrencyRepositoryWrapper;
import org.mifosplatform.portfolio.charge.exception.ChargeNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository
public class ClientChargeRepositoryWrapper {
private final ClientChargeRepository repository;
private final OrganisationCurrencyRepositoryWrapper organisationCurrencyRepository;
@Autowired
public ClientChargeRepositoryWrapper(final ClientChargeRepository repository,
final OrganisationCurrencyRepositoryWrapper organisationCurrencyRepositoryWrapper) {
this.repository = repository;
this.organisationCurrencyRepository = organisationCurrencyRepositoryWrapper;
}
public ClientCharge findOneWithNotFoundDetection(final Long id) {
final ClientCharge clientCharge = this.repository.findOne(id);
if (clientCharge == null) { throw new ChargeNotFoundException(id); }
// enrich Client charge with details of Organizational currency
clientCharge.setCurrency(organisationCurrencyRepository.findOneWithNotFoundDetection(clientCharge.getCharge().getCurrencyCode()));
return clientCharge;
}
public void save(final ClientCharge clientCharge) {
this.repository.save(clientCharge);
}
public void saveAndFlush(final ClientCharge clientCharge) {
this.repository.saveAndFlush(clientCharge);
}
public void delete(final ClientCharge clientCharge) {
this.repository.delete(clientCharge);
}
}
| fixing transaction scope for client charges deletion
| mifosng-provider/src/main/java/org/mifosplatform/portfolio/client/domain/ClientChargeRepositoryWrapper.java | fixing transaction scope for client charges deletion |
|
Java | apache-2.0 | 4772487de8a31a87c5a859956c494d08d939e404 | 0 | jandppw/ppwcode-recovered-from-google-code,jandockx/ppwcode-recovered-from-google-code,jandppw/ppwcode-recovered-from-google-code,jandockx/ppwcode-recovered-from-google-code,jandppw/ppwcode-recovered-from-google-code,jandockx/ppwcode-recovered-from-google-code,jandockx/ppwcode-recovered-from-google-code,jandppw/ppwcode-recovered-from-google-code,jandockx/ppwcode-recovered-from-google-code,jandppw/ppwcode-recovered-from-google-code,jandockx/ppwcode-recovered-from-google-code,jandppw/ppwcode-recovered-from-google-code | java/vernacular/value/trunk/src/main/java/org/ppwcode/vernacular/value_III/AbstractPropertyEditorConverter.java | /*<license>
Copyright 2004 - $Date$ by PeopleWare n.v..
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.
</license>*/
package org.ppwcode.vernacular.value_III;
import java.beans.PropertyEditor;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* <p>Support for converters based on {@link PropertyEditor PropertyEditors}.
* Derive from this class and implement {@link #getPropertyEditor(FacesContext, UIComponent)}.
* Then add an entry in <kbd>faces-config.xml</kbd> to map the target types
* to the correct converter class descendant.</p>
* <p>Often, there are 2 String representations of value objects:</p>
* <ul>
* <li>a programmatic representation, e.g., to be used as values in a HTML
* select option tag; and</li>
* <li>a label, or display name, to be presented to end users.</li>
* </ul>
* <p>When {@link #isLabelRepresentation()} is <code>true</code>, this convertor's
* {@link #getAsString(FacesContext, UIComponent, Object)} method returns the
* label. If {@link #isLabelRepresentation()} is <code>false</code>
* (the default), the {@link #getAsString(FacesContext, UIComponent, Object)}
* method returns the programmatic representation. This only works if the
* property editor found for the type of the value to be converted</p>
* <p><strong>Note that the {@link #getAsObject(FacesContext, UIComponent, String)}
* method only works when {@link #isLabelRepresentation()} is <code>false</code>:
* it is often impossible to convert a human-readable label to an
* object.</strong></p>
*
* @author Wim Lambrechts
* @author Jan Dockx
* @author PeopleWare n.v.
*
* @invar getPropertyEditor() != null;
*/
public abstract class AbstractPropertyEditorConverter implements Converter {
/*<section name="Meta Information">*/
//------------------------------------------------------------------
/** {@value} */
public static final String CVS_REVISION = "$Revision$"; //$NON-NLS-1$
/** {@value} */
public static final String CVS_DATE = "$Date$"; //$NON-NLS-1$
/** {@value} */
public static final String CVS_STATE = "$State$"; //$NON-NLS-1$
/** {@value} */
public static final String CVS_TAG = "$Name$"; //$NON-NLS-1$
/*</section>*/
private static final Log LOG =
LogFactory.getLog(AbstractPropertyEditorConverter.class);
/**
* Default constructor.
*/
protected AbstractPropertyEditorConverter() {
LOG.debug("creation of new ...PropertyEditorConverter ("
+ getClass().getName() + ")");
}
/**
* @pre context != null;
* @pre component != null;
* @return ; the result of the conversion of <code>value</code>
* to an Object by {@link #getPropertyEditor(FacesContext, UIComponent)}
* @throws ConverterException
* getPropertyEditor(context, component);
* @throws ConverterException
* getPropertyEditor(context, component).getValue()#IllegalArgumentException;
* @throws ConverterException
* isLabelRepresenation();
*/
public final Object getAsObject(final FacesContext context,
final UIComponent component, final String value) throws ConverterException {
assert context != null;
assert component != null;
LOG.debug("request to convert \"" + value + "\" to object for "
+ component + "(id = " + component.getClientId(context) + ")");
if (isLabelRepresentation()) {
LOG.debug("Cannot convert from String to Object in label-representation-mode");
throw new ConverterException("Cannot convert from String to Object in "
+ "label-representation-mode");
}
try {
PropertyEditor editor = getPropertyEditor(context, component); // ConverterException
LOG.debug("retrieved PropertyEditor: " + editor);
editor.setAsText(value);
Object result = editor.getValue();
if (LOG.isDebugEnabled()) {
LOG.debug("convertion result: " + result);
}
return result;
}
catch (IllegalArgumentException iae) {
// MUDO (jand) good FacesMessage, i18n; find out what happens if this fails
throw new ConverterException(iae);
}
}
/**
* @pre context != null;
* @pre component != null;
* @return ; the result of the conversion of <code>value</code>
* to a String by {@link #getPropertyEditor(FacesContext, UIComponent)}
* @throws ConverterException
* getPropertyEditor(context, component);
*/
public final String getAsString(final FacesContext context,
final UIComponent component, final Object value) throws ConverterException {
assert context != null;
assert component != null;
if (LOG.isDebugEnabled()) {
LOG.debug("request to convert object \"" + value + "\" to String for "
+ component + "(id = " + component.getClientId(context) + ")");
}
PropertyEditor editor = getPropertyEditor(context, component); // ConverterException
LOG.debug("retrieved PropertyEditor: " + editor);
editor.setValue(value);
String result = editor.getAsText();
LOG.debug("convertion result: " + result);
return result;
}
/**
* @basic
* @init false;
*/
public final boolean isLabelRepresentation() {
return $labelRepresentation;
}
/**
* @post new.isLabelRepresentation() == labelRepresentation;
*/
public final void setLabelRepresentation(final boolean labelRepresentation) {
$labelRepresentation = labelRepresentation;
}
private boolean $labelRepresentation;
/**
* Subclasses need to implement this method. Return a {@link PropertyEditor}
* for the target type of this converter. This method is not allowed to
* return <code>null</code>.
*
* @pre context != null;
* @pre component != null;
* @basic
* @throws ConverterException
* true;
*/
protected abstract PropertyEditor getPropertyEditor(final FacesContext context,
final UIComponent component)
throws ConverterException;
}
| technology dependent stuff needs to be in separate package for clarity | java/vernacular/value/trunk/src/main/java/org/ppwcode/vernacular/value_III/AbstractPropertyEditorConverter.java | technology dependent stuff needs to be in separate package for clarity |
||
Java | apache-2.0 | bab16568d4b408fb821f74df0486d1ff96c38755 | 0 | kalaspuffar/pdfbox,kalaspuffar/pdfbox,apache/pdfbox,apache/pdfbox | /*
* Copyright 2018 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.pdfbox.pdmodel.interactive.annotation.handlers;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.fontbox.util.Charsets;
import org.apache.pdfbox.contentstream.operator.Operator;
import org.apache.pdfbox.cos.COSArray;
import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.cos.COSNumber;
import org.apache.pdfbox.cos.COSObject;
import org.apache.pdfbox.pdfparser.PDFStreamParser;
import org.apache.pdfbox.pdmodel.PDAppearanceContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.graphics.color.PDColor;
import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceCMYK;
import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceGray;
import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceRGB;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationFreeText;
import static org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationLine.LE_NONE;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceStream;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDBorderEffectDictionary;
import org.apache.pdfbox.pdmodel.interactive.annotation.layout.AppearanceStyle;
import org.apache.pdfbox.pdmodel.interactive.annotation.layout.PlainText;
import org.apache.pdfbox.pdmodel.interactive.annotation.layout.PlainTextFormatter;
import org.apache.pdfbox.util.Matrix;
public class PDFreeTextAppearanceHandler extends PDAbstractAppearanceHandler
{
private static final Log LOG = LogFactory.getLog(PDFreeTextAppearanceHandler.class);
private static final Pattern COLOR_PATTERN =
Pattern.compile(".*color\\:\\s*\\#([0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]).*");
public PDFreeTextAppearanceHandler(PDAnnotation annotation)
{
super(annotation);
}
@Override
public void generateAppearanceStreams()
{
generateNormalAppearance();
generateRolloverAppearance();
generateDownAppearance();
}
@Override
public void generateNormalAppearance()
{
PDAnnotationFreeText annotation = (PDAnnotationFreeText) getAnnotation();
float[] pathsArray = new float[0];
if (PDAnnotationFreeText.IT_FREE_TEXT_CALLOUT.equals(annotation.getIntent()))
{
pathsArray = annotation.getCallout();
if (pathsArray == null || pathsArray.length != 4 && pathsArray.length != 6)
{
pathsArray = new float[0];
}
}
AnnotationBorder ab = AnnotationBorder.getAnnotationBorder(annotation, annotation.getBorderStyle());
try (PDAppearanceContentStream cs = getNormalAppearanceAsContentStream(true))
{
// The fill color is the /C entry, there is no /IC entry defined
boolean hasBackground = cs.setNonStrokingColorOnDemand(annotation.getColor());
setOpacity(cs, annotation.getConstantOpacity());
// Adobe uses the last non stroking color from /DA as stroking color!
// But if there is a color in /DS, then that one is used for text.
PDColor strokingColor = extractNonStrokingColor(annotation);
boolean hasStroke = cs.setStrokingColorOnDemand(strokingColor);
PDColor textColor = strokingColor;
String defaultStyleString = annotation.getDefaultStyleString();
if (defaultStyleString != null)
{
Matcher m = COLOR_PATTERN.matcher(defaultStyleString);
if (m.find())
{
int color = Integer.parseInt(m.group(1), 16);
float r = ((color >> 16) & 0xFF) / 255f;
float g = ((color >> 8) & 0xFF) / 255f;
float b = (color & 0xFF) / 255f;
textColor = new PDColor( new float[] { r, g, b }, PDDeviceRGB.INSTANCE);
}
}
if (ab.dashArray != null)
{
cs.setLineDashPattern(ab.dashArray, 0);
}
cs.setLineWidth(ab.width);
// draw callout line(s)
// must be done before retangle paint to avoid a line cutting through cloud
// see CTAN-example-Annotations.pdf
for (int i = 0; i < pathsArray.length / 2; ++i)
{
float x = pathsArray[i * 2];
float y = pathsArray[i * 2 + 1];
if (i == 0)
{
if (SHORT_STYLES.contains(annotation.getLineEndingStyle()))
{
// modify coordinate to shorten the segment
// https://stackoverflow.com/questions/7740507/extend-a-line-segment-a-specific-distance
float x1 = pathsArray[2];
float y1 = pathsArray[3];
float len = (float) (Math.sqrt(Math.pow(x - x1, 2) + Math.pow(y - y1, 2)));
if (Float.compare(len, 0) != 0)
{
x += (x1 - x) / len * ab.width;
y += (y1 - y) / len * ab.width;
}
}
cs.moveTo(x, y);
}
else
{
cs.lineTo(x, y);
}
}
if (pathsArray.length > 0)
{
cs.stroke();
}
// paint the styles here and after line(s) draw, to avoid line crossing a filled shape
if (PDAnnotationFreeText.IT_FREE_TEXT_CALLOUT.equals(annotation.getIntent())
// check only needed to avoid q cm Q if LE_NONE
&& !LE_NONE.equals(annotation.getLineEndingStyle())
&& pathsArray.length >= 4)
{
float x2 = pathsArray[2];
float y2 = pathsArray[3];
float x1 = pathsArray[0];
float y1 = pathsArray[1];
cs.saveGraphicsState();
if (ANGLED_STYLES.contains(annotation.getLineEndingStyle()))
{
// do a transform so that first "arm" is imagined flat,
// like in line handler.
// The alternative would be to apply the transform to the
// LE shape coordinates directly, which would be more work
// and produce code difficult to understand
double angle = Math.atan2(y2 - y1, x2 - x1);
cs.transform(Matrix.getRotateInstance(angle, x1, y1));
}
else
{
cs.transform(Matrix.getTranslateInstance(x1, y1));
}
drawStyle(annotation.getLineEndingStyle(), cs, 0, 0, ab.width, hasStroke, hasBackground, false);
cs.restoreGraphicsState();
}
PDRectangle borderBox;
PDBorderEffectDictionary borderEffect = annotation.getBorderEffect();
if (borderEffect != null && borderEffect.getStyle().equals(PDBorderEffectDictionary.STYLE_CLOUDY))
{
// Adobe draws the text with the original rectangle in mind.
// but if there is an /RD, then writing area get smaller.
// do this here because /RD is overwritten in a few lines
borderBox = applyRectDifferences(getRectangle(), annotation.getRectDifferences());
//TODO this segment was copied from square handler. Refactor?
CloudyBorder cloudyBorder = new CloudyBorder(cs,
borderEffect.getIntensity(), ab.width, getRectangle());
cloudyBorder.createCloudyRectangle(annotation.getRectDifference());
annotation.setRectangle(cloudyBorder.getRectangle());
annotation.setRectDifference(cloudyBorder.getRectDifference());
PDAppearanceStream appearanceStream = annotation.getNormalAppearanceStream();
appearanceStream.setBBox(cloudyBorder.getBBox());
appearanceStream.setMatrix(cloudyBorder.getMatrix());
}
else
{
// handle the border box
//
// There are two options. The handling is not part of the PDF specification but
// implementation specific to Adobe Reader
// - if /RD is set the border box is the /Rect entry inset by the respective
// border difference.
// - if /RD is not set then we don't touch /RD etc because Adobe doesn't either.
borderBox = applyRectDifferences(getRectangle(), annotation.getRectDifferences());
annotation.getNormalAppearanceStream().setBBox(borderBox);
// note that borderBox is not modified
PDRectangle paddedRectangle = getPaddedRectangle(borderBox, ab.width / 2);
cs.addRect(paddedRectangle.getLowerLeftX(), paddedRectangle.getLowerLeftY(),
paddedRectangle.getWidth(), paddedRectangle.getHeight());
}
cs.drawShape(ab.width, hasStroke, hasBackground);
// rotation is an undocumented feature, but Adobe uses it. Examples can be found
// in pdf_commenting_new.pdf file, page 3.
int rotation = annotation.getCOSObject().getInt(COSName.ROTATE, 0);
cs.transform(Matrix.getRotateInstance(Math.toRadians(rotation), 0, 0));
float xOffset;
float yOffset;
float width = rotation == 90 || rotation == 270 ? borderBox.getHeight() : borderBox.getWidth();
// strategy to write formatted text is somewhat inspired by
// AppearanceGeneratorHelper.insertGeneratedAppearance()
PDFont font = PDType1Font.HELVETICA;
float clipY;
float clipWidth = width - ab.width * 4;
float clipHeight = rotation == 90 || rotation == 270 ?
borderBox.getWidth() - ab.width * 4 : borderBox.getHeight() - ab.width * 4;
float fontSize = extractFontSize(annotation);
// value used by Adobe, no idea where it comes from, actual font bbox max y is 0.931
// gathered by creating an annotation with width 0.
float yDelta = 0.7896f;
switch (rotation)
{
case 180:
xOffset = - borderBox.getUpperRightX() + ab.width * 2;
yOffset = - borderBox.getLowerLeftY() - ab.width * 2 - yDelta * fontSize;
clipY = - borderBox.getUpperRightY() + ab.width * 2;
break;
case 90:
xOffset = borderBox.getLowerLeftY() + ab.width * 2;
yOffset = - borderBox.getLowerLeftX() - ab.width * 2 - yDelta * fontSize;
clipY = - borderBox.getUpperRightX() + ab.width * 2;
break;
case 270:
xOffset = - borderBox.getUpperRightY() + ab.width * 2;
yOffset = borderBox.getUpperRightX() - ab.width * 2 - yDelta * fontSize;
clipY = borderBox.getLowerLeftX() + ab.width * 2;
break;
case 0:
default:
xOffset = borderBox.getLowerLeftX() + ab.width * 2;
yOffset = borderBox.getUpperRightY() - ab.width * 2 - yDelta * fontSize;
clipY = borderBox.getLowerLeftY() + ab.width * 2;
break;
}
// clip writing area
cs.addRect(xOffset, clipY, clipWidth, clipHeight);
cs.clip();
cs.beginText();
cs.setFont(font, fontSize);
cs.setNonStrokingColor(textColor.getComponents());
AppearanceStyle appearanceStyle = new AppearanceStyle();
appearanceStyle.setFont(font);
appearanceStyle.setFontSize(fontSize);
PlainTextFormatter formatter = new PlainTextFormatter.Builder(cs)
.style(appearanceStyle)
.text(new PlainText(annotation.getContents()))
.width(width - ab.width * 4)
.wrapLines(true)
.initialOffset(xOffset, yOffset)
// Adobe ignores the /Q
//.textAlign(annotation.getQ())
.build();
try
{
formatter.format();
}
catch (IllegalArgumentException ex)
{
throw new IOException(ex);
}
cs.endText();
if (pathsArray.length > 0)
{
PDRectangle rect = getRectangle();
// Adjust rectangle
// important to do this after the rectangle has been painted, because the
// final rectangle will be bigger due to callout
// CTAN-example-Annotations.pdf p1
//TODO in a class structure this should be overridable
float minX = Float.MAX_VALUE;
float minY = Float.MAX_VALUE;
float maxX = Float.MIN_VALUE;
float maxY = Float.MIN_VALUE;
for (int i = 0; i < pathsArray.length / 2; ++i)
{
float x = pathsArray[i * 2];
float y = pathsArray[i * 2 + 1];
minX = Math.min(minX, x);
minY = Math.min(minY, y);
maxX = Math.max(maxX, x);
maxY = Math.max(maxY, y);
}
// arrow length is 9 * width at about 30° => 10 * width seems to be enough
rect.setLowerLeftX(Math.min(minX - ab.width * 10, rect.getLowerLeftX()));
rect.setLowerLeftY(Math.min(minY - ab.width * 10, rect.getLowerLeftY()));
rect.setUpperRightX(Math.max(maxX + ab.width * 10, rect.getUpperRightX()));
rect.setUpperRightY(Math.max(maxY + ab.width * 10, rect.getUpperRightY()));
annotation.setRectangle(rect);
// need to set the BBox too, because rectangle modification came later
annotation.getNormalAppearanceStream().setBBox(getRectangle());
//TODO when callout is used, /RD should be so that the result is the writable part
}
}
catch (IOException ex)
{
LOG.error(ex);
}
}
// get the last non stroking color from the /DA entry
private PDColor extractNonStrokingColor(PDAnnotationFreeText annotation)
{
// It could also work with a regular expression, but that should be written so that
// "/LucidaConsole 13.94766 Tf .392 .585 .93 rg" does not produce "2 .585 .93 rg" as result
// Another alternative might be to create a PDDocument and a PDPage with /DA content as /Content,
// process the whole thing and then get the non stroking color.
PDColor strokingColor = new PDColor(new float[]{0}, PDDeviceGray.INSTANCE);
String defaultAppearance = annotation.getDefaultAppearance();
if (defaultAppearance == null)
{
return strokingColor;
}
try
{
// not sure if charset is correct, but we only need numbers and simple characters
PDFStreamParser parser = new PDFStreamParser(defaultAppearance.getBytes(Charsets.US_ASCII));
COSArray arguments = new COSArray();
COSArray colors = null;
Operator graphicOp = null;
for (Object token = parser.parseNextToken(); token != null; token = parser.parseNextToken())
{
if (token instanceof COSObject)
{
arguments.add(((COSObject) token).getObject());
}
else if (token instanceof Operator)
{
Operator op = (Operator) token;
String name = op.getName();
if ("g".equals(name) || "rg".equals(name) || "k".equals(name))
{
graphicOp = op;
colors = arguments;
}
arguments = new COSArray();
}
else
{
arguments.add((COSBase) token);
}
}
if (graphicOp != null)
{
switch (graphicOp.getName())
{
case "g":
strokingColor = new PDColor(colors, PDDeviceGray.INSTANCE);
break;
case "rg":
strokingColor = new PDColor(colors, PDDeviceRGB.INSTANCE);
break;
case "k":
strokingColor = new PDColor(colors, PDDeviceCMYK.INSTANCE);
break;
default:
break;
}
}
}
catch (IOException ex)
{
LOG.warn("Problem parsing /DA, will use default black", ex);
}
return strokingColor;
}
//TODO extractNonStrokingColor and extractFontSize
// might somehow be replaced with PDDefaultAppearanceString,
// which is quite similar.
private float extractFontSize(PDAnnotationFreeText annotation)
{
String defaultAppearance = annotation.getDefaultAppearance();
if (defaultAppearance == null)
{
return 10;
}
try
{
// not sure if charset is correct, but we only need numbers and simple characters
PDFStreamParser parser = new PDFStreamParser(defaultAppearance.getBytes(Charsets.US_ASCII));
COSArray arguments = new COSArray();
COSArray fontArguments = new COSArray();
for (Object token = parser.parseNextToken(); token != null; token = parser.parseNextToken())
{
if (token instanceof COSObject)
{
arguments.add(((COSObject) token).getObject());
}
else if (token instanceof Operator)
{
Operator op = (Operator) token;
String name = op.getName();
if ("Tf".equals(name))
{
fontArguments = arguments;
}
arguments = new COSArray();
}
else
{
arguments.add((COSBase) token);
}
}
if (fontArguments.size() >= 2)
{
COSBase base = fontArguments.get(1);
if (base instanceof COSNumber)
{
return ((COSNumber) base).floatValue();
}
}
}
catch (IOException ex)
{
LOG.warn("Problem parsing /DA, will use default 10", ex);
}
return 10;
}
@Override
public void generateRolloverAppearance()
{
// TODO to be implemented
}
@Override
public void generateDownAppearance()
{
// TODO to be implemented
}
}
| pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDFreeTextAppearanceHandler.java | /*
* Copyright 2018 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.pdfbox.pdmodel.interactive.annotation.handlers;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.fontbox.util.Charsets;
import org.apache.pdfbox.contentstream.operator.Operator;
import org.apache.pdfbox.cos.COSArray;
import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.cos.COSNumber;
import org.apache.pdfbox.cos.COSObject;
import org.apache.pdfbox.pdfparser.PDFStreamParser;
import org.apache.pdfbox.pdmodel.PDAppearanceContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.graphics.color.PDColor;
import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceCMYK;
import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceGray;
import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceRGB;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationFreeText;
import static org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationLine.LE_NONE;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceStream;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDBorderEffectDictionary;
import org.apache.pdfbox.pdmodel.interactive.annotation.layout.AppearanceStyle;
import org.apache.pdfbox.pdmodel.interactive.annotation.layout.PlainText;
import org.apache.pdfbox.pdmodel.interactive.annotation.layout.PlainTextFormatter;
import org.apache.pdfbox.util.Matrix;
public class PDFreeTextAppearanceHandler extends PDAbstractAppearanceHandler
{
private static final Log LOG = LogFactory.getLog(PDFreeTextAppearanceHandler.class);
private static final Pattern COLOR_PATTERN = Pattern.compile(".*color\\:\\#([0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]).*");
public PDFreeTextAppearanceHandler(PDAnnotation annotation)
{
super(annotation);
}
@Override
public void generateAppearanceStreams()
{
generateNormalAppearance();
generateRolloverAppearance();
generateDownAppearance();
}
@Override
public void generateNormalAppearance()
{
PDAnnotationFreeText annotation = (PDAnnotationFreeText) getAnnotation();
float[] pathsArray = new float[0];
if (PDAnnotationFreeText.IT_FREE_TEXT_CALLOUT.equals(annotation.getIntent()))
{
pathsArray = annotation.getCallout();
if (pathsArray == null || pathsArray.length != 4 && pathsArray.length != 6)
{
pathsArray = new float[0];
}
}
AnnotationBorder ab = AnnotationBorder.getAnnotationBorder(annotation, annotation.getBorderStyle());
try (PDAppearanceContentStream cs = getNormalAppearanceAsContentStream(true))
{
// The fill color is the /C entry, there is no /IC entry defined
boolean hasBackground = cs.setNonStrokingColorOnDemand(annotation.getColor());
setOpacity(cs, annotation.getConstantOpacity());
// Adobe uses the last non stroking color from /DA as stroking color!
// But if there is a color in /DS, then that one is used for text.
PDColor strokingColor = extractNonStrokingColor(annotation);
boolean hasStroke = cs.setStrokingColorOnDemand(strokingColor);
PDColor textColor = strokingColor;
String defaultStyleString = annotation.getDefaultStyleString();
if (defaultStyleString != null)
{
Matcher m = COLOR_PATTERN.matcher(defaultStyleString);
if (m.find())
{
int color = Integer.parseInt(m.group(1), 16);
float r = ((color >> 16) & 0xFF) / 255f;
float g = ((color >> 8) & 0xFF) / 255f;
float b = (color & 0xFF) / 255f;
textColor = new PDColor( new float[] { r, g, b }, PDDeviceRGB.INSTANCE);
}
}
if (ab.dashArray != null)
{
cs.setLineDashPattern(ab.dashArray, 0);
}
cs.setLineWidth(ab.width);
// draw callout line(s)
// must be done before retangle paint to avoid a line cutting through cloud
// see CTAN-example-Annotations.pdf
for (int i = 0; i < pathsArray.length / 2; ++i)
{
float x = pathsArray[i * 2];
float y = pathsArray[i * 2 + 1];
if (i == 0)
{
if (SHORT_STYLES.contains(annotation.getLineEndingStyle()))
{
// modify coordinate to shorten the segment
// https://stackoverflow.com/questions/7740507/extend-a-line-segment-a-specific-distance
float x1 = pathsArray[2];
float y1 = pathsArray[3];
float len = (float) (Math.sqrt(Math.pow(x - x1, 2) + Math.pow(y - y1, 2)));
if (Float.compare(len, 0) != 0)
{
x += (x1 - x) / len * ab.width;
y += (y1 - y) / len * ab.width;
}
}
cs.moveTo(x, y);
}
else
{
cs.lineTo(x, y);
}
}
if (pathsArray.length > 0)
{
cs.stroke();
}
// paint the styles here and after line(s) draw, to avoid line crossing a filled shape
if (PDAnnotationFreeText.IT_FREE_TEXT_CALLOUT.equals(annotation.getIntent())
// check only needed to avoid q cm Q if LE_NONE
&& !LE_NONE.equals(annotation.getLineEndingStyle())
&& pathsArray.length >= 4)
{
float x2 = pathsArray[2];
float y2 = pathsArray[3];
float x1 = pathsArray[0];
float y1 = pathsArray[1];
cs.saveGraphicsState();
if (ANGLED_STYLES.contains(annotation.getLineEndingStyle()))
{
// do a transform so that first "arm" is imagined flat,
// like in line handler.
// The alternative would be to apply the transform to the
// LE shape coordinates directly, which would be more work
// and produce code difficult to understand
double angle = Math.atan2(y2 - y1, x2 - x1);
cs.transform(Matrix.getRotateInstance(angle, x1, y1));
}
else
{
cs.transform(Matrix.getTranslateInstance(x1, y1));
}
drawStyle(annotation.getLineEndingStyle(), cs, 0, 0, ab.width, hasStroke, hasBackground, false);
cs.restoreGraphicsState();
}
PDRectangle borderBox;
PDBorderEffectDictionary borderEffect = annotation.getBorderEffect();
if (borderEffect != null && borderEffect.getStyle().equals(PDBorderEffectDictionary.STYLE_CLOUDY))
{
// Adobe draws the text with the original rectangle in mind.
// but if there is an /RD, then writing area get smaller.
// do this here because /RD is overwritten in a few lines
borderBox = applyRectDifferences(getRectangle(), annotation.getRectDifferences());
//TODO this segment was copied from square handler. Refactor?
CloudyBorder cloudyBorder = new CloudyBorder(cs,
borderEffect.getIntensity(), ab.width, getRectangle());
cloudyBorder.createCloudyRectangle(annotation.getRectDifference());
annotation.setRectangle(cloudyBorder.getRectangle());
annotation.setRectDifference(cloudyBorder.getRectDifference());
PDAppearanceStream appearanceStream = annotation.getNormalAppearanceStream();
appearanceStream.setBBox(cloudyBorder.getBBox());
appearanceStream.setMatrix(cloudyBorder.getMatrix());
}
else
{
// handle the border box
//
// There are two options. The handling is not part of the PDF specification but
// implementation specific to Adobe Reader
// - if /RD is set the border box is the /Rect entry inset by the respective
// border difference.
// - if /RD is not set then we don't touch /RD etc because Adobe doesn't either.
borderBox = applyRectDifferences(getRectangle(), annotation.getRectDifferences());
annotation.getNormalAppearanceStream().setBBox(borderBox);
// note that borderBox is not modified
PDRectangle paddedRectangle = getPaddedRectangle(borderBox, ab.width / 2);
cs.addRect(paddedRectangle.getLowerLeftX(), paddedRectangle.getLowerLeftY(),
paddedRectangle.getWidth(), paddedRectangle.getHeight());
}
cs.drawShape(ab.width, hasStroke, hasBackground);
// rotation is an undocumented feature, but Adobe uses it. Examples can be found
// in pdf_commenting_new.pdf file, page 3.
int rotation = annotation.getCOSObject().getInt(COSName.ROTATE, 0);
cs.transform(Matrix.getRotateInstance(Math.toRadians(rotation), 0, 0));
float xOffset;
float yOffset;
float width = rotation == 90 || rotation == 270 ? borderBox.getHeight() : borderBox.getWidth();
// strategy to write formatted text is somewhat inspired by
// AppearanceGeneratorHelper.insertGeneratedAppearance()
PDFont font = PDType1Font.HELVETICA;
float clipY;
float clipWidth = width - ab.width * 4;
float clipHeight = rotation == 90 || rotation == 270 ?
borderBox.getWidth() - ab.width * 4 : borderBox.getHeight() - ab.width * 4;
float fontSize = extractFontSize(annotation);
// value used by Adobe, no idea where it comes from, actual font bbox max y is 0.931
// gathered by creating an annotation with width 0.
float yDelta = 0.7896f;
switch (rotation)
{
case 180:
xOffset = - borderBox.getUpperRightX() + ab.width * 2;
yOffset = - borderBox.getLowerLeftY() - ab.width * 2 - yDelta * fontSize;
clipY = - borderBox.getUpperRightY() + ab.width * 2;
break;
case 90:
xOffset = borderBox.getLowerLeftY() + ab.width * 2;
yOffset = - borderBox.getLowerLeftX() - ab.width * 2 - yDelta * fontSize;
clipY = - borderBox.getUpperRightX() + ab.width * 2;
break;
case 270:
xOffset = - borderBox.getUpperRightY() + ab.width * 2;
yOffset = borderBox.getUpperRightX() - ab.width * 2 - yDelta * fontSize;
clipY = borderBox.getLowerLeftX() + ab.width * 2;
break;
case 0:
default:
xOffset = borderBox.getLowerLeftX() + ab.width * 2;
yOffset = borderBox.getUpperRightY() - ab.width * 2 - yDelta * fontSize;
clipY = borderBox.getLowerLeftY() + ab.width * 2;
break;
}
// clip writing area
cs.addRect(xOffset, clipY, clipWidth, clipHeight);
cs.clip();
cs.beginText();
cs.setFont(font, fontSize);
cs.setNonStrokingColor(textColor.getComponents());
AppearanceStyle appearanceStyle = new AppearanceStyle();
appearanceStyle.setFont(font);
appearanceStyle.setFontSize(fontSize);
PlainTextFormatter formatter = new PlainTextFormatter.Builder(cs)
.style(appearanceStyle)
.text(new PlainText(annotation.getContents()))
.width(width - ab.width * 4)
.wrapLines(true)
.initialOffset(xOffset, yOffset)
// Adobe ignores the /Q
//.textAlign(annotation.getQ())
.build();
try
{
formatter.format();
}
catch (IllegalArgumentException ex)
{
throw new IOException(ex);
}
cs.endText();
if (pathsArray.length > 0)
{
PDRectangle rect = getRectangle();
// Adjust rectangle
// important to do this after the rectangle has been painted, because the
// final rectangle will be bigger due to callout
// CTAN-example-Annotations.pdf p1
//TODO in a class structure this should be overridable
float minX = Float.MAX_VALUE;
float minY = Float.MAX_VALUE;
float maxX = Float.MIN_VALUE;
float maxY = Float.MIN_VALUE;
for (int i = 0; i < pathsArray.length / 2; ++i)
{
float x = pathsArray[i * 2];
float y = pathsArray[i * 2 + 1];
minX = Math.min(minX, x);
minY = Math.min(minY, y);
maxX = Math.max(maxX, x);
maxY = Math.max(maxY, y);
}
// arrow length is 9 * width at about 30° => 10 * width seems to be enough
rect.setLowerLeftX(Math.min(minX - ab.width * 10, rect.getLowerLeftX()));
rect.setLowerLeftY(Math.min(minY - ab.width * 10, rect.getLowerLeftY()));
rect.setUpperRightX(Math.max(maxX + ab.width * 10, rect.getUpperRightX()));
rect.setUpperRightY(Math.max(maxY + ab.width * 10, rect.getUpperRightY()));
annotation.setRectangle(rect);
// need to set the BBox too, because rectangle modification came later
annotation.getNormalAppearanceStream().setBBox(getRectangle());
//TODO when callout is used, /RD should be so that the result is the writable part
}
}
catch (IOException ex)
{
LOG.error(ex);
}
}
// get the last non stroking color from the /DA entry
private PDColor extractNonStrokingColor(PDAnnotationFreeText annotation)
{
// It could also work with a regular expression, but that should be written so that
// "/LucidaConsole 13.94766 Tf .392 .585 .93 rg" does not produce "2 .585 .93 rg" as result
// Another alternative might be to create a PDDocument and a PDPage with /DA content as /Content,
// process the whole thing and then get the non stroking color.
PDColor strokingColor = new PDColor(new float[]{0}, PDDeviceGray.INSTANCE);
String defaultAppearance = annotation.getDefaultAppearance();
if (defaultAppearance == null)
{
return strokingColor;
}
try
{
// not sure if charset is correct, but we only need numbers and simple characters
PDFStreamParser parser = new PDFStreamParser(defaultAppearance.getBytes(Charsets.US_ASCII));
COSArray arguments = new COSArray();
COSArray colors = null;
Operator graphicOp = null;
for (Object token = parser.parseNextToken(); token != null; token = parser.parseNextToken())
{
if (token instanceof COSObject)
{
arguments.add(((COSObject) token).getObject());
}
else if (token instanceof Operator)
{
Operator op = (Operator) token;
String name = op.getName();
if ("g".equals(name) || "rg".equals(name) || "k".equals(name))
{
graphicOp = op;
colors = arguments;
}
arguments = new COSArray();
}
else
{
arguments.add((COSBase) token);
}
}
if (graphicOp != null)
{
switch (graphicOp.getName())
{
case "g":
strokingColor = new PDColor(colors, PDDeviceGray.INSTANCE);
break;
case "rg":
strokingColor = new PDColor(colors, PDDeviceRGB.INSTANCE);
break;
case "k":
strokingColor = new PDColor(colors, PDDeviceCMYK.INSTANCE);
break;
default:
break;
}
}
}
catch (IOException ex)
{
LOG.warn("Problem parsing /DA, will use default black", ex);
}
return strokingColor;
}
//TODO extractNonStrokingColor and extractFontSize
// might somehow be replaced with PDDefaultAppearanceString,
// which is quite similar.
private float extractFontSize(PDAnnotationFreeText annotation)
{
String defaultAppearance = annotation.getDefaultAppearance();
if (defaultAppearance == null)
{
return 10;
}
try
{
// not sure if charset is correct, but we only need numbers and simple characters
PDFStreamParser parser = new PDFStreamParser(defaultAppearance.getBytes(Charsets.US_ASCII));
COSArray arguments = new COSArray();
COSArray fontArguments = new COSArray();
for (Object token = parser.parseNextToken(); token != null; token = parser.parseNextToken())
{
if (token instanceof COSObject)
{
arguments.add(((COSObject) token).getObject());
}
else if (token instanceof Operator)
{
Operator op = (Operator) token;
String name = op.getName();
if ("Tf".equals(name))
{
fontArguments = arguments;
}
arguments = new COSArray();
}
else
{
arguments.add((COSBase) token);
}
}
if (fontArguments.size() >= 2)
{
COSBase base = fontArguments.get(1);
if (base instanceof COSNumber)
{
return ((COSNumber) base).floatValue();
}
}
}
catch (IOException ex)
{
LOG.warn("Problem parsing /DA, will use default 10", ex);
}
return 10;
}
@Override
public void generateRolloverAppearance()
{
// TODO to be implemented
}
@Override
public void generateDownAppearance()
{
// TODO to be implemented
}
}
| PDFBOX-3353: change regexp to allow space(s) after "color:"
git-svn-id: c3ad59981690829a43dc34c293c4e2cd04bcd994@1865050 13f79535-47bb-0310-9956-ffa450edef68
| pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/annotation/handlers/PDFreeTextAppearanceHandler.java | PDFBOX-3353: change regexp to allow space(s) after "color:" |
|
Java | apache-2.0 | 8038114510076069ccf55307acd1bebb4d602871 | 0 | jeffbrown/grailsnolib,jeffbrown/grailsnolib | /* Copyright 2004-2005 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.grails.aop.framework.autoproxy;
import org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator;
import org.springframework.aop.framework.autoproxy.InfrastructureAdvisorAutoProxyCreator;
import groovy.lang.GroovyObject;
/**
* Tells Spring always to proxy Groovy classes
*
* @author Graeme Rocher
* @since 1.2
*/
public class GroovyAwareInfrastructureAdvisorAutoProxyCreator extends AnnotationAwareAspectJAutoProxyCreator {
@Override
protected boolean shouldProxyTargetClass(Class<?> beanClass, String beanName) {
return GroovyObject.class.isAssignableFrom(beanClass) || super.shouldProxyTargetClass(beanClass, beanName);
}
}
| src/java/org/codehaus/groovy/grails/aop/framework/autoproxy/GroovyAwareInfrastructureAdvisorAutoProxyCreator.java | /* Copyright 2004-2005 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.grails.aop.framework.autoproxy;
import org.springframework.aop.framework.autoproxy.InfrastructureAdvisorAutoProxyCreator;
import groovy.lang.GroovyObject;
/**
* Tells Spring always to proxy Groovy classes
*
* @author Graeme Rocher
* @since 1.2
*/
public class GroovyAwareInfrastructureAdvisorAutoProxyCreator extends InfrastructureAdvisorAutoProxyCreator{
@Override
protected boolean shouldProxyTargetClass(Class<?> beanClass, String beanName) {
return GroovyObject.class.isAssignableFrom(beanClass) || super.shouldProxyTargetClass(beanClass, beanName);
}
}
| fix for GRAILS-5932 "AOP 2 not working with Grails 1.2 (works with Grails 1.1.x)"
| src/java/org/codehaus/groovy/grails/aop/framework/autoproxy/GroovyAwareInfrastructureAdvisorAutoProxyCreator.java | fix for GRAILS-5932 "AOP 2 not working with Grails 1.2 (works with Grails 1.1.x)" |
|
Java | apache-2.0 | 8c92eefa24dfbb00c19da581a2b2b5681c420c65 | 0 | freeVM/freeVM,freeVM/freeVM,freeVM/freeVM,freeVM/freeVM,freeVM/freeVM | /*
* 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.harmony.pack200;
import java.io.IOException;
import java.io.InputStream;
/**
* A PopulationCodec is a Codec that is well suited to encoding data that shows
* statistical or repetitive patterns, containing for example a few numbers
* which are repeated a lot throughout the set, but not necessarily
* sequentially.
*/
public class PopulationCodec extends Codec {
private final Codec favouredCodec;
private Codec tokenCodec;
private final Codec unfavouredCodec;
private int l;
private int[] favoured;
public PopulationCodec(Codec favouredCodec, Codec tokenCodec,
Codec unvafouredCodec) {
this.favouredCodec = favouredCodec;
this.tokenCodec = tokenCodec;
this.unfavouredCodec = unvafouredCodec;
}
public PopulationCodec(Codec favouredCodec, int l, Codec unvafouredCodec) {
if (l >= 256 || l <= 0)
throw new IllegalArgumentException("L must be between 1..255");
this.favouredCodec = favouredCodec;
this.l = l;
this.unfavouredCodec = unvafouredCodec;
}
public int decode(InputStream in) throws IOException, Pack200Exception {
throw new Pack200Exception(
"Population encoding does not work unless the number of elements are known");
}
public int decode(InputStream in, long last) throws IOException,
Pack200Exception {
throw new Pack200Exception(
"Population encoding does not work unless the number of elements are known");
}
public int[] decodeInts(int n, InputStream in) throws IOException,
Pack200Exception {
lastBandLength = 0;
favoured = new int[n]; // there must be <= n values, but probably a lot
// less
int result[];
// read table of favorites first
int smallest = Integer.MAX_VALUE;
int last = 0;
int value = 0;
int k = -1;
while (true) {
value = favouredCodec.decode(in, last);
if (k > -1 && (value == smallest || value == last))
break;
favoured[++k] = value;
if (Math.abs(smallest) > Math.abs(value)) {
smallest = value;
} else if (Math.abs(smallest) == Math.abs(value)) {
// ensure that -X and +X -> +X
smallest = Math.abs(smallest);
}
last = value;
}
lastBandLength += k;
// if tokenCodec needs to be derived from the T, L and K values
if (tokenCodec == null) {
if (k < 256) {
tokenCodec = Codec.BYTE1;
} else {
// if k >= 256, b >= 2
int b = 1;
while (++b < 5 && tokenCodec == null) {
BHSDCodec codec = new BHSDCodec(b, 256 - l, 0);
if (codec.encodes(k))
tokenCodec = codec;
}
if (tokenCodec == null)
throw new Pack200Exception(
"Cannot calculate token codec from " + k + " and "
+ l);
}
}
// read favorites
lastBandLength += n;
result = tokenCodec.decodeInts(n, in);
// read unfavorites
last = 0;
for (int i = 0; i < n; i++) {
int index = result[i];
if (index == 0) {
lastBandLength++;
result[i] = last = unfavouredCodec.decode(in, last);
} else {
result[i] = favoured[index - 1];
}
}
return result;
}
public int[] getFavoured() {
return favoured;
}
public Codec getFavouredCodec() {
return favouredCodec;
}
public Codec getUnfavouredCodec() {
return unfavouredCodec;
}
public byte[] encode(int value, int last) throws Pack200Exception {
throw new Pack200Exception(
"Population encoding does not work unless the number of elements are known");
}
public byte[] encode(int value) throws Pack200Exception {
throw new Pack200Exception(
"Population encoding does not work unless the number of elements are known");
}
public byte[] encode(int[] favoured, int[] tokens, int[] unfavoured) throws Pack200Exception {
byte[] favouredEncoded = favouredCodec.encode(favoured);
byte[] tokensEncoded = tokenCodec.encode(tokens);
byte[] unfavouredEncoded = unfavouredCodec.encode(unfavoured);
byte[] band = new byte[favouredEncoded.length + tokensEncoded.length + unfavouredEncoded.length];
return band;
}
public Codec getTokenCodec() {
return tokenCodec;
}
public int getL() {
return l;
}
}
| enhanced/classlib/trunk/modules/pack200/src/main/java/org/apache/harmony/pack200/PopulationCodec.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.harmony.pack200;
import java.io.IOException;
import java.io.InputStream;
/**
* A PopulationCodec is a Codec that is well suited to encoding data that shows
* statistical or repetitive patterns, containing for example a few numbers
* which are repeated a lot throughout the set, but not necessarily
* sequentially.
*/
public class PopulationCodec extends Codec {
private final Codec favouredCodec;
private Codec tokenCodec;
private final Codec unvafouredCodec;
private int l;
private int[] favoured;
public PopulationCodec(Codec favouredCodec, Codec tokenCodec,
Codec unvafouredCodec) {
this.favouredCodec = favouredCodec;
this.tokenCodec = tokenCodec;
this.unvafouredCodec = unvafouredCodec;
}
public PopulationCodec(Codec favouredCodec, int l, Codec unvafouredCodec) {
if (l >= 256 || l <= 0)
throw new IllegalArgumentException("L must be between 1..255");
this.favouredCodec = favouredCodec;
this.l = l;
this.unvafouredCodec = unvafouredCodec;
}
public int decode(InputStream in) throws IOException, Pack200Exception {
throw new Pack200Exception(
"Population encoding does not work unless the number of elements are known");
}
public int decode(InputStream in, long last) throws IOException,
Pack200Exception {
throw new Pack200Exception(
"Population encoding does not work unless the number of elements are known");
}
public int[] decodeInts(int n, InputStream in) throws IOException,
Pack200Exception {
lastBandLength = 0;
favoured = new int[n]; // there must be <= n values, but probably a lot
// less
int result[];
// read table of favorites first
int smallest = Integer.MAX_VALUE;
int last = 0;
int value = 0;
int k = -1;
while (true) {
value = favouredCodec.decode(in, last);
if (k > -1 && (value == smallest || value == last))
break;
favoured[++k] = value;
if (Math.abs(smallest) > Math.abs(value)) {
smallest = value;
} else if (Math.abs(smallest) == Math.abs(value)) {
// ensure that -X and +X -> +X
smallest = Math.abs(smallest);
}
last = value;
}
lastBandLength += k;
// if tokenCodec needs to be derived from the T, L and K values
if (tokenCodec == null) {
if (k < 256) {
tokenCodec = Codec.BYTE1;
} else {
// if k >= 256, b >= 2
int b = 1;
while (++b < 5 && tokenCodec == null) {
BHSDCodec codec = new BHSDCodec(b, 256 - l, 0);
if (codec.encodes(k))
tokenCodec = codec;
}
if (tokenCodec == null)
throw new Pack200Exception(
"Cannot calculate token codec from " + k + " and "
+ l);
}
}
// read favorites
lastBandLength += n;
result = tokenCodec.decodeInts(n, in);
// read unfavorites
last = 0;
for (int i = 0; i < n; i++) {
int index = result[i];
if (index == 0) {
lastBandLength++;
result[i] = last = unvafouredCodec.decode(in, last);
} else {
result[i] = favoured[index - 1];
}
}
return result;
}
public int[] getFavoured() {
return favoured;
}
public Codec getFavouredCodec() {
return favouredCodec;
}
public Codec getUnfavouredCodec() {
return unvafouredCodec;
}
public byte[] encode(int value, int last) throws Pack200Exception {
throw new Pack200Exception(
"Population encoding does not work unless the number of elements are known");
}
public byte[] encode(int value) throws Pack200Exception {
throw new Pack200Exception(
"Population encoding does not work unless the number of elements are known");
}
public byte[] encode(int[] favoured, int[] tokens, int[] unfavoured) throws Pack200Exception {
byte[] favouredEncoded = favouredCodec.encode(favoured);
byte[] tokensEncoded = tokenCodec.encode(tokens);
byte[] unfavouredEncoded = unvafouredCodec.encode(unfavoured);
byte[] band = new byte[favouredEncoded.length + tokensEncoded.length + unfavouredEncoded.length];
return band;
}
public Codec getTokenCodec() {
return tokenCodec;
}
public int getL() {
return l;
}
}
| Pack200 - fix spelling mistake
svn path=/harmony/; revision=785994
| enhanced/classlib/trunk/modules/pack200/src/main/java/org/apache/harmony/pack200/PopulationCodec.java | Pack200 - fix spelling mistake |
|
Java | apache-2.0 | 09e267fb3fae8f841bbb8cfbd36ffd25e48974c6 | 0 | diffplug/spotless,diffplug/spotless,diffplug/spotless,diffplug/spotless,diffplug/spotless,diffplug/spotless | /*
* Copyright 2016 DiffPlug
*
* 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.diffplug.gradle.spotless;
import static com.diffplug.gradle.spotless.PluginGradlePreconditions.requireElementsNonNull;
import java.io.File;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.util.*;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.gradle.api.GradleException;
import org.gradle.api.Project;
import org.gradle.api.file.FileCollection;
import com.diffplug.spotless.FormatExceptionPolicyStrict;
import com.diffplug.spotless.FormatterFunc;
import com.diffplug.spotless.FormatterStep;
import com.diffplug.spotless.LazyForwardingEquality;
import com.diffplug.spotless.LineEnding;
import com.diffplug.spotless.ThrowingEx;
import com.diffplug.spotless.extra.EclipseBasedStepBuilder;
import com.diffplug.spotless.extra.wtp.EclipseWtpFormatterStep;
import com.diffplug.spotless.generic.EndWithNewlineStep;
import com.diffplug.spotless.generic.IndentStep;
import com.diffplug.spotless.generic.LicenseHeaderStep;
import com.diffplug.spotless.generic.ReplaceRegexStep;
import com.diffplug.spotless.generic.ReplaceStep;
import com.diffplug.spotless.generic.TrimTrailingWhitespaceStep;
import com.diffplug.spotless.npm.PrettierFormatterStep;
import groovy.lang.Closure;
/** Adds a `spotless{Name}Check` and `spotless{Name}Apply` task. */
public class FormatExtension {
final SpotlessExtension root;
public FormatExtension(SpotlessExtension root) {
this.root = Objects.requireNonNull(root);
}
private String formatName() {
for (Map.Entry<String, FormatExtension> entry : root.formats.entrySet()) {
if (entry.getValue() == this) {
return entry.getKey();
}
}
throw new IllegalStateException("This format is not contained by any SpotlessExtension.");
}
boolean paddedCell = false;
/** Enables paddedCell mode. @see <a href="https://github.com/diffplug/spotless/blob/master/PADDEDCELL.md">Padded cell</a> */
public void paddedCell() {
paddedCell(true);
}
/** Enables paddedCell mode. @see <a href="https://github.com/diffplug/spotless/blob/master/PADDEDCELL.md">Padded cell</a> */
public void paddedCell(boolean paddedCell) {
this.paddedCell = paddedCell;
}
LineEnding lineEndings;
/** Returns the line endings to use (defaults to {@link SpotlessExtension#getLineEndings()}. */
public LineEnding getLineEndings() {
return lineEndings == null ? root.getLineEndings() : lineEndings;
}
/** Sets the line endings to use (defaults to {@link SpotlessExtension#getLineEndings()}. */
public void setLineEndings(LineEnding lineEndings) {
this.lineEndings = Objects.requireNonNull(lineEndings);
}
Charset encoding;
/** Returns the encoding to use (defaults to {@link SpotlessExtension#getEncoding()}. */
public Charset getEncoding() {
return encoding == null ? root.getEncoding() : encoding;
}
/** Sets the encoding to use (defaults to {@link SpotlessExtension#getEncoding()}. */
public void setEncoding(String name) {
setEncoding(Charset.forName(Objects.requireNonNull(name)));
}
/** Sets the encoding to use (defaults to {@link SpotlessExtension#getEncoding()}. */
public void setEncoding(Charset charset) {
encoding = Objects.requireNonNull(charset);
}
final FormatExceptionPolicyStrict exceptionPolicy = new FormatExceptionPolicyStrict();
/** Ignores errors in the given step. */
public void ignoreErrorForStep(String stepName) {
exceptionPolicy.excludeStep(Objects.requireNonNull(stepName));
}
/** Ignores errors for the given relative path. */
public void ignoreErrorForPath(String relativePath) {
exceptionPolicy.excludePath(Objects.requireNonNull(relativePath));
}
/** Sets encoding to use (defaults to {@link SpotlessExtension#getEncoding()}). */
public void encoding(String charset) {
setEncoding(charset);
}
/** The files to be formatted = (target - targetExclude). */
protected FileCollection target, targetExclude;
/**
* Sets which files should be formatted. Files to be formatted = (target - targetExclude).
*
* When this method is called multiple times, only the last call has any effect.
*
* FileCollections pass through raw.
* Strings are treated as the 'include' arg to fileTree, with project.rootDir as the dir.
* List<String> are treated as the 'includes' arg to fileTree, with project.rootDir as the dir.
* Anything else gets passed to getProject().files().
*/
public void target(Object... targets) {
this.target = parseTargetsIsExclude(targets, false);
}
/**
* Sets which files will be excluded from formatting. Files to be formatted = (target - targetExclude).
*
* When this method is called multiple times, only the last call has any effect.
*
* FileCollections pass through raw.
* Strings are treated as the 'include' arg to fileTree, with project.rootDir as the dir.
* List<String> are treated as the 'includes' arg to fileTree, with project.rootDir as the dir.
* Anything else gets passed to getProject().files().
*/
public void targetExclude(Object... targets) {
this.targetExclude = parseTargetsIsExclude(targets, true);
}
private FileCollection parseTargetsIsExclude(Object[] targets, boolean isExclude) {
requireElementsNonNull(targets);
if (targets.length == 0) {
return getProject().files();
} else if (targets.length == 1) {
return parseTargetIsExclude(targets[0], isExclude);
} else {
if (Stream.of(targets).allMatch(o -> o instanceof String)) {
return parseTargetIsExclude(Arrays.asList(targets), isExclude);
} else {
FileCollection union = getProject().files();
for (Object target : targets) {
union = union.plus(parseTargetIsExclude(target, isExclude));
}
return union;
}
}
}
/**
* FileCollections pass through raw.
* Strings are treated as the 'include' arg to fileTree, with project.rootDir as the dir.
* List<String> are treated as the 'includes' arg to fileTree, with project.rootDir as the dir.
* Anything else gets passed to getProject().files().
*/
protected final FileCollection parseTarget(Object target) {
return parseTargetIsExclude(target, false);
}
private final FileCollection parseTargetIsExclude(Object target, boolean isExclude) {
if (target instanceof FileCollection) {
return (FileCollection) target;
} else if (target instanceof String ||
(target instanceof List && ((List<?>) target).stream().allMatch(o -> o instanceof String))) {
// since people are likely to do '**/*.md', we want to make sure to exclude folders
// they don't want to format which will slow down the operation greatly
File dir = getProject().getProjectDir();
List<String> excludes = new ArrayList<>();
// no git
excludes.add(".git");
// no .gradle
if (getProject() == getProject().getRootProject()) {
excludes.add(".gradle");
}
// no build folders (flatInclude means that subproject might not be subfolders, see https://github.com/diffplug/spotless/issues/121)
relativizeIfSubdir(excludes, dir, getProject().getBuildDir());
for (Project subproject : getProject().getSubprojects()) {
relativizeIfSubdir(excludes, dir, subproject.getBuildDir());
}
if (target instanceof String) {
return (FileCollection) getProject().fileTree(dir).include((String) target).exclude(excludes);
} else {
// target can only be a List<String> at this point
@SuppressWarnings("unchecked")
List<String> targetList = (List<String>) target;
return (FileCollection) getProject().fileTree(dir).include(targetList).exclude(excludes);
}
} else {
return getProject().files(target);
}
}
private static void relativizeIfSubdir(List<String> relativePaths, File root, File dest) {
String relativized = relativize(root, dest);
if (relativized != null) {
relativePaths.add(relativized);
}
}
/**
* Returns the relative path between root and dest,
* or null if dest is not a child of root.
*/
static @Nullable String relativize(File root, File dest) {
String rootPath = root.getAbsolutePath();
String destPath = dest.getAbsolutePath();
if (!destPath.startsWith(rootPath)) {
return null;
} else {
return destPath.substring(rootPath.length());
}
}
/** The steps that need to be added. */
protected final List<FormatterStep> steps = new ArrayList<>();
/** Adds a new step. */
public void addStep(FormatterStep newStep) {
Objects.requireNonNull(newStep);
int existingIdx = getExistingStepIdx(newStep.getName());
if (existingIdx != -1) {
throw new GradleException("Multiple steps with name '" + newStep.getName() + "' for spotless format '" + formatName() + "'");
}
steps.add(newStep);
}
/** Returns the existing step with the given name, if any. */
@Deprecated
protected @Nullable FormatterStep getExistingStep(String stepName) {
return steps.stream() //
.filter(step -> stepName.equals(step.getName())) //
.findFirst() //
.orElse(null);
}
/** Returns the index of the existing step with the given name, or -1 if no such step exists. */
protected int getExistingStepIdx(String stepName) {
for (int i = 0; i < steps.size(); ++i) {
if (steps.get(i).getName().equals(stepName)) {
return i;
}
}
return -1;
}
/** Replaces the given step. */
protected void replaceStep(FormatterStep replacementStep) {
int existingIdx = getExistingStepIdx(replacementStep.getName());
if (existingIdx == -1) {
throw new GradleException("Cannot replace step '" + replacementStep.getName() + "' for spotless format '" + formatName() + "' because it hasn't been added yet.");
}
steps.set(existingIdx, replacementStep);
}
/** Clears all of the existing steps. */
public void clearSteps() {
steps.clear();
}
/**
* An optional performance optimization if you are using any of the `custom` or `customLazy`
* methods. If you aren't explicitly calling `custom` or `customLazy`, then this method
* has no effect.
*
* Spotless tracks what files have changed from run to run, so that it can run faster
* by only checking files which have changed, or whose formatting steps have changed.
* If you use either the `custom` or `customLazy` methods, then gradle can never mark
* your files as `up-to-date`, because it can't know if perhaps the behavior of your
* custom function has changed.
*
* If you set `bumpThisNumberIfACustomStepChanges( <some number> )`, then spotless will
* assume that the custom rules have not changed if the number has not changed. If a
* custom rule does change, then you must bump the number so that spotless will know
* that it must recheck the files it has already checked.
*/
public void bumpThisNumberIfACustomStepChanges(int number) {
globalState = number;
}
private Serializable globalState = new NeverUpToDateBetweenRuns();
static class NeverUpToDateBetweenRuns extends LazyForwardingEquality<Integer> {
private static final long serialVersionUID = 1L;
private static final Random RANDOM = new Random();
@Override
protected Integer calculateState() throws Exception {
return RANDOM.nextInt();
}
}
/**
* Adds the given custom step, which is constructed lazily for performance reasons.
*
* The resulting function will receive a string with unix-newlines, and it must return a string unix newlines.
*
* If you're getting errors about `closure cannot be cast to com.diffplug.common.base.Throwing$Function`, then use
* {@link #customLazyGroovy(String, ThrowingEx.Supplier)}.
*/
public void customLazy(String name, ThrowingEx.Supplier<FormatterFunc> formatterSupplier) {
Objects.requireNonNull(name, "name");
Objects.requireNonNull(formatterSupplier, "formatterSupplier");
addStep(FormatterStep.createLazy(name, () -> globalState, unusedState -> formatterSupplier.get()));
}
/** Same as {@link #customLazy(String, ThrowingEx.Supplier)}, but for Groovy closures. */
public void customLazyGroovy(String name, ThrowingEx.Supplier<Closure<String>> formatterSupplier) {
Objects.requireNonNull(formatterSupplier, "formatterSupplier");
customLazy(name, () -> formatterSupplier.get()::call);
}
/** Adds a custom step. Receives a string with unix-newlines, must return a string with unix newlines. */
public void custom(String name, Closure<String> formatter) {
Objects.requireNonNull(formatter, "formatter");
custom(name, formatter::call);
}
/** Adds a custom step. Receives a string with unix-newlines, must return a string with unix newlines. */
public void custom(String name, FormatterFunc formatter) {
Objects.requireNonNull(formatter, "formatter");
customLazy(name, () -> formatter);
}
/** Highly efficient find-replace char sequence. */
public void replace(String name, CharSequence original, CharSequence after) {
addStep(ReplaceStep.create(name, original, after));
}
/** Highly efficient find-replace regex. */
public void replaceRegex(String name, String regex, String replacement) {
addStep(ReplaceRegexStep.create(name, regex, replacement));
}
/** Removes trailing whitespace. */
public void trimTrailingWhitespace() {
addStep(TrimTrailingWhitespaceStep.create());
}
/** Ensures that files end with a single newline. */
public void endWithNewline() {
addStep(EndWithNewlineStep.create());
}
/** Ensures that the files are indented using spaces. */
public void indentWithSpaces(int numSpacesPerTab) {
addStep(IndentStep.Type.SPACE.create(numSpacesPerTab));
}
/** Ensures that the files are indented using spaces. */
public void indentWithSpaces() {
addStep(IndentStep.Type.SPACE.create());
}
/** Ensures that the files are indented using tabs. */
public void indentWithTabs(int tabToSpaces) {
addStep(IndentStep.Type.TAB.create(tabToSpaces));
}
/** Ensures that the files are indented using tabs. */
public void indentWithTabs() {
addStep(IndentStep.Type.TAB.create());
}
abstract class LicenseHeaderConfig {
String delimiter;
String yearSeparator = LicenseHeaderStep.defaultYearDelimiter();
public LicenseHeaderConfig(String delimiter) {
this.delimiter = Objects.requireNonNull(delimiter, "delimiter");
}
/**
* @param delimiter
* Spotless will look for a line that starts with this regular expression pattern to know what the "top" is.
*/
public LicenseHeaderConfig delimiter(String delimiter) {
this.delimiter = Objects.requireNonNull(delimiter, "delimiter");
replaceStep(createStep());
return this;
}
/**
* @param yearSeparator
* The characters used to separate the first and last years in multi years patterns.
*/
public LicenseHeaderConfig yearSeparator(String yearSeparator) {
this.yearSeparator = Objects.requireNonNull(yearSeparator, "yearSeparator");
replaceStep(createStep());
return this;
}
abstract FormatterStep createStep();
}
class LicenseStringHeaderConfig extends LicenseHeaderConfig {
private String header;
LicenseStringHeaderConfig(String delimiter, String header) {
super(delimiter);
this.header = Objects.requireNonNull(header, "header");
}
FormatterStep createStep() {
return LicenseHeaderStep.createFromHeader(header, delimiter, yearSeparator);
}
}
class LicenseFileHeaderConfig extends LicenseHeaderConfig {
private Object headerFile;
LicenseFileHeaderConfig(String delimiter, Object headerFile) {
super(delimiter);
this.headerFile = Objects.requireNonNull(headerFile, "headerFile");
}
FormatterStep createStep() {
return LicenseHeaderStep
.createFromFile(getProject().file(headerFile), getEncoding(), delimiter,
yearSeparator);
}
}
/**
* @param licenseHeader
* Content that should be at the top of every file.
* @param delimiter
* Spotless will look for a line that starts with this regular expression pattern to know what the "top" is.
*/
public LicenseHeaderConfig licenseHeader(String licenseHeader, String delimiter) {
LicenseHeaderConfig config = new LicenseStringHeaderConfig(delimiter, licenseHeader);
addStep(config.createStep());
return config;
}
/**
* @param licenseHeaderFile
* Content that should be at the top of every file.
* @param delimiter
* Spotless will look for a line that starts with this regular expression pattern to know what the "top" is.
*/
public LicenseHeaderConfig licenseHeaderFile(Object licenseHeaderFile, String delimiter) {
LicenseHeaderConfig config = new LicenseFileHeaderConfig(delimiter, licenseHeaderFile);
addStep(config.createStep());
return config;
}
public abstract class NpmStepConfig<T extends NpmStepConfig<?>> {
@Nullable
protected Object npmFile;
@SuppressWarnings("unchecked")
public T npmExecutable(final Object npmFile) {
this.npmFile = npmFile;
replaceStep(createStep());
return (T) this;
}
File npmFileOrNull() {
return npmFile != null ? getProject().file(npmFile) : null;
}
abstract FormatterStep createStep();
}
public class PrettierConfig extends NpmStepConfig<PrettierConfig> {
@Nullable
Object prettierConfigFile;
@Nullable
Map<String, Object> prettierConfig;
final Map<String, String> devDependencies;
PrettierConfig(Map<String, String> devDependencies) {
this.devDependencies = Objects.requireNonNull(devDependencies);
}
public PrettierConfig configFile(final Object prettierConfigFile) {
this.prettierConfigFile = prettierConfigFile;
replaceStep(createStep());
return this;
}
public PrettierConfig config(final Map<String, Object> prettierConfig) {
this.prettierConfig = new TreeMap<>(prettierConfig);
replaceStep(createStep());
return this;
}
FormatterStep createStep() {
final Project project = getProject();
return PrettierFormatterStep.create(
devDependencies,
GradleProvisioner.fromProject(project),
project.getBuildDir(),
npmFileOrNull(),
new com.diffplug.spotless.npm.PrettierConfig(
this.prettierConfigFile != null ? project.file(this.prettierConfigFile) : null,
this.prettierConfig));
}
}
/** Uses the default version of prettier. */
public PrettierConfig prettier() {
return prettier(PrettierFormatterStep.defaultDevDependencies());
}
/** Uses the specified version of prettier. */
public PrettierConfig prettier(String version) {
return prettier(PrettierFormatterStep.defaultDevDependenciesWithPrettier(version));
}
/** Uses exactly the npm packages specified in the map. */
public PrettierConfig prettier(Map<String, String> devDependencies) {
PrettierConfig prettierConfig = new PrettierConfig(devDependencies);
addStep(prettierConfig.createStep());
return prettierConfig;
}
public class EclipseWtpConfig {
private final EclipseBasedStepBuilder builder;
EclipseWtpConfig(EclipseWtpFormatterStep type, String version) {
builder = type.createBuilder(GradleProvisioner.fromProject(getProject()));
builder.setVersion(version);
addStep(builder.build());
}
public void configFile(Object... configFiles) {
requireElementsNonNull(configFiles);
Project project = getProject();
builder.setPreferences(project.files(configFiles).getFiles());
replaceStep(builder.build());
}
}
public EclipseWtpConfig eclipseWtp(EclipseWtpFormatterStep type) {
return eclipseWtp(type, EclipseWtpFormatterStep.defaultVersion());
}
public EclipseWtpConfig eclipseWtp(EclipseWtpFormatterStep type, String version) {
return new EclipseWtpConfig(type, version);
}
/** Sets up a format task according to the values in this extension. */
protected void setupTask(SpotlessTask task) {
task.setPaddedCell(paddedCell);
task.setEncoding(getEncoding().name());
task.setExceptionPolicy(exceptionPolicy);
if (targetExclude == null) {
task.setTarget(target);
} else {
task.setTarget(target.minus(targetExclude));
}
task.setSteps(steps);
task.setLineEndingsPolicy(getLineEndings().createPolicy(getProject().getProjectDir(), () -> task.target));
}
/** Returns the project that this extension is attached to. */
protected Project getProject() {
return root.project;
}
}
| plugin-gradle/src/main/java/com/diffplug/gradle/spotless/FormatExtension.java | /*
* Copyright 2016 DiffPlug
*
* 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.diffplug.gradle.spotless;
import static com.diffplug.gradle.spotless.PluginGradlePreconditions.requireElementsNonNull;
import java.io.File;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.util.*;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.gradle.api.GradleException;
import org.gradle.api.Project;
import org.gradle.api.file.FileCollection;
import com.diffplug.spotless.FormatExceptionPolicyStrict;
import com.diffplug.spotless.FormatterFunc;
import com.diffplug.spotless.FormatterStep;
import com.diffplug.spotless.LazyForwardingEquality;
import com.diffplug.spotless.LineEnding;
import com.diffplug.spotless.ThrowingEx;
import com.diffplug.spotless.extra.EclipseBasedStepBuilder;
import com.diffplug.spotless.extra.wtp.EclipseWtpFormatterStep;
import com.diffplug.spotless.generic.EndWithNewlineStep;
import com.diffplug.spotless.generic.IndentStep;
import com.diffplug.spotless.generic.LicenseHeaderStep;
import com.diffplug.spotless.generic.ReplaceRegexStep;
import com.diffplug.spotless.generic.ReplaceStep;
import com.diffplug.spotless.generic.TrimTrailingWhitespaceStep;
import com.diffplug.spotless.npm.PrettierFormatterStep;
import groovy.lang.Closure;
/** Adds a `spotless{Name}Check` and `spotless{Name}Apply` task. */
public class FormatExtension {
final SpotlessExtension root;
public FormatExtension(SpotlessExtension root) {
this.root = Objects.requireNonNull(root);
}
private String formatName() {
for (Map.Entry<String, FormatExtension> entry : root.formats.entrySet()) {
if (entry.getValue() == this) {
return entry.getKey();
}
}
throw new IllegalStateException("This format is not contained by any SpotlessExtension.");
}
boolean paddedCell = false;
/** Enables paddedCell mode. @see <a href="https://github.com/diffplug/spotless/blob/master/PADDEDCELL.md">Padded cell</a> */
public void paddedCell() {
paddedCell(true);
}
/** Enables paddedCell mode. @see <a href="https://github.com/diffplug/spotless/blob/master/PADDEDCELL.md">Padded cell</a> */
public void paddedCell(boolean paddedCell) {
this.paddedCell = paddedCell;
}
LineEnding lineEndings;
/** Returns the line endings to use (defaults to {@link SpotlessExtension#getLineEndings()}. */
public LineEnding getLineEndings() {
return lineEndings == null ? root.getLineEndings() : lineEndings;
}
/** Sets the line endings to use (defaults to {@link SpotlessExtension#getLineEndings()}. */
public void setLineEndings(LineEnding lineEndings) {
this.lineEndings = Objects.requireNonNull(lineEndings);
}
Charset encoding;
/** Returns the encoding to use (defaults to {@link SpotlessExtension#getEncoding()}. */
public Charset getEncoding() {
return encoding == null ? root.getEncoding() : encoding;
}
/** Sets the encoding to use (defaults to {@link SpotlessExtension#getEncoding()}. */
public void setEncoding(String name) {
setEncoding(Charset.forName(Objects.requireNonNull(name)));
}
/** Sets the encoding to use (defaults to {@link SpotlessExtension#getEncoding()}. */
public void setEncoding(Charset charset) {
encoding = Objects.requireNonNull(charset);
}
final FormatExceptionPolicyStrict exceptionPolicy = new FormatExceptionPolicyStrict();
/** Ignores errors in the given step. */
public void ignoreErrorForStep(String stepName) {
exceptionPolicy.excludeStep(Objects.requireNonNull(stepName));
}
/** Ignores errors for the given relative path. */
public void ignoreErrorForPath(String relativePath) {
exceptionPolicy.excludePath(Objects.requireNonNull(relativePath));
}
/** Sets encoding to use (defaults to {@link SpotlessExtension#getEncoding()}). */
public void encoding(String charset) {
setEncoding(charset);
}
/** The files to be formatted = (target - targetExclude). */
protected FileCollection target, targetExclude;
/**
* Sets which files should be formatted. Files to be formatted = (target - targetExclude).
*
* When this method is called multiple times, only the last call has any effect.
*
* FileCollections pass through raw.
* Strings are treated as the 'include' arg to fileTree, with project.rootDir as the dir.
* List<String> are treated as the 'includes' arg to fileTree, with project.rootDir as the dir.
* Anything else gets passed to getProject().files().
*/
public void target(Object... targets) {
this.target = parseTargets(targets);
}
/**
* Sets which files will be excluded from formatting. Files to be formatted = (target - targetExclude).
*
* When this method is called multiple times, only the last call has any effect.
*
* FileCollections pass through raw.
* Strings are treated as the 'include' arg to fileTree, with project.rootDir as the dir.
* List<String> are treated as the 'includes' arg to fileTree, with project.rootDir as the dir.
* Anything else gets passed to getProject().files().
*/
public void targetExclude(Object... targets) {
this.targetExclude = parseTargets(targets);
}
private FileCollection parseTargets(Object[] targets) {
requireElementsNonNull(targets);
if (targets.length == 0) {
return getProject().files();
} else if (targets.length == 1) {
return parseTarget(targets[0]);
} else {
if (Stream.of(targets).allMatch(o -> o instanceof String)) {
return parseTarget(Arrays.asList(targets));
} else {
FileCollection union = getProject().files();
for (Object target : targets) {
union = union.plus(parseTarget(target));
}
return union;
}
}
}
/**
* FileCollections pass through raw.
* Strings are treated as the 'include' arg to fileTree, with project.rootDir as the dir.
* List<String> are treated as the 'includes' arg to fileTree, with project.rootDir as the dir.
* Anything else gets passed to getProject().files().
*/
@SuppressWarnings("unchecked")
protected FileCollection parseTarget(Object target) {
if (target instanceof FileCollection) {
return (FileCollection) target;
} else if (target instanceof String ||
(target instanceof List && ((List<?>) target).stream().allMatch(o -> o instanceof String))) {
// since people are likely to do '**/*.md', we want to make sure to exclude folders
// they don't want to format which will slow down the operation greatly
File dir = getProject().getProjectDir();
List<String> excludes = new ArrayList<>();
// no git
excludes.add(".git");
// no .gradle
if (getProject() == getProject().getRootProject()) {
excludes.add(".gradle");
}
// no build folders (flatInclude means that subproject might not be subfolders, see https://github.com/diffplug/spotless/issues/121)
relativizeIfSubdir(excludes, dir, getProject().getBuildDir());
for (Project subproject : getProject().getSubprojects()) {
relativizeIfSubdir(excludes, dir, subproject.getBuildDir());
}
if (target instanceof String) {
return (FileCollection) getProject().fileTree(dir).include((String) target).exclude(excludes);
} else {
// target can only be a List<String> at this point
return (FileCollection) getProject().fileTree(dir).include((List<String>) target).exclude(excludes);
}
} else {
return getProject().files(target);
}
}
private static void relativizeIfSubdir(List<String> relativePaths, File root, File dest) {
String relativized = relativize(root, dest);
if (relativized != null) {
relativePaths.add(relativized);
}
}
/**
* Returns the relative path between root and dest,
* or null if dest is not a child of root.
*/
static @Nullable String relativize(File root, File dest) {
String rootPath = root.getAbsolutePath();
String destPath = dest.getAbsolutePath();
if (!destPath.startsWith(rootPath)) {
return null;
} else {
return destPath.substring(rootPath.length());
}
}
/** The steps that need to be added. */
protected final List<FormatterStep> steps = new ArrayList<>();
/** Adds a new step. */
public void addStep(FormatterStep newStep) {
Objects.requireNonNull(newStep);
int existingIdx = getExistingStepIdx(newStep.getName());
if (existingIdx != -1) {
throw new GradleException("Multiple steps with name '" + newStep.getName() + "' for spotless format '" + formatName() + "'");
}
steps.add(newStep);
}
/** Returns the existing step with the given name, if any. */
@Deprecated
protected @Nullable FormatterStep getExistingStep(String stepName) {
return steps.stream() //
.filter(step -> stepName.equals(step.getName())) //
.findFirst() //
.orElse(null);
}
/** Returns the index of the existing step with the given name, or -1 if no such step exists. */
protected int getExistingStepIdx(String stepName) {
for (int i = 0; i < steps.size(); ++i) {
if (steps.get(i).getName().equals(stepName)) {
return i;
}
}
return -1;
}
/** Replaces the given step. */
protected void replaceStep(FormatterStep replacementStep) {
int existingIdx = getExistingStepIdx(replacementStep.getName());
if (existingIdx == -1) {
throw new GradleException("Cannot replace step '" + replacementStep.getName() + "' for spotless format '" + formatName() + "' because it hasn't been added yet.");
}
steps.set(existingIdx, replacementStep);
}
/** Clears all of the existing steps. */
public void clearSteps() {
steps.clear();
}
/**
* An optional performance optimization if you are using any of the `custom` or `customLazy`
* methods. If you aren't explicitly calling `custom` or `customLazy`, then this method
* has no effect.
*
* Spotless tracks what files have changed from run to run, so that it can run faster
* by only checking files which have changed, or whose formatting steps have changed.
* If you use either the `custom` or `customLazy` methods, then gradle can never mark
* your files as `up-to-date`, because it can't know if perhaps the behavior of your
* custom function has changed.
*
* If you set `bumpThisNumberIfACustomStepChanges( <some number> )`, then spotless will
* assume that the custom rules have not changed if the number has not changed. If a
* custom rule does change, then you must bump the number so that spotless will know
* that it must recheck the files it has already checked.
*/
public void bumpThisNumberIfACustomStepChanges(int number) {
globalState = number;
}
private Serializable globalState = new NeverUpToDateBetweenRuns();
static class NeverUpToDateBetweenRuns extends LazyForwardingEquality<Integer> {
private static final long serialVersionUID = 1L;
private static final Random RANDOM = new Random();
@Override
protected Integer calculateState() throws Exception {
return RANDOM.nextInt();
}
}
/**
* Adds the given custom step, which is constructed lazily for performance reasons.
*
* The resulting function will receive a string with unix-newlines, and it must return a string unix newlines.
*
* If you're getting errors about `closure cannot be cast to com.diffplug.common.base.Throwing$Function`, then use
* {@link #customLazyGroovy(String, ThrowingEx.Supplier)}.
*/
public void customLazy(String name, ThrowingEx.Supplier<FormatterFunc> formatterSupplier) {
Objects.requireNonNull(name, "name");
Objects.requireNonNull(formatterSupplier, "formatterSupplier");
addStep(FormatterStep.createLazy(name, () -> globalState, unusedState -> formatterSupplier.get()));
}
/** Same as {@link #customLazy(String, ThrowingEx.Supplier)}, but for Groovy closures. */
public void customLazyGroovy(String name, ThrowingEx.Supplier<Closure<String>> formatterSupplier) {
Objects.requireNonNull(formatterSupplier, "formatterSupplier");
customLazy(name, () -> formatterSupplier.get()::call);
}
/** Adds a custom step. Receives a string with unix-newlines, must return a string with unix newlines. */
public void custom(String name, Closure<String> formatter) {
Objects.requireNonNull(formatter, "formatter");
custom(name, formatter::call);
}
/** Adds a custom step. Receives a string with unix-newlines, must return a string with unix newlines. */
public void custom(String name, FormatterFunc formatter) {
Objects.requireNonNull(formatter, "formatter");
customLazy(name, () -> formatter);
}
/** Highly efficient find-replace char sequence. */
public void replace(String name, CharSequence original, CharSequence after) {
addStep(ReplaceStep.create(name, original, after));
}
/** Highly efficient find-replace regex. */
public void replaceRegex(String name, String regex, String replacement) {
addStep(ReplaceRegexStep.create(name, regex, replacement));
}
/** Removes trailing whitespace. */
public void trimTrailingWhitespace() {
addStep(TrimTrailingWhitespaceStep.create());
}
/** Ensures that files end with a single newline. */
public void endWithNewline() {
addStep(EndWithNewlineStep.create());
}
/** Ensures that the files are indented using spaces. */
public void indentWithSpaces(int numSpacesPerTab) {
addStep(IndentStep.Type.SPACE.create(numSpacesPerTab));
}
/** Ensures that the files are indented using spaces. */
public void indentWithSpaces() {
addStep(IndentStep.Type.SPACE.create());
}
/** Ensures that the files are indented using tabs. */
public void indentWithTabs(int tabToSpaces) {
addStep(IndentStep.Type.TAB.create(tabToSpaces));
}
/** Ensures that the files are indented using tabs. */
public void indentWithTabs() {
addStep(IndentStep.Type.TAB.create());
}
abstract class LicenseHeaderConfig {
String delimiter;
String yearSeparator = LicenseHeaderStep.defaultYearDelimiter();
public LicenseHeaderConfig(String delimiter) {
this.delimiter = Objects.requireNonNull(delimiter, "delimiter");
}
/**
* @param delimiter
* Spotless will look for a line that starts with this regular expression pattern to know what the "top" is.
*/
public LicenseHeaderConfig delimiter(String delimiter) {
this.delimiter = Objects.requireNonNull(delimiter, "delimiter");
replaceStep(createStep());
return this;
}
/**
* @param yearSeparator
* The characters used to separate the first and last years in multi years patterns.
*/
public LicenseHeaderConfig yearSeparator(String yearSeparator) {
this.yearSeparator = Objects.requireNonNull(yearSeparator, "yearSeparator");
replaceStep(createStep());
return this;
}
abstract FormatterStep createStep();
}
class LicenseStringHeaderConfig extends LicenseHeaderConfig {
private String header;
LicenseStringHeaderConfig(String delimiter, String header) {
super(delimiter);
this.header = Objects.requireNonNull(header, "header");
}
FormatterStep createStep() {
return LicenseHeaderStep.createFromHeader(header, delimiter, yearSeparator);
}
}
class LicenseFileHeaderConfig extends LicenseHeaderConfig {
private Object headerFile;
LicenseFileHeaderConfig(String delimiter, Object headerFile) {
super(delimiter);
this.headerFile = Objects.requireNonNull(headerFile, "headerFile");
}
FormatterStep createStep() {
return LicenseHeaderStep
.createFromFile(getProject().file(headerFile), getEncoding(), delimiter,
yearSeparator);
}
}
/**
* @param licenseHeader
* Content that should be at the top of every file.
* @param delimiter
* Spotless will look for a line that starts with this regular expression pattern to know what the "top" is.
*/
public LicenseHeaderConfig licenseHeader(String licenseHeader, String delimiter) {
LicenseHeaderConfig config = new LicenseStringHeaderConfig(delimiter, licenseHeader);
addStep(config.createStep());
return config;
}
/**
* @param licenseHeaderFile
* Content that should be at the top of every file.
* @param delimiter
* Spotless will look for a line that starts with this regular expression pattern to know what the "top" is.
*/
public LicenseHeaderConfig licenseHeaderFile(Object licenseHeaderFile, String delimiter) {
LicenseHeaderConfig config = new LicenseFileHeaderConfig(delimiter, licenseHeaderFile);
addStep(config.createStep());
return config;
}
public abstract class NpmStepConfig<T extends NpmStepConfig<?>> {
@Nullable
protected Object npmFile;
@SuppressWarnings("unchecked")
public T npmExecutable(final Object npmFile) {
this.npmFile = npmFile;
replaceStep(createStep());
return (T) this;
}
File npmFileOrNull() {
return npmFile != null ? getProject().file(npmFile) : null;
}
abstract FormatterStep createStep();
}
public class PrettierConfig extends NpmStepConfig<PrettierConfig> {
@Nullable
Object prettierConfigFile;
@Nullable
Map<String, Object> prettierConfig;
final Map<String, String> devDependencies;
PrettierConfig(Map<String, String> devDependencies) {
this.devDependencies = Objects.requireNonNull(devDependencies);
}
public PrettierConfig configFile(final Object prettierConfigFile) {
this.prettierConfigFile = prettierConfigFile;
replaceStep(createStep());
return this;
}
public PrettierConfig config(final Map<String, Object> prettierConfig) {
this.prettierConfig = new TreeMap<>(prettierConfig);
replaceStep(createStep());
return this;
}
FormatterStep createStep() {
final Project project = getProject();
return PrettierFormatterStep.create(
devDependencies,
GradleProvisioner.fromProject(project),
project.getBuildDir(),
npmFileOrNull(),
new com.diffplug.spotless.npm.PrettierConfig(
this.prettierConfigFile != null ? project.file(this.prettierConfigFile) : null,
this.prettierConfig));
}
}
/** Uses the default version of prettier. */
public PrettierConfig prettier() {
return prettier(PrettierFormatterStep.defaultDevDependencies());
}
/** Uses the specified version of prettier. */
public PrettierConfig prettier(String version) {
return prettier(PrettierFormatterStep.defaultDevDependenciesWithPrettier(version));
}
/** Uses exactly the npm packages specified in the map. */
public PrettierConfig prettier(Map<String, String> devDependencies) {
PrettierConfig prettierConfig = new PrettierConfig(devDependencies);
addStep(prettierConfig.createStep());
return prettierConfig;
}
public class EclipseWtpConfig {
private final EclipseBasedStepBuilder builder;
EclipseWtpConfig(EclipseWtpFormatterStep type, String version) {
builder = type.createBuilder(GradleProvisioner.fromProject(getProject()));
builder.setVersion(version);
addStep(builder.build());
}
public void configFile(Object... configFiles) {
requireElementsNonNull(configFiles);
Project project = getProject();
builder.setPreferences(project.files(configFiles).getFiles());
replaceStep(builder.build());
}
}
public EclipseWtpConfig eclipseWtp(EclipseWtpFormatterStep type) {
return eclipseWtp(type, EclipseWtpFormatterStep.defaultVersion());
}
public EclipseWtpConfig eclipseWtp(EclipseWtpFormatterStep type, String version) {
return new EclipseWtpConfig(type, version);
}
/** Sets up a format task according to the values in this extension. */
protected void setupTask(SpotlessTask task) {
task.setPaddedCell(paddedCell);
task.setEncoding(getEncoding().name());
task.setExceptionPolicy(exceptionPolicy);
if (targetExclude == null) {
task.setTarget(target);
} else {
task.setTarget(target.minus(targetExclude));
}
task.setSteps(steps);
task.setLineEndingsPolicy(getLineEndings().createPolicy(getProject().getProjectDir(), () -> task.target));
}
/** Returns the project that this extension is attached to. */
protected Project getProject() {
return root.project;
}
}
| Add plumbing to FormatExtension to differentiate between parsing with the intent to include files, versus parsing with the intent to exclude files. | plugin-gradle/src/main/java/com/diffplug/gradle/spotless/FormatExtension.java | Add plumbing to FormatExtension to differentiate between parsing with the intent to include files, versus parsing with the intent to exclude files. |
|
Java | apache-2.0 | c25dc3f4edfeb3cafd361ed64f780d53f5f366c8 | 0 | ottogroup/flink-spector | package org.flinkspector.core.runtime;
import com.google.common.primitives.Bytes;
import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.api.java.typeutils.TypeExtractor;
import org.apache.flink.core.memory.DataOutputViewStreamWrapper;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
/**
* This class is used to send output from Apache Flink to the listening runtime.
*/
public class OutputPublisher {
private AtomicInteger msgCount = new AtomicInteger(0);
private Set<Integer> closed = new HashSet<Integer>();
private Socket client;
private OutputStream outputStream;
private DataOutputViewStreamWrapper streamWriter;
TypeSerializer<byte[]> serializer;
private InetAddress hostAdress;
private int port;
private int parallelism = -1;
private boolean socketOpen = false;
public OutputPublisher(String host, int port) throws UnknownHostException {
//TODO: hostAddress from constructor
hostAdress = InetAddress.getLoopbackAddress();
this.port = port;
//TODO: use real config
ExecutionConfig config = new ExecutionConfig();
TypeInformation<byte[]> typeInfo = TypeExtractor.getForObject(new byte[0]);
serializer = typeInfo.createSerializer(config);
}
private void open() {
if (!socketOpen) {
try {
client = new Socket(hostAdress, port);
outputStream = client.getOutputStream();
streamWriter = new DataOutputViewStreamWrapper(outputStream);
} catch (IOException e) {
e.printStackTrace();
}
socketOpen = true;
}
}
/**
* Send a opening message to the subscriber.
* Signaling the start of output.
*
* @param taskNumber index of the subtask.
* @param numTasks number of parallelism.
* @param serializer serialized serializer.
*/
public synchronized void sendOpen(int taskNumber,
int numTasks,
byte[] serializer) {
String open = String.format("OPEN %d %d",
taskNumber,
numTasks);
byte[] msg = Bytes.concat((open + " ;").getBytes(), serializer);
parallelism = numTasks;
sendBytes(msg);
}
private void sendBytes(byte[] bytes) {
open();
try {
serializer.serialize(bytes, streamWriter);
} catch (IOException e) {
e.printStackTrace();
//dumb retry
sendBytes(bytes);
}
}
public void send(byte[] bytes) {
sendBytes(bytes);
}
public void send(String string) {
sendBytes(string.getBytes(StandardCharsets.UTF_8));
}
/**
* Send a record message to the subscriber.
*
* @param bytes serialized record.
*/
public synchronized void sendRecord(byte[] bytes) {
byte[] msg = Bytes.concat("REC".getBytes(), bytes);
msgCount.incrementAndGet();
sendBytes(msg);
}
/**
* Signal the closing of the output producer.
*
* @param taskNumber index of the subtask.
*/
public synchronized void sendClose(int taskNumber) {
if (!closed.contains(taskNumber)) {
String close = String.format("CLOSE %d %d",
taskNumber, msgCount.get());
sendBytes(close.getBytes());
closed.add(taskNumber);
}
if(closed.size() == parallelism) {
try {
close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void close() throws IOException {
try {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
// first regular attempt to cleanly close. Failing that will escalate
if (client != null) {
client.close();
}
} catch (Exception e) {
throw new IOException("Error while closing connection that streams data back to client at "
+ hostAdress.toString() + ":" + port, e);
} finally {
// if we failed prior to closing the client, close it
if (client != null) {
try {
client.close();
} catch (Throwable t) {
// best effort to close, we do not care about an exception here any more
}
}
}
}
}
| flinkspector-core/src/main/java/org/flinkspector/core/runtime/OutputPublisher.java | package org.flinkspector.core.runtime;
import com.google.common.primitives.Bytes;
import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.common.typeutils.TypeSerializer;
import org.apache.flink.api.java.typeutils.TypeExtractor;
import org.apache.flink.core.memory.DataOutputViewStreamWrapper;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
/**
* This class is used to send output from Apache Flink to the listening runtime.
*/
public class OutputPublisher {
private AtomicInteger msgCount = new AtomicInteger(0);
private Set<Integer> closed = new HashSet<Integer>();
private Socket client;
private OutputStream outputStream;
private DataOutputViewStreamWrapper streamWriter;
TypeSerializer<byte[]> serializer;
private InetAddress hostAdress;
private int port;
private int parallelism = -1;
private boolean socketOpen = false;
public OutputPublisher(String host, int port) throws UnknownHostException {
//TODO: hostAddress from constructor
hostAdress = InetAddress.getLoopbackAddress();
this.port = port;
//TODO: use real config
ExecutionConfig config = new ExecutionConfig();
TypeInformation<byte[]> typeInfo = TypeExtractor.getForObject(new byte[0]);
serializer = typeInfo.createSerializer(config);
}
private void open() {
if (!socketOpen) {
try {
client = new Socket(hostAdress, port);
outputStream = client.getOutputStream();
streamWriter = new DataOutputViewStreamWrapper(outputStream);
} catch (IOException e) {
e.printStackTrace();
}
socketOpen = true;
}
}
/**
* Send a opening message to the subscriber.
* Signaling the start of output.
*
* @param taskNumber index of the subtask.
* @param numTasks number of parallelism.
* @param serializer serialized serializer.
*/
public synchronized void sendOpen(int taskNumber,
int numTasks,
byte[] serializer) {
String open = String.format("OPEN %d %d",
taskNumber,
numTasks);
byte[] msg = Bytes.concat((open + " ;").getBytes(), serializer);
parallelism = numTasks;
sendBytes(msg);
}
private void sendBytes(byte[] bytes) {
open();
try {
serializer.serialize(bytes, streamWriter);
} catch (IOException e) {
e.printStackTrace();
}
}
public void send(byte[] bytes) {
sendBytes(bytes);
}
public void send(String string) {
sendBytes(string.getBytes(StandardCharsets.UTF_8));
}
/**
* Send a record message to the subscriber.
*
* @param bytes serialized record.
*/
public synchronized void sendRecord(byte[] bytes) {
byte[] msg = Bytes.concat("REC".getBytes(), bytes);
msgCount.incrementAndGet();
sendBytes(msg);
}
/**
* Signal the closing of the output producer.
*
* @param taskNumber index of the subtask.
*/
public synchronized void sendClose(int taskNumber) {
if (!closed.contains(taskNumber)) {
String close = String.format("CLOSE %d %d",
taskNumber, msgCount.get());
sendBytes(close.getBytes());
closed.add(taskNumber);
}
if(closed.size() == parallelism) {
try {
close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void close() throws IOException {
try {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
// first regular attempt to cleanly close. Failing that will escalate
if (client != null) {
client.close();
}
} catch (Exception e) {
throw new IOException("Error while closing connection that streams data back to client at "
+ hostAdress.toString() + ":" + port, e);
} finally {
// if we failed prior to closing the client, close it
if (client != null) {
try {
client.close();
} catch (Throwable t) {
// best effort to close, we do not care about an exception here any more
}
}
}
}
}
| retrying
| flinkspector-core/src/main/java/org/flinkspector/core/runtime/OutputPublisher.java | retrying |
|
Java | apache-2.0 | 0b359aec15f2e7a03cf8b8c0514a2eac3a31b124 | 0 | jusjoken/gemstone2 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Gemstone;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.RoundingMode;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.TreeSet;
import java.util.logging.Level;
import org.apache.log4j.Logger;
import sagex.UIContext;
import sagex.phoenix.vfs.IMediaResource;
import sagex.phoenix.vfs.views.ViewFolder;
/**
*
* @author SBANTA
* @author JUSJOKEN
* - 10/09/2011 - added LOG4J setup and Main method for testing, and StringNumberFormat
* - 10/10/2011 - added some generic functions
* - 04/04/2012 - updated for Gemstone
*/
public class util {
static private final Logger LOG = Logger.getLogger(util.class);
public static final char[] symbols = new char[36];
private static final Random random = new Random();
public static final String OptionNotFound = "Option not Found";
public static enum TriState{YES,NO,OTHER};
public static enum ExportType{ALL,WIDGETS,FLOWS,FLOW,MENUS,GENERAL};
public static final String ListToken = ":&&:";
public static void main(String[] args){
//String test = StringNumberFormat("27.96903", 0, 2);
//String test = StringNumberFormat("27.1", 0, 2);
//LOG.debug(test);
//api.InitLogger();
test1();
}
public static void test1(){
PropertiesExt Props = new PropertiesExt();
String FilePath = util.UserDataLocation() + File.separator + "menutest.properties";
Boolean KeepProcessing = Boolean.TRUE;
//read the properties from the properties file
try {
FileInputStream in = new FileInputStream(FilePath);
try {
Props.load(in);
in.close();
} catch (IOException ex) {
LOG.debug("test1: IO exception inporting properties " + util.class.getName() + ex);
KeepProcessing = Boolean.FALSE;
}
} catch (FileNotFoundException ex) {
LOG.debug("test1: file not found inporting properties " + util.class.getName() + ex);
KeepProcessing = Boolean.FALSE;
}
if (KeepProcessing){
LOG.debug("test1: start of BRANCHES");
for (String Key:Props.GetSubpropertiesThatAreBranches("Gemstone/Widgets")){
LOG.debug("TEST item '" + Key + "'");
}
LOG.debug("test1: start of LEAVES");
for (String Key:Props.GetSubpropertiesThatAreLeaves("Gemstone/Widgets")){
LOG.debug("TEST item '" + Key + "'");
}
}
}
private static void print(Map map) {
LOG.debug("One=" + map.get("One"));
LOG.debug("Two=" + map.get("Two"));
LOG.debug("Three=" + map.get("Three"));
LOG.debug("Four=" + map.get("Four"));
LOG.debug("Five=" + map.get("Five"));
}
private static void print2(Map map, Integer items) {
for(int i=1; i<=items; i++){
LOG.debug("TEST " + map.getClass() + " ITEMS '" + items + "' - " + TempName(i) + "=" + map.get(TempName(i)) + " Mem = '" + FreeMem() + "'");
}
}
private static void testMap(Map map, Integer Multiplier) {
LOG.debug("Testing " + map.getClass());
for(int i=1; i<=Multiplier; i++){
map.put(TempName(i), new byte[10*1024*1024]);
print2(map,i);
}
// LOG.debug("Adding 10MB * " + Multiplier);
//// for(int i=1; i<=Multiplier; i++){
// byte[] block = new byte[10*1024*1024*Multiplier]; // 10 MB
//// }
// print(map);
}
public static String FreeMem() {
Long total = Runtime.getRuntime().totalMemory();
Long free = Runtime.getRuntime().freeMemory();
String InfoText = Math.round((total-free)/1000000.0) + "MB/";
return InfoText;
}
public static void LogFreeMem(String Message) {
Long total = Runtime.getRuntime().totalMemory();
Long free = Runtime.getRuntime().freeMemory();
String InfoText = Math.round((total-free)/1000000.0) + "MB";
LOG.debug(Message + " FreeMem '" + InfoText + "'");
}
private static String TempName(Integer i) {
return "Item_" + i;
}
// private static void testMap(Map map, Integer Multiplier) {
// LOG.debug("Testing " + map.getClass());
// map.put("One", new Integer(1));
// map.put("Two", new Integer(2));
// map.put("Three", new Integer(3));
// map.put("Four", new Integer(4));
// map.put("Five", new Integer(5));
// print(map);
// LOG.debug("Adding 10MB * " + Multiplier);
//// for(int i=1; i<=Multiplier; i++){
// byte[] block = new byte[10*1024*1024*Multiplier]; // 10 MB
//// }
// print(map);
// }
public static void test1(Integer Min, Integer Multiplier) {
testMap(new SoftHashMap(Min), Multiplier);
//testMap(new HashMap(), Multiplier);
}
//pass in a String that contains a number and this will format it to a specific number of decimal places
public static String StringNumberFormat(String Input, Integer DecimalPlaces){
return StringNumberFormat(Input, DecimalPlaces, DecimalPlaces);
}
public static String StringNumberFormat(String Input, Integer MinDecimalPlaces, Integer MaxDecimalPlaces){
float a = 0;
try {
a = Float.parseFloat(Input);
} catch (NumberFormatException nfe) {
LOG.error("StringNumberFormat - NumberFormatException for '" + Input + "'");
return Input;
}
NumberFormat df = DecimalFormat.getInstance();
df.setMinimumFractionDigits(MinDecimalPlaces);
df.setMaximumFractionDigits(MaxDecimalPlaces);
df.setRoundingMode(RoundingMode.DOWN);
String retString = df.format(a);
return retString;
}
public static Object CheckSeasonSize(Map<String, Object> Files, int sizeneeded) {
LinkedHashMap<String, Object> WithBlanks = new LinkedHashMap<String, Object>();
for(int index=0;index<sizeneeded;index++){
WithBlanks.put("blankelement1"+index, null);}
WithBlanks.putAll(Files);
for(int index=sizeneeded;index<sizeneeded+sizeneeded;index++){
WithBlanks.put("blankelement"+index, null);}
return WithBlanks;
}
public static Object CheckCategorySize(Map<String, Object> Files) {
LinkedHashMap<String, Object> WithBlanks = new LinkedHashMap<String, Object>();
WithBlanks.put("blankelement1", null);
WithBlanks.putAll(Files);
WithBlanks.put("blankelement4", null);
return WithBlanks;
}
public static Object CheckSimpleSize(Object[] Files,int sizeneeded) {
if (!Files.toString().contains("blankelement")) {
List<Object> WithBlanks = new ArrayList<Object>();
for(int index=0;index<sizeneeded;index++){
WithBlanks.add("blankelement"+index);}
for (Object curr : Files) {
WithBlanks.add(curr);
}
for(int index=sizeneeded;index<sizeneeded+sizeneeded;index++){
WithBlanks.add("blankelement"+index);}
return WithBlanks;
}
return Files;
}
public static Object CheckFileSize(List<Object> files, String diamondprop) {
String viewtype = Flow.GetFlowType(diamondprop);
ArrayList<Object> NewList = new ArrayList<Object>();
if (viewtype == "Wall Flow" && files.size() < 5) {
} else if (viewtype == "Cover Flow" && files.size() < 7) {
NewList.add(null);
NewList.add(null);
NewList.add(null);
NewList.addAll(files);
NewList.add(null);
NewList.add(null);
return NewList;
}
return files;
}
public static LinkedHashMap<String, Integer> GetLetterLocations(Object[] MediaFiles) {
String CurrentLocation = "845948921";
Boolean ScrapTitle = Boolean.parseBoolean(sagex.api.Configuration.GetProperty("ui/ignore_the_when_sorting", "false"));
LinkedHashMap<String, Integer> Values = new LinkedHashMap<String, Integer>();
String Title = "";
int i = 0;
for (Object curr : MediaFiles) {
if (ScrapTitle) {
Title = MetadataCalls.GetSortTitle(curr);
} else {
Title = MetadataCalls.GetMediaTitle(curr);
}
if (!Title.startsWith(CurrentLocation)) {
CurrentLocation = Title.substring(0, 1);
Values.put(CurrentLocation.toLowerCase(), i);
}
i++;
}
return Values;
}
// public static HashMap<Object,Object> GetHeaders(Object MediaFiles,String Method){
// Object[] Files = FanartCaching.toArray(MediaFiles);
// HashMap<Object,Object> Headers = new HashMap<Object,Object>();
// Object CurrGroup=null;
// if(Method.contains("AirDate")){
// for(Object curr:Files){
// Object thisvalue=GetTimeAdded(curr);
// if(thisvalue!=CurrGroup){
// Headers.put(curr,thisvalue);
// CurrGroup=thisvalue;}}
//
// }
// else if (Method.contains("Title")){
// for(Object curr:Files){
// String thisvalues=ClassFromString.GetSortDividerClass(Method,curr).toString();
// Object thisvalue=thisvalues.substring(0,1);
// if(!thisvalue.equals(CurrGroup)){
// Headers.put(curr,thisvalue);
// CurrGroup=thisvalue;}
// }
//
// }
// return Headers;}
public static boolean IsHeader(Map headers, Object Key) {
return headers.containsKey(Key);
}
public static String GenerateRandomName(){
char[] buf = new char[10];
for (int idx = 0; idx < buf.length; ++idx)
buf[idx] = symbols[random.nextInt(symbols.length)];
return "sd" + new String(buf);
}
public static Boolean HasProperty(String Property){
String tValue = sagex.api.Configuration.GetProperty(new UIContext(sagex.api.Global.GetUIContextName()),Property, null);
if (tValue==null || tValue.equals(OptionNotFound)){
return Boolean.FALSE;
}else{
return Boolean.TRUE;
}
}
public static String GetProperty(String Property, String DefaultValue){
String tValue = sagex.api.Configuration.GetProperty(new UIContext(sagex.api.Global.GetUIContextName()),Property, null);
if (tValue==null || tValue.equals(OptionNotFound)){
return DefaultValue;
}else{
return tValue;
}
}
public static Boolean GetPropertyAsBoolean(String Property, Boolean DefaultValue){
String tValue = sagex.api.Configuration.GetProperty(new UIContext(sagex.api.Global.GetUIContextName()),Property, null);
if (tValue==null || tValue.equals(OptionNotFound)){
return DefaultValue;
}else{
return Boolean.parseBoolean(tValue);
}
}
//Evaluates the property and returns it's value - must be true or false - returns true otherwise
public static Boolean GetPropertyEvalAsBoolean(String Property, Boolean DefaultValue){
String tValue = sagex.api.Configuration.GetProperty(new UIContext(sagex.api.Global.GetUIContextName()),Property, null);
if (tValue==null || tValue.equals(OptionNotFound)){
return DefaultValue;
}else{
return Boolean.parseBoolean(EvaluateAttribute(tValue));
}
}
public static TriState GetPropertyAsTriState(String Property, TriState DefaultValue){
String tValue = sagex.api.Configuration.GetProperty(new UIContext(sagex.api.Global.GetUIContextName()),Property, null);
if (tValue==null || tValue.equals(OptionNotFound)){
return DefaultValue;
}else if(tValue.equals("YES")){
return TriState.YES;
}else if(tValue.equals("NO")){
return TriState.NO;
}else if(tValue.equals("OTHER")){
return TriState.OTHER;
}else if(Boolean.parseBoolean(tValue)){
return TriState.YES;
}else if(!Boolean.parseBoolean(tValue)){
return TriState.NO;
}else{
return TriState.YES;
}
}
public static List<String> GetPropertyAsList(String Property){
String tValue = sagex.api.Configuration.GetProperty(new UIContext(sagex.api.Global.GetUIContextName()),Property, null);
if (tValue==null || tValue.equals(OptionNotFound)){
return new LinkedList<String>();
}else{
return ConvertStringtoList(tValue);
}
}
public static Integer GetPropertyAsInteger(String Property, Integer DefaultValue){
//read in the Sage Property and force convert it to an Integer
Integer tInteger = DefaultValue;
String tValue = sagex.api.Configuration.GetProperty(new UIContext(sagex.api.Global.GetUIContextName()),Property, null);
if (tValue==null || tValue.equals(OptionNotFound)){
return DefaultValue;
}
try {
tInteger = Integer.valueOf(tValue);
} catch (NumberFormatException ex) {
//use DefaultValue
return DefaultValue;
}
return tInteger;
}
public static Double GetPropertyAsDouble(String Property, Double DefaultValue){
//read in the Sage Property and force convert it to an Integer
Double tDouble = DefaultValue;
String tValue = sagex.api.Configuration.GetProperty(new UIContext(sagex.api.Global.GetUIContextName()),Property, null);
if (tValue==null || tValue.equals(OptionNotFound)){
return DefaultValue;
}
try {
tDouble = Double.valueOf(tValue);
} catch (NumberFormatException ex) {
//use DefaultValue
return DefaultValue;
}
return tDouble;
}
public static String GetServerProperty(String Property, String DefaultValue){
String tValue = sagex.api.Configuration.GetServerProperty(new UIContext(sagex.api.Global.GetUIContextName()),Property, null);
if (tValue==null || tValue.equals(OptionNotFound)){
return DefaultValue;
}else{
return tValue;
}
}
public static void SetProperty(String Property, String Value){
sagex.api.Configuration.SetProperty(new UIContext(sagex.api.Global.GetUIContextName()),Property, Value);
}
public static void SetPropertyAsTriState(String Property, TriState Value){
sagex.api.Configuration.SetProperty(new UIContext(sagex.api.Global.GetUIContextName()),Property, Value.toString());
}
public static void SetPropertyAsList(String Property, List<String> ListValue){
String Value = ConvertListtoString(ListValue);
if (ListValue.size()>0){
sagex.api.Configuration.SetProperty(new UIContext(sagex.api.Global.GetUIContextName()),Property, Value);
}else{
RemoveProperty(Property);
}
}
public static void SetServerProperty(String Property, String Value){
sagex.api.Configuration.SetServerProperty(new UIContext(sagex.api.Global.GetUIContextName()),Property, Value);
}
public static void RemoveServerProperty(String Property){
sagex.api.Configuration.RemoveServerProperty(new UIContext(sagex.api.Global.GetUIContextName()),Property);
}
public static void RemovePropertyAndChildren(String Property){
sagex.api.Configuration.RemovePropertyAndChildren(new UIContext(sagex.api.Global.GetUIContextName()),Property);
}
public static void RemoveProperty(String Property){
sagex.api.Configuration.RemoveProperty(new UIContext(sagex.api.Global.GetUIContextName()),Property);
}
public static void RemoveServerPropertyAndChildren(String Property){
sagex.api.Configuration.RemoveServerPropertyAndChildren(new UIContext(sagex.api.Global.GetUIContextName()),Property);
}
public static String ConvertListtoString(List<String> ListValue){
return ConvertListtoString(ListValue, ListToken);
}
public static String ConvertListtoString(List<String> ListValue, String Separator){
String Value = "";
if (ListValue.size()>0){
Boolean tFirstItem = Boolean.TRUE;
for (String ListItem : ListValue){
if (tFirstItem){
Value = ListItem;
tFirstItem = Boolean.FALSE;
}else{
Value = Value + Separator + ListItem;
}
}
}
return Value;
}
public static List<String> ConvertStringtoList(String tValue){
if (tValue.equals(OptionNotFound) || tValue.equals("") || tValue==null){
return new LinkedList<String>();
}else{
return Arrays.asList(tValue.split(ListToken));
}
}
public static String EvaluateAttribute(String Attribute){
//LOG.debug("EvaluateAttribute: Attribute = '" + Attribute + "'");
Object[] passvalue = new Object[1];
passvalue[0] = sagex.api.WidgetAPI.EvaluateExpression(new UIContext(sagex.api.Global.GetUIContextName()), Attribute);
if (passvalue[0]==null){
LOG.debug("EvaluateAttribute for Attribute = '" + Attribute + "' not evaluated.");
return OptionNotFound;
}else{
//LOG.debug("EvaluateAttribute for Attribute = '" + Attribute + "' = '" + passvalue[0].toString() + "'");
return passvalue[0].toString();
}
}
public static void OptionsClear(){
//clear all the Options settings used only while the Options menu is open
String tProp = Const.BaseProp + Const.PropDivider + Const.OptionsFocused;
RemovePropertyAndChildren(tProp);
tProp = Const.BaseProp + Const.PropDivider + Const.OptionsType;
RemovePropertyAndChildren(tProp);
tProp = Const.BaseProp + Const.PropDivider + Const.OptionsTitle;
RemovePropertyAndChildren(tProp);
}
public static void OptionsLastFocusedSet(Integer CurrentLevel, String FocusedItem){
String tProp = Const.BaseProp + Const.PropDivider + Const.OptionsFocused + Const.PropDivider + CurrentLevel.toString() + Const.PropDivider + Const.OptionsFocusedItem;
//LOG.debug("OptionsLastFocusedSet: CurrentLevel = '" + CurrentLevel + "' FocusedItem = '" + FocusedItem + "'");
SetProperty(tProp, FocusedItem);
}
public static String OptionsLastFocusedGet(Integer CurrentLevel){
String tProp = Const.BaseProp + Const.PropDivider + Const.OptionsFocused + Const.PropDivider + CurrentLevel.toString() + Const.PropDivider + Const.OptionsFocusedItem;
String FocusedItem = GetProperty(tProp, OptionNotFound);
//LOG.debug("OptionsLastFocusedGet: CurrentLevel = '" + CurrentLevel + "' FocusedItem = '" + FocusedItem + "'");
return FocusedItem;
}
public static String OptionsTypeGet(Integer CurrentLevel){
String tProp = Const.BaseProp + Const.PropDivider + Const.OptionsType + Const.PropDivider + CurrentLevel.toString() + Const.PropDivider + Const.OptionsTypeName;
String OptionsType = GetProperty(tProp, OptionNotFound);
//LOG.debug("OptionsTypeGet: CurrentLevel = '" + CurrentLevel + "' OptionsType = '" + OptionsType + "'");
return OptionsType;
}
public static Integer OptionsTypeSet(Integer CurrentLevel, String OptionsType){
String tProp = Const.BaseProp + Const.PropDivider + Const.OptionsType + Const.PropDivider + CurrentLevel.toString() + Const.PropDivider + Const.OptionsTypeName;
//LOG.debug("OptionsTypeSet: CurrentLevel = '" + CurrentLevel + "' OptionsType = '" + OptionsType + "'");
SetProperty(tProp, OptionsType);
return CurrentLevel;
}
public static void OptionsTitleSet(Integer CurrentLevel, String Title){
String tProp = Const.BaseProp + Const.PropDivider + Const.OptionsTitle + Const.PropDivider + CurrentLevel.toString() + Const.PropDivider + Const.OptionsTitleName;
//LOG.debug("OptionsTitleSet: CurrentLevel = '" + CurrentLevel + "' Title = '" + Title + "'");
SetProperty(tProp, Title);
}
public static String OptionsTitleGet(Integer CurrentLevel){
String tProp = Const.BaseProp + Const.PropDivider + Const.OptionsTitle + Const.PropDivider + CurrentLevel.toString() + Const.PropDivider + Const.OptionsTitleName;
String Title = GetProperty(tProp, OptionNotFound);
//LOG.debug("OptionsTitleGet: CurrentLevel = '" + CurrentLevel + "' Title = '" + Title + "'");
return Title;
}
//Set of functions for Get/Set of generic True/False values with passed in test names to display
public static Boolean GetTrueFalseOption(String PropSection, String PropName){
return GetTrueFalseOptionBase(Boolean.FALSE, PropSection, PropName, Boolean.FALSE);
}
public static Boolean GetTrueFalseOption(String PropSection, String PropName, Boolean DefaultValue){
return GetTrueFalseOptionBase(Boolean.FALSE, PropSection, PropName, DefaultValue);
}
public static Boolean GetTrueFalseOptionBase(Boolean bFlow, String PropSection, String PropName, Boolean DefaultValue){
String tProp = "";
if (PropName.equals("")){ //expect the full property string in the PropSection
tProp = PropSection;
}else{
if (bFlow){
tProp = Flow.GetFlowBaseProp(PropSection) + Const.PropDivider + PropName;
}else{
tProp = Const.BaseProp + Const.PropDivider + PropSection + Const.PropDivider + PropName;
}
}
return util.GetPropertyAsBoolean(tProp, DefaultValue);
}
public static String GetTrueFalseOptionName(String PropSection, String TrueValue, String FalseValue, Boolean DefaultValue){
return GetTrueFalseOptionNameBase(Boolean.FALSE, PropSection, "", TrueValue, FalseValue, DefaultValue);
}
public static String GetTrueFalseOptionName(String PropSection, String TrueValue, String FalseValue){
return GetTrueFalseOptionNameBase(Boolean.FALSE, PropSection, "", TrueValue, FalseValue, Boolean.FALSE);
}
public static String GetTrueFalseOptionName(String PropSection, String PropName, String TrueValue, String FalseValue){
return GetTrueFalseOptionNameBase(Boolean.FALSE, PropSection, PropName, TrueValue, FalseValue, Boolean.FALSE);
}
public static String GetTrueFalseOptionName(String PropSection, String PropName, String TrueValue, String FalseValue, Boolean DefaultValue){
return GetTrueFalseOptionNameBase(Boolean.FALSE, PropSection, PropName, TrueValue, FalseValue, DefaultValue);
}
public static String GetTrueFalseOptionNameBase(Boolean bFlow, String PropSection, String PropName, String TrueValue, String FalseValue, Boolean DefaultValue){
String tProp = "";
if (PropName.equals("")){ //expect the full property string in the PropSection
tProp = PropSection;
}else{
if (bFlow){
tProp = Flow.GetFlowBaseProp(PropSection) + Const.PropDivider + PropName;
}else{
tProp = Const.BaseProp + Const.PropDivider + PropSection + Const.PropDivider + PropName;
}
}
Boolean CurrentValue = util.GetPropertyAsBoolean(tProp, DefaultValue);
if (CurrentValue){
return TrueValue;
}else{
return FalseValue;
}
}
//option for full Property string passed in
public static void SetTrueFalseOptionNext(String PropSection, Boolean DefaultValue){
SetTrueFalseOptionNextBase(Boolean.FALSE, PropSection, "", DefaultValue);
}
//option for assuming a FALSE default value and full Property string passed in
public static void SetTrueFalseOptionNext(String PropSection){
SetTrueFalseOptionNextBase(Boolean.FALSE, PropSection, "", Boolean.FALSE);
}
//option for assuming a FALSE default value
public static void SetTrueFalseOptionNext(String PropSection, String PropName){
SetTrueFalseOptionNextBase(Boolean.FALSE, PropSection, PropName, Boolean.FALSE);
}
public static void SetTrueFalseOptionNext(String PropSection, String PropName, Boolean DefaultValue){
SetTrueFalseOptionNextBase(Boolean.FALSE, PropSection, PropName, DefaultValue);
}
public static void SetTrueFalseOptionNextBase(Boolean bFlow, String PropSection, String PropName, Boolean DefaultValue){
String tProp = "";
if (PropName.equals("")){ //expect the full property string in the PropSection
tProp = PropSection;
}else{
if (bFlow){
tProp = Flow.GetFlowBaseProp(PropSection) + Const.PropDivider + PropName;
}else{
tProp = Const.BaseProp + Const.PropDivider + PropSection + Const.PropDivider + PropName;
}
}
Boolean NewValue = !util.GetPropertyAsBoolean(tProp, DefaultValue);
util.SetProperty(tProp, NewValue.toString());
}
//option for full Property string passed in
public static void SetTrueFalseOption(String PropSection, Boolean NewValue){
SetTrueFalseOptionBase(Boolean.FALSE, PropSection, "", NewValue);
}
public static void SetTrueFalseOption(String PropSection, String PropName, Boolean NewValue){
SetTrueFalseOptionBase(Boolean.FALSE, PropSection, PropName, NewValue);
}
public static void SetTrueFalseOptionBase(Boolean bFlow, String PropSection, String PropName, Boolean NewValue){
String tProp = "";
if (PropName.equals("")){ //expect the full property string in the PropSection
tProp = PropSection;
}else{
if (bFlow){
tProp = Flow.GetFlowBaseProp(PropSection) + Const.PropDivider + PropName;
}else{
tProp = Const.BaseProp + Const.PropDivider + PropSection + Const.PropDivider + PropName;
}
}
util.SetProperty(tProp, NewValue.toString());
}
//Set of functions for Get/Set of generic passed in List
//List items must be separated by ListToken
public static String GetListOptionName(String PropSection, String PropName, String OptionList, String DefaultValue){
return GetListOptionNameBase(Boolean.FALSE, PropSection, PropName, OptionList, DefaultValue);
}
public static String GetListOptionNameBase(Boolean bFlow, String PropSection, String PropName, String OptionList, String DefaultValue){
String tProp = "";
if (bFlow){
tProp = Flow.GetFlowBaseProp(PropSection) + Const.PropDivider + PropName;
}else{
tProp = Const.BaseProp + Const.PropDivider + PropSection + Const.PropDivider + PropName;
}
String CurrentValue = util.GetProperty(tProp, DefaultValue);
if (ConvertStringtoList(OptionList).contains(CurrentValue)){
return CurrentValue;
}else{
return DefaultValue;
}
}
public static void SetListOptionNext(String PropSection, String PropName, String OptionList){
SetListOptionNextBase(Boolean.FALSE, PropSection, PropName, OptionList);
}
public static void SetListOptionNextBase(Boolean bFlow, String PropSection, String PropName, String OptionList){
String tProp = "";
if (bFlow){
tProp = Flow.GetFlowBaseProp(PropSection) + Const.PropDivider + PropName;
}else{
tProp = Const.BaseProp + Const.PropDivider + PropSection + Const.PropDivider + PropName;
}
String CurrentValue = util.GetProperty(tProp, OptionNotFound);
//LOG.debug("SetListOptionNextBase: currentvalue '" + CurrentValue + "' for '" + tProp + "'");
List<String> FullList = ConvertStringtoList(OptionList);
if (CurrentValue.equals(OptionNotFound)){
util.SetProperty(tProp, FullList.get(1)); //default to the 2nd item
}else{
Integer pos = FullList.indexOf(CurrentValue);
if (pos==-1){ //not found
util.SetProperty(tProp, FullList.get(0));
}else if(pos==FullList.size()-1){ //last item
util.SetProperty(tProp, FullList.get(0));
}else{ //get next item
util.SetProperty(tProp, FullList.get(pos+1));
}
}
}
//set of functions for generic String based properties
public static String GetOptionName(String PropSection, String PropName, String DefaultValue){
return GetOptionNameBase(Boolean.FALSE, PropSection, PropName, DefaultValue);
}
public static String GetOptionNameBase(Boolean bFlow, String PropSection, String PropName, String DefaultValue){
String tProp = "";
if (bFlow){
tProp = Flow.GetFlowBaseProp(PropSection) + Const.PropDivider + PropName;
}else{
tProp = Const.BaseProp + Const.PropDivider + PropSection + Const.PropDivider + PropName;
}
//LOG.debug("GetOptionNameBase: property '" + tProp + "'");
return util.GetProperty(tProp, DefaultValue);
}
public static void SetOption(String PropSection, String PropName, String NewValue){
SetOptionBase(Boolean.FALSE, PropSection, PropName, NewValue);
}
public static void SetOptionBase(Boolean bFlow, String PropSection, String PropName, String NewValue){
String tProp = "";
if (bFlow){
tProp = Flow.GetFlowBaseProp(PropSection) + Const.PropDivider + PropName;
}else{
tProp = Const.BaseProp + Const.PropDivider + PropSection + Const.PropDivider + PropName;
}
util.SetProperty(tProp, NewValue);
}
public static String PropertyListasString(String PropSection, String PropName){
return PropertyListasStringBase(Boolean.FALSE, PropSection, PropName);
}
public static String PropertyListasStringBase(Boolean bFlow, String PropSection, String PropName){
String tProp = "";
if (bFlow){
tProp = Flow.GetFlowBaseProp(PropSection) + Const.PropDivider + PropName;
}else{
tProp = Const.BaseProp + Const.PropDivider + PropSection + Const.PropDivider + PropName;
}
return ConvertListtoString(GetPropertyAsList(tProp),",");
}
public static List<String> PropertyList(String PropSection, String PropName){
return PropertyListBase(Boolean.FALSE, PropSection, PropName);
}
public static List<String> PropertyListBase(Boolean bFlow, String PropSection, String PropName){
String tProp = "";
if (bFlow){
tProp = Flow.GetFlowBaseProp(PropSection) + Const.PropDivider + PropName;
}else{
tProp = Const.BaseProp + Const.PropDivider + PropSection + Const.PropDivider + PropName;
}
TreeSet<String> tList = new TreeSet<String>();
tList.addAll(GetPropertyAsList(tProp));
return new ArrayList<String>(tList);
}
public static void PropertyListAdd( String PropSection, String PropName, String NewValue){
PropertyListAddBase(Boolean.FALSE, PropSection, PropName, NewValue);
}
public static void PropertyListAddBase(Boolean bFlow, String PropSection, String PropName, String NewValue){
String tProp = "";
if (bFlow){
tProp = Flow.GetFlowBaseProp(PropSection) + Const.PropDivider + PropName;
}else{
tProp = Const.BaseProp + Const.PropDivider + PropSection + Const.PropDivider + PropName;
}
ArrayList<String> tList = new ArrayList<String>(GetPropertyAsList(tProp));
tList.add(NewValue);
SetPropertyAsList(tProp, tList);
}
public static void PropertyListRemove(String PropSection, String PropName, String NewValue){
PropertyListRemoveBase(Boolean.FALSE, PropSection, PropName, NewValue);
}
public static void PropertyListRemoveBase(Boolean bFlow, String PropSection, String PropName, String NewValue){
String tProp = "";
if (bFlow){
tProp = Flow.GetFlowBaseProp(PropSection) + Const.PropDivider + PropName;
}else{
tProp = Const.BaseProp + Const.PropDivider + PropSection + Const.PropDivider + PropName;
}
ArrayList<String> tList = new ArrayList<String>(GetPropertyAsList(tProp));
tList.remove(NewValue);
SetPropertyAsList(tProp, tList);
}
public static void PropertyListRemoveAll(String PropSection, String PropName){
PropertyListRemoveAllBase(Boolean.FALSE, PropSection, PropName);
}
public static void PropertyListRemoveAllBase(Boolean bFlow, String PropSection, String PropName){
String tProp = "";
if (bFlow){
tProp = Flow.GetFlowBaseProp(PropSection) + Const.PropDivider + PropName;
}else{
tProp = Const.BaseProp + Const.PropDivider + PropSection + Const.PropDivider + PropName;
}
RemoveProperty(tProp);
}
public static Boolean PropertyListContains(String PropSection, String PropName, String NewValue){
return PropertyListContainsBase(Boolean.FALSE, PropSection, PropName, NewValue);
}
public static Boolean PropertyListContainsBase(Boolean bFlow, String PropSection, String PropName, String NewValue){
String tProp = "";
if (bFlow){
tProp = Flow.GetFlowBaseProp(PropSection) + Const.PropDivider + PropName;
}else{
tProp = Const.BaseProp + Const.PropDivider + PropSection + Const.PropDivider + PropName;
}
List<String> tList = GetPropertyAsList(tProp);
if (tList.contains(NewValue)){
return Boolean.TRUE;
}else{
return Boolean.FALSE;
}
}
public static Boolean PropertyListContains(String PropSection, String PropName, ViewFolder Folder){
return PropertyListContainsBase(Boolean.FALSE, PropSection, PropName, Folder);
}
public static Boolean PropertyListContainsBase(Boolean bFlow, String PropSection, String PropName, ViewFolder Folder){
String tProp = "";
if (bFlow){
tProp = Flow.GetFlowBaseProp(PropSection) + Const.PropDivider + PropName;
}else{
tProp = Const.BaseProp + Const.PropDivider + PropSection + Const.PropDivider + PropName;
}
List<String> tList = GetPropertyAsList(tProp);
if (tList.size()>0){
for (IMediaResource Child: Folder.getChildren()){
String NewValue = Child.getTitle();
if (tList.contains(NewValue)){
return Boolean.TRUE;
}
}
return Boolean.FALSE;
}else{
return Boolean.FALSE;
}
}
public static Integer PropertyListCount(String PropSection, String PropName){
return PropertyListCountBase(Boolean.FALSE, PropSection, PropName);
}
public static Integer PropertyListCountBase(Boolean bFlow, String PropSection, String PropName){
String tProp = "";
if (bFlow){
tProp = Flow.GetFlowBaseProp(PropSection) + Const.PropDivider + PropName;
}else{
tProp = Const.BaseProp + Const.PropDivider + PropSection + Const.PropDivider + PropName;
}
List<String> tList = GetPropertyAsList(tProp);
return tList.size();
}
public static String NotFound(){
return OptionNotFound;
}
public static String UnknownName(){
return Const.UnknownName;
}
public static Object PadMediaFiles(Integer PadBefore, Object MediaFiles, Integer PadAfter){
Object tMediaFiles = MediaFiles;
for (int index=0;index<PadBefore;index++){
tMediaFiles = sagex.api.Database.DataUnion(sagex.api.Utility.CreateArray("BlankItem" + (index+1)), tMediaFiles);
}
for (int index=0;index<PadAfter;index++){
tMediaFiles = sagex.api.Database.DataUnion(tMediaFiles, sagex.api.Utility.CreateArray("BlankItem"+(index+100)));
}
return tMediaFiles;
}
public static Object BlankArrayItems(Integer ItemCount, String UniqueID){
Object tArray = null;
for (int index=0;index<ItemCount;index++){
tArray = sagex.api.Database.DataUnion(sagex.api.Utility.CreateArray("BlankItem" + UniqueID + (index)), tArray);
}
return tArray;
}
//VFS utility functions
//Get the menu title based on the flow and the current folder
public static String GetMenuTitle(String FlowKey, Object thisFolder){
String tFlowName = Flow.GetFlowName(FlowKey);
String FolderName = phoenix.media.GetTitle(thisFolder);
String ParentName = phoenix.media.GetTitle(phoenix.umb.GetParent((sagex.phoenix.vfs.IMediaResource) thisFolder));
if (ParentName==null){
return tFlowName + " : " + FolderName;
}else{
return tFlowName + " : " + ParentName + "/" + FolderName;
}
}
public static ArrayList<String> GetFirstListItems(ArrayList<String> InList, Integer Items){
//filter out null values and return at most Items items
ArrayList<String> OutList = new ArrayList<String>();
Integer counter = 0;
for (String Item: InList){
if (Item==null){
//do nothing
}else{
OutList.add(Item);
counter++;
if (counter>=Items){
break;
}
}
}
return OutList;
}
public static String PrintDateSortable(){
DateFormat df = new SimpleDateFormat("yyyyMMdd-HHmm");
return df.format(new Date());
}
public static String PrintDateTime(){
DateFormat df = new SimpleDateFormat("HHmm MMM dd yyyy");
return df.format(new Date());
}
public static String PrintDateSortable(Date myDate){
DateFormat df = new SimpleDateFormat("yyyyMMdd-HHmm");
return df.format(myDate);
}
public static String PrintDateTime(Date myDate){
DateFormat df = new SimpleDateFormat("HHmm MMM dd yyyy");
return df.format(myDate);
}
public static String UserDataLocation(){
return GetSageTVRootDir() + File.separator + "userdata" + File.separator + "Gemstone";
}
public static String DefaultsLocation(){
return GetSageTVRootDir() + File.separator + "STVs" + File.separator + "Gemstone" + File.separator + "defaults";
}
public static String MenusLocation(){
return GetSageTVRootDir() + File.separator + "STVs" + File.separator + "Gemstone" + File.separator + "menus";
}
public static String GetSageTVRootDir(){
return sagex.phoenix.Phoenix.getInstance().getSageTVRootDir().toString();
}
public static Boolean IsADM(){
String ADMPluginID = "jusjokenADM";
String ADMWidgetSymbol = "JUSJOKEN-469564";
// check to see if the ADM Plugin is installed
Object[] FoundWidget = new Object[1];
FoundWidget[0] = sagex.api.WidgetAPI.FindWidgetBySymbol(new UIContext(sagex.api.Global.GetUIContextName()), ADMWidgetSymbol);
if (sagex.api.PluginAPI.IsPluginEnabled(sagex.api.PluginAPI.GetAvailablePluginForID(ADMPluginID)) || FoundWidget[0]!=null){
return Boolean.TRUE;
}
return Boolean.FALSE;
}
public static String repeat(String str, int times){
StringBuilder ret = new StringBuilder();
for(int i = 0;i < times;i++) ret.append(str);
return ret.toString();
}
public static String intToString(Integer num, Integer digits) {
if (digits<0){
return num.toString();
}
// create variable length array of zeros
char[] zeros = new char[digits];
Arrays.fill(zeros, '0');
// format number as String
DecimalFormat df = new DecimalFormat(String.valueOf(zeros));
return df.format(num);
}
public static String MD5(String md5) {
try {
byte[] bytesOfMessage;
try {
bytesOfMessage = md5.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] array = md.digest(bytesOfMessage);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < array.length; ++i) {
sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
}
return sb.toString();
} catch (UnsupportedEncodingException ex) {
java.util.logging.Logger.getLogger(util.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (NoSuchAlgorithmException e) {
}
return null;
}
public static Boolean HandleNonCompatiblePlugins(){
Boolean DisableForConflict = Boolean.TRUE;
Boolean ReloadUI = Boolean.FALSE;
//Boolean DisableForConflict = GetTrueFalseOption("Utility", "PluginConflictMode", Boolean.FALSE);
UIContext tUI = new UIContext(sagex.api.Global.GetUIContextName());
// //List plugins
// Object[] plugins = PluginAPI.GetAllAvailablePlugins();
// if (plugins != null && plugins.length > 0) {
// for (Object plugin : plugins) {
// LOG.debug("HandleNonCompatiblePlugins: Plugin '" + PluginAPI.GetPluginIdentifier(plugin)+ "' Installed '" + PluginAPI.IsPluginInstalled(plugin) + "' Enabled '" + PluginAPI.IsPluginEnabled(plugin) + "' C Installed '" + PluginAPI.IsClientPluginInstalled(plugin) + "'");
// }
// }
//
//check for CVF
Object thisPlugin = sagex.api.PluginAPI.GetAvailablePluginForID(tUI,"jusjokencvf");
if (sagex.api.PluginAPI.IsPluginEnabled(tUI,thisPlugin)){
if(DisableForConflict){
sagex.api.PluginAPI.DisablePlugin(tUI, thisPlugin);
String tMessage = "CVF Plugin is NOT compatible with Gemstone as Gemstone now contains similar functions.\n \n* CVF Plugin has been disabled.";
PostSytemMessage(Const.SystemMessagePluginConflictCode, Const.SystemMessagePluginConflictName, Const.SystemMessageAlertLevelInfo, tMessage);
ReloadUI = Boolean.TRUE;
LOG.debug("HandleNonCompatiblePlugins: CVF found and disabled");
}else{
String tMessage = "CVF Plugin is NOT compatible with Gemstone as Gemstone now contains similar functions.\n \n* Please disable the CVF Plugin and reload the UI.";
PostSytemMessage(Const.SystemMessagePluginConflictCode, Const.SystemMessagePluginConflictName, Const.SystemMessageAlertLevelError, tMessage);
LOG.debug("HandleNonCompatiblePlugins: CVF found and System Error message created");
}
}else{
LOG.debug("HandleNonCompatiblePlugins: checking for CVF - not found");
}
//check for ADM
thisPlugin = sagex.api.PluginAPI.GetAvailablePluginForID(tUI,"jusjokenadm");
if (sagex.api.PluginAPI.IsPluginEnabled(tUI, thisPlugin)){
if(DisableForConflict){
sagex.api.PluginAPI.DisablePlugin(tUI, thisPlugin);
String tMessage = "ADM Plugin is NOT compatible with Gemstone as Gemstone now contains similar functions.\n \n* ADM Plugin has been disabled.";
PostSytemMessage(Const.SystemMessagePluginConflictCode, Const.SystemMessagePluginConflictName, Const.SystemMessageAlertLevelInfo, tMessage);
ReloadUI = Boolean.TRUE;
LOG.debug("HandleNonCompatiblePlugins: ADM found and disabled");
}else{
String tMessage = "ADM Plugin is NOT compatible with Gemstone as Gemstone now contains similar functions.\n \n* Please disable the ADM Plugin and reload the UI.";
PostSytemMessage(Const.SystemMessagePluginConflictCode, Const.SystemMessagePluginConflictName, Const.SystemMessageAlertLevelError, tMessage);
LOG.debug("HandleNonCompatiblePlugins: ADM found and System Error message created");
}
}else{
LOG.debug("HandleNonCompatiblePlugins: checking for ADM - not found");
}
return ReloadUI;
}
public static void PostSytemMessage(Integer Code, String MessageType, Integer AlertLevel, String Message){
Properties MessageProp = new Properties();
MessageProp.setProperty("code", Code.toString());
MessageProp.setProperty("typename", MessageType);
sagex.api.SystemMessageAPI.PostSystemMessage(new UIContext(sagex.api.Global.GetUIContextName()), Code, AlertLevel, Message, MessageProp);
}
public static String CleanProperty(String PropLocation, String Default){
String tValue = GetProperty(PropLocation, Default);
//see if the value has Diamond_ or sagediamond_ in it and if so then return the default
if (tValue.startsWith("Diamond_") || tValue.startsWith("sagediamond_")){
//save the default so the old invalid property is overwritten
SetProperty(PropLocation, Default);
return Default;
}
return tValue;
}
//TODO: remove as only used for temp conversion for Scott's Menus for Playon
public static void BuildActions(){
UIContext tUI = new UIContext(sagex.api.Global.GetUIContextName());
Properties Props = new Properties();
Object[] Menus = sagex.api.WidgetAPI.GetWidgetsByType(tUI,"Menu");
for (Object item: Menus){
String tName = sagex.api.WidgetAPI.GetWidgetName(item);
//LOG.debug("BuildActions: Menu '" + tName + "'");
if (tName.startsWith("PlayOn::")){
String tTitle = tName.substring(8);
if (tTitle.startsWith("Custom")){
continue;
}
String ActionName = tTitle.replaceAll("::", "_");
String ActionVal = tTitle.replaceAll("::", " ");
ActionName = "xItemPlayOn_" + ActionName.replaceAll(" ", "_");
String ActionTitle = tTitle.replaceAll("::", " - ");
LOG.debug("BuildActions: Item '" + ActionName + "' Title '" + ActionTitle + "'");
String Start = "ADM/custom_actions/";
Props.put(Start + ActionName + "/ActionCategory/1", "Online");
Props.put(Start + ActionName + "/ActionCategory/2", "PlayOn");
Props.put(Start + ActionName + "/ButtonText", ActionTitle);
Props.put(Start + ActionName + "/WidgetSymbol", "KMWIY-932161");
Props.put(Start + ActionName + "/ActionVariables/1/Val", ActionVal);
Props.put(Start + ActionName + "/ActionVariables/1/Var", "PlayOnMenuItem");
Props.put(Start + ActionName + "/ActionVariables/1/VarType", "VarTypeGlobal");
Props.put(Start + ActionName + "/CopyModeAttributeVar", "ThisItem");
}
}
String FilePath = util.UserDataLocation() + File.separator + "ActionTemp.properties";
if (Props.size()>0){
try {
FileOutputStream out = new FileOutputStream(FilePath);
try {
Props.store(out, Const.PropertyComment);
out.close();
} catch (IOException ex) {
LOG.debug("Execute: error exporting properties " + util.class.getName() + ex);
}
} catch (FileNotFoundException ex) {
LOG.debug("Execute: error exporting properties " + util.class.getName() + ex);
}
}
}
}
| Gemstone/src/Gemstone/util.java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Gemstone;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.RoundingMode;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.TreeSet;
import java.util.logging.Level;
import org.apache.log4j.Logger;
import sagex.UIContext;
import sagex.phoenix.vfs.IMediaResource;
import sagex.phoenix.vfs.views.ViewFolder;
/**
*
* @author SBANTA
* @author JUSJOKEN
* - 10/09/2011 - added LOG4J setup and Main method for testing, and StringNumberFormat
* - 10/10/2011 - added some generic functions
* - 04/04/2012 - updated for Gemstone
*/
public class util {
static private final Logger LOG = Logger.getLogger(util.class);
public static final char[] symbols = new char[36];
private static final Random random = new Random();
public static final String OptionNotFound = "Option not Found";
public static enum TriState{YES,NO,OTHER};
public static enum ExportType{ALL,WIDGETS,FLOWS,FLOW,MENUS,GENERAL};
public static final String ListToken = ":&&:";
public static void main(String[] args){
//String test = StringNumberFormat("27.96903", 0, 2);
//String test = StringNumberFormat("27.1", 0, 2);
//LOG.debug(test);
//api.InitLogger();
test1();
}
public static void test1(){
PropertiesExt Props = new PropertiesExt();
String FilePath = util.UserDataLocation() + File.separator + "menutest.properties";
Boolean KeepProcessing = Boolean.TRUE;
//read the properties from the properties file
try {
FileInputStream in = new FileInputStream(FilePath);
try {
Props.load(in);
in.close();
} catch (IOException ex) {
LOG.debug("test1: IO exception inporting properties " + util.class.getName() + ex);
KeepProcessing = Boolean.FALSE;
}
} catch (FileNotFoundException ex) {
LOG.debug("test1: file not found inporting properties " + util.class.getName() + ex);
KeepProcessing = Boolean.FALSE;
}
if (KeepProcessing){
LOG.debug("test1: start of BRANCHES");
for (String Key:Props.GetSubpropertiesThatAreBranches("Gemstone/Widgets")){
LOG.debug("TEST item '" + Key + "'");
}
LOG.debug("test1: start of LEAVES");
for (String Key:Props.GetSubpropertiesThatAreLeaves("Gemstone/Widgets")){
LOG.debug("TEST item '" + Key + "'");
}
}
}
private static void print(Map map) {
LOG.debug("One=" + map.get("One"));
LOG.debug("Two=" + map.get("Two"));
LOG.debug("Three=" + map.get("Three"));
LOG.debug("Four=" + map.get("Four"));
LOG.debug("Five=" + map.get("Five"));
}
private static void print2(Map map, Integer items) {
for(int i=1; i<=items; i++){
LOG.debug("TEST " + map.getClass() + " ITEMS '" + items + "' - " + TempName(i) + "=" + map.get(TempName(i)) + " Mem = '" + FreeMem() + "'");
}
}
private static void testMap(Map map, Integer Multiplier) {
LOG.debug("Testing " + map.getClass());
for(int i=1; i<=Multiplier; i++){
map.put(TempName(i), new byte[10*1024*1024]);
print2(map,i);
}
// LOG.debug("Adding 10MB * " + Multiplier);
//// for(int i=1; i<=Multiplier; i++){
// byte[] block = new byte[10*1024*1024*Multiplier]; // 10 MB
//// }
// print(map);
}
public static String FreeMem() {
Long total = Runtime.getRuntime().totalMemory();
Long free = Runtime.getRuntime().freeMemory();
String InfoText = Math.round((total-free)/1000000.0) + "MB/";
return InfoText;
}
public static void LogFreeMem(String Message) {
Long total = Runtime.getRuntime().totalMemory();
Long free = Runtime.getRuntime().freeMemory();
String InfoText = Math.round((total-free)/1000000.0) + "MB";
LOG.debug(Message + " FreeMem '" + InfoText + "'");
}
private static String TempName(Integer i) {
return "Item_" + i;
}
// private static void testMap(Map map, Integer Multiplier) {
// LOG.debug("Testing " + map.getClass());
// map.put("One", new Integer(1));
// map.put("Two", new Integer(2));
// map.put("Three", new Integer(3));
// map.put("Four", new Integer(4));
// map.put("Five", new Integer(5));
// print(map);
// LOG.debug("Adding 10MB * " + Multiplier);
//// for(int i=1; i<=Multiplier; i++){
// byte[] block = new byte[10*1024*1024*Multiplier]; // 10 MB
//// }
// print(map);
// }
public static void test1(Integer Min, Integer Multiplier) {
testMap(new SoftHashMap(Min), Multiplier);
//testMap(new HashMap(), Multiplier);
}
//pass in a String that contains a number and this will format it to a specific number of decimal places
public static String StringNumberFormat(String Input, Integer DecimalPlaces){
return StringNumberFormat(Input, DecimalPlaces, DecimalPlaces);
}
public static String StringNumberFormat(String Input, Integer MinDecimalPlaces, Integer MaxDecimalPlaces){
float a = 0;
try {
a = Float.parseFloat(Input);
} catch (NumberFormatException nfe) {
LOG.error("StringNumberFormat - NumberFormatException for '" + Input + "'");
return Input;
}
NumberFormat df = DecimalFormat.getInstance();
df.setMinimumFractionDigits(MinDecimalPlaces);
df.setMaximumFractionDigits(MaxDecimalPlaces);
df.setRoundingMode(RoundingMode.DOWN);
String retString = df.format(a);
return retString;
}
public static Object CheckSeasonSize(Map<String, Object> Files, int sizeneeded) {
LinkedHashMap<String, Object> WithBlanks = new LinkedHashMap<String, Object>();
for(int index=0;index<sizeneeded;index++){
WithBlanks.put("blankelement1"+index, null);}
WithBlanks.putAll(Files);
for(int index=sizeneeded;index<sizeneeded+sizeneeded;index++){
WithBlanks.put("blankelement"+index, null);}
return WithBlanks;
}
public static Object CheckCategorySize(Map<String, Object> Files) {
LinkedHashMap<String, Object> WithBlanks = new LinkedHashMap<String, Object>();
WithBlanks.put("blankelement1", null);
WithBlanks.putAll(Files);
WithBlanks.put("blankelement4", null);
return WithBlanks;
}
public static Object CheckSimpleSize(Object[] Files,int sizeneeded) {
if (!Files.toString().contains("blankelement")) {
List<Object> WithBlanks = new ArrayList<Object>();
for(int index=0;index<sizeneeded;index++){
WithBlanks.add("blankelement"+index);}
for (Object curr : Files) {
WithBlanks.add(curr);
}
for(int index=sizeneeded;index<sizeneeded+sizeneeded;index++){
WithBlanks.add("blankelement"+index);}
return WithBlanks;
}
return Files;
}
public static Object CheckFileSize(List<Object> files, String diamondprop) {
String viewtype = Flow.GetFlowType(diamondprop);
ArrayList<Object> NewList = new ArrayList<Object>();
if (viewtype == "Wall Flow" && files.size() < 5) {
} else if (viewtype == "Cover Flow" && files.size() < 7) {
NewList.add(null);
NewList.add(null);
NewList.add(null);
NewList.addAll(files);
NewList.add(null);
NewList.add(null);
return NewList;
}
return files;
}
public static LinkedHashMap<String, Integer> GetLetterLocations(Object[] MediaFiles) {
String CurrentLocation = "845948921";
Boolean ScrapTitle = Boolean.parseBoolean(sagex.api.Configuration.GetProperty("ui/ignore_the_when_sorting", "false"));
LinkedHashMap<String, Integer> Values = new LinkedHashMap<String, Integer>();
String Title = "";
int i = 0;
for (Object curr : MediaFiles) {
if (ScrapTitle) {
Title = MetadataCalls.GetSortTitle(curr);
} else {
Title = MetadataCalls.GetMediaTitle(curr);
}
if (!Title.startsWith(CurrentLocation)) {
CurrentLocation = Title.substring(0, 1);
Values.put(CurrentLocation.toLowerCase(), i);
}
i++;
}
return Values;
}
// public static HashMap<Object,Object> GetHeaders(Object MediaFiles,String Method){
// Object[] Files = FanartCaching.toArray(MediaFiles);
// HashMap<Object,Object> Headers = new HashMap<Object,Object>();
// Object CurrGroup=null;
// if(Method.contains("AirDate")){
// for(Object curr:Files){
// Object thisvalue=GetTimeAdded(curr);
// if(thisvalue!=CurrGroup){
// Headers.put(curr,thisvalue);
// CurrGroup=thisvalue;}}
//
// }
// else if (Method.contains("Title")){
// for(Object curr:Files){
// String thisvalues=ClassFromString.GetSortDividerClass(Method,curr).toString();
// Object thisvalue=thisvalues.substring(0,1);
// if(!thisvalue.equals(CurrGroup)){
// Headers.put(curr,thisvalue);
// CurrGroup=thisvalue;}
// }
//
// }
// return Headers;}
public static boolean IsHeader(Map headers, Object Key) {
return headers.containsKey(Key);
}
public static String GenerateRandomName(){
char[] buf = new char[10];
for (int idx = 0; idx < buf.length; ++idx)
buf[idx] = symbols[random.nextInt(symbols.length)];
return "sd" + new String(buf);
}
public static Boolean HasProperty(String Property){
String tValue = sagex.api.Configuration.GetProperty(new UIContext(sagex.api.Global.GetUIContextName()),Property, null);
if (tValue==null || tValue.equals(OptionNotFound)){
return Boolean.FALSE;
}else{
return Boolean.TRUE;
}
}
public static String GetProperty(String Property, String DefaultValue){
String tValue = sagex.api.Configuration.GetProperty(new UIContext(sagex.api.Global.GetUIContextName()),Property, null);
if (tValue==null || tValue.equals(OptionNotFound)){
return DefaultValue;
}else{
return tValue;
}
}
public static Boolean GetPropertyAsBoolean(String Property, Boolean DefaultValue){
String tValue = sagex.api.Configuration.GetProperty(new UIContext(sagex.api.Global.GetUIContextName()),Property, null);
if (tValue==null || tValue.equals(OptionNotFound)){
return DefaultValue;
}else{
return Boolean.parseBoolean(tValue);
}
}
//Evaluates the property and returns it's value - must be true or false - returns true otherwise
public static Boolean GetPropertyEvalAsBoolean(String Property, Boolean DefaultValue){
String tValue = sagex.api.Configuration.GetProperty(new UIContext(sagex.api.Global.GetUIContextName()),Property, null);
if (tValue==null || tValue.equals(OptionNotFound)){
return DefaultValue;
}else{
return Boolean.parseBoolean(EvaluateAttribute(tValue));
}
}
public static TriState GetPropertyAsTriState(String Property, TriState DefaultValue){
String tValue = sagex.api.Configuration.GetProperty(new UIContext(sagex.api.Global.GetUIContextName()),Property, null);
if (tValue==null || tValue.equals(OptionNotFound)){
return DefaultValue;
}else if(tValue.equals("YES")){
return TriState.YES;
}else if(tValue.equals("NO")){
return TriState.NO;
}else if(tValue.equals("OTHER")){
return TriState.OTHER;
}else if(Boolean.parseBoolean(tValue)){
return TriState.YES;
}else if(!Boolean.parseBoolean(tValue)){
return TriState.NO;
}else{
return TriState.YES;
}
}
public static List<String> GetPropertyAsList(String Property){
String tValue = sagex.api.Configuration.GetProperty(new UIContext(sagex.api.Global.GetUIContextName()),Property, null);
if (tValue==null || tValue.equals(OptionNotFound)){
return new LinkedList<String>();
}else{
return ConvertStringtoList(tValue);
}
}
public static Integer GetPropertyAsInteger(String Property, Integer DefaultValue){
//read in the Sage Property and force convert it to an Integer
Integer tInteger = DefaultValue;
String tValue = sagex.api.Configuration.GetProperty(new UIContext(sagex.api.Global.GetUIContextName()),Property, null);
if (tValue==null || tValue.equals(OptionNotFound)){
return DefaultValue;
}
try {
tInteger = Integer.valueOf(tValue);
} catch (NumberFormatException ex) {
//use DefaultValue
return DefaultValue;
}
return tInteger;
}
public static Double GetPropertyAsDouble(String Property, Double DefaultValue){
//read in the Sage Property and force convert it to an Integer
Double tDouble = DefaultValue;
String tValue = sagex.api.Configuration.GetProperty(new UIContext(sagex.api.Global.GetUIContextName()),Property, null);
if (tValue==null || tValue.equals(OptionNotFound)){
return DefaultValue;
}
try {
tDouble = Double.valueOf(tValue);
} catch (NumberFormatException ex) {
//use DefaultValue
return DefaultValue;
}
return tDouble;
}
public static String GetServerProperty(String Property, String DefaultValue){
String tValue = sagex.api.Configuration.GetServerProperty(new UIContext(sagex.api.Global.GetUIContextName()),Property, null);
if (tValue==null || tValue.equals(OptionNotFound)){
return DefaultValue;
}else{
return tValue;
}
}
public static void SetProperty(String Property, String Value){
sagex.api.Configuration.SetProperty(new UIContext(sagex.api.Global.GetUIContextName()),Property, Value);
}
public static void SetPropertyAsTriState(String Property, TriState Value){
sagex.api.Configuration.SetProperty(new UIContext(sagex.api.Global.GetUIContextName()),Property, Value.toString());
}
public static void SetPropertyAsList(String Property, List<String> ListValue){
String Value = ConvertListtoString(ListValue);
if (ListValue.size()>0){
sagex.api.Configuration.SetProperty(new UIContext(sagex.api.Global.GetUIContextName()),Property, Value);
}else{
RemoveProperty(Property);
}
}
public static void SetServerProperty(String Property, String Value){
sagex.api.Configuration.SetServerProperty(new UIContext(sagex.api.Global.GetUIContextName()),Property, Value);
}
public static void RemoveServerProperty(String Property){
sagex.api.Configuration.RemoveServerProperty(new UIContext(sagex.api.Global.GetUIContextName()),Property);
}
public static void RemovePropertyAndChildren(String Property){
sagex.api.Configuration.RemovePropertyAndChildren(new UIContext(sagex.api.Global.GetUIContextName()),Property);
}
public static void RemoveProperty(String Property){
sagex.api.Configuration.RemoveProperty(new UIContext(sagex.api.Global.GetUIContextName()),Property);
}
public static void RemoveServerPropertyAndChildren(String Property){
sagex.api.Configuration.RemoveServerPropertyAndChildren(new UIContext(sagex.api.Global.GetUIContextName()),Property);
}
public static String ConvertListtoString(List<String> ListValue){
return ConvertListtoString(ListValue, ListToken);
}
public static String ConvertListtoString(List<String> ListValue, String Separator){
String Value = "";
if (ListValue.size()>0){
Boolean tFirstItem = Boolean.TRUE;
for (String ListItem : ListValue){
if (tFirstItem){
Value = ListItem;
tFirstItem = Boolean.FALSE;
}else{
Value = Value + Separator + ListItem;
}
}
}
return Value;
}
public static List<String> ConvertStringtoList(String tValue){
if (tValue.equals(OptionNotFound) || tValue.equals("") || tValue==null){
return new LinkedList<String>();
}else{
return Arrays.asList(tValue.split(ListToken));
}
}
public static String EvaluateAttribute(String Attribute){
//LOG.debug("EvaluateAttribute: Attribute = '" + Attribute + "'");
Object[] passvalue = new Object[1];
passvalue[0] = sagex.api.WidgetAPI.EvaluateExpression(new UIContext(sagex.api.Global.GetUIContextName()), Attribute);
if (passvalue[0]==null){
LOG.debug("EvaluateAttribute for Attribute = '" + Attribute + "' not evaluated.");
return OptionNotFound;
}else{
//LOG.debug("EvaluateAttribute for Attribute = '" + Attribute + "' = '" + passvalue[0].toString() + "'");
return passvalue[0].toString();
}
}
public static void OptionsClear(){
//clear all the Options settings used only while the Options menu is open
String tProp = Const.BaseProp + Const.PropDivider + Const.OptionsFocused;
RemovePropertyAndChildren(tProp);
tProp = Const.BaseProp + Const.PropDivider + Const.OptionsType;
RemovePropertyAndChildren(tProp);
tProp = Const.BaseProp + Const.PropDivider + Const.OptionsTitle;
RemovePropertyAndChildren(tProp);
}
public static void OptionsLastFocusedSet(Integer CurrentLevel, String FocusedItem){
String tProp = Const.BaseProp + Const.PropDivider + Const.OptionsFocused + Const.PropDivider + CurrentLevel.toString() + Const.PropDivider + Const.OptionsFocusedItem;
//LOG.debug("OptionsLastFocusedSet: CurrentLevel = '" + CurrentLevel + "' FocusedItem = '" + FocusedItem + "'");
SetProperty(tProp, FocusedItem);
}
public static String OptionsLastFocusedGet(Integer CurrentLevel){
String tProp = Const.BaseProp + Const.PropDivider + Const.OptionsFocused + Const.PropDivider + CurrentLevel.toString() + Const.PropDivider + Const.OptionsFocusedItem;
String FocusedItem = GetProperty(tProp, OptionNotFound);
//LOG.debug("OptionsLastFocusedGet: CurrentLevel = '" + CurrentLevel + "' FocusedItem = '" + FocusedItem + "'");
return FocusedItem;
}
public static String OptionsTypeGet(Integer CurrentLevel){
String tProp = Const.BaseProp + Const.PropDivider + Const.OptionsType + Const.PropDivider + CurrentLevel.toString() + Const.PropDivider + Const.OptionsTypeName;
String OptionsType = GetProperty(tProp, OptionNotFound);
//LOG.debug("OptionsTypeGet: CurrentLevel = '" + CurrentLevel + "' OptionsType = '" + OptionsType + "'");
return OptionsType;
}
public static Integer OptionsTypeSet(Integer CurrentLevel, String OptionsType){
String tProp = Const.BaseProp + Const.PropDivider + Const.OptionsType + Const.PropDivider + CurrentLevel.toString() + Const.PropDivider + Const.OptionsTypeName;
//LOG.debug("OptionsTypeSet: CurrentLevel = '" + CurrentLevel + "' OptionsType = '" + OptionsType + "'");
SetProperty(tProp, OptionsType);
return CurrentLevel;
}
public static void OptionsTitleSet(Integer CurrentLevel, String Title){
String tProp = Const.BaseProp + Const.PropDivider + Const.OptionsTitle + Const.PropDivider + CurrentLevel.toString() + Const.PropDivider + Const.OptionsTitleName;
//LOG.debug("OptionsTitleSet: CurrentLevel = '" + CurrentLevel + "' Title = '" + Title + "'");
SetProperty(tProp, Title);
}
public static String OptionsTitleGet(Integer CurrentLevel){
String tProp = Const.BaseProp + Const.PropDivider + Const.OptionsTitle + Const.PropDivider + CurrentLevel.toString() + Const.PropDivider + Const.OptionsTitleName;
String Title = GetProperty(tProp, OptionNotFound);
//LOG.debug("OptionsTitleGet: CurrentLevel = '" + CurrentLevel + "' Title = '" + Title + "'");
return Title;
}
//Set of functions for Get/Set of generic True/False values with passed in test names to display
public static Boolean GetTrueFalseOption(String PropSection, String PropName){
return GetTrueFalseOptionBase(Boolean.FALSE, PropSection, PropName, Boolean.FALSE);
}
public static Boolean GetTrueFalseOption(String PropSection, String PropName, Boolean DefaultValue){
return GetTrueFalseOptionBase(Boolean.FALSE, PropSection, PropName, DefaultValue);
}
public static Boolean GetTrueFalseOptionBase(Boolean bFlow, String PropSection, String PropName, Boolean DefaultValue){
String tProp = "";
if (PropName.equals("")){ //expect the full property string in the PropSection
tProp = PropSection;
}else{
if (bFlow){
tProp = Flow.GetFlowBaseProp(PropSection) + Const.PropDivider + PropName;
}else{
tProp = Const.BaseProp + Const.PropDivider + PropSection + Const.PropDivider + PropName;
}
}
return util.GetPropertyAsBoolean(tProp, DefaultValue);
}
public static String GetTrueFalseOptionName(String PropSection, String TrueValue, String FalseValue, Boolean DefaultValue){
return GetTrueFalseOptionNameBase(Boolean.FALSE, PropSection, "", TrueValue, FalseValue, DefaultValue);
}
public static String GetTrueFalseOptionName(String PropSection, String TrueValue, String FalseValue){
return GetTrueFalseOptionNameBase(Boolean.FALSE, PropSection, "", TrueValue, FalseValue, Boolean.FALSE);
}
public static String GetTrueFalseOptionName(String PropSection, String PropName, String TrueValue, String FalseValue){
return GetTrueFalseOptionNameBase(Boolean.FALSE, PropSection, PropName, TrueValue, FalseValue, Boolean.FALSE);
}
public static String GetTrueFalseOptionName(String PropSection, String PropName, String TrueValue, String FalseValue, Boolean DefaultValue){
return GetTrueFalseOptionNameBase(Boolean.FALSE, PropSection, PropName, TrueValue, FalseValue, DefaultValue);
}
public static String GetTrueFalseOptionNameBase(Boolean bFlow, String PropSection, String PropName, String TrueValue, String FalseValue, Boolean DefaultValue){
String tProp = "";
if (PropName.equals("")){ //expect the full property string in the PropSection
tProp = PropSection;
}else{
if (bFlow){
tProp = Flow.GetFlowBaseProp(PropSection) + Const.PropDivider + PropName;
}else{
tProp = Const.BaseProp + Const.PropDivider + PropSection + Const.PropDivider + PropName;
}
}
Boolean CurrentValue = util.GetPropertyAsBoolean(tProp, DefaultValue);
if (CurrentValue){
return TrueValue;
}else{
return FalseValue;
}
}
//option for full Property string passed in
public static void SetTrueFalseOptionNext(String PropSection, Boolean DefaultValue){
SetTrueFalseOptionNextBase(Boolean.FALSE, PropSection, "", DefaultValue);
}
//option for assuming a FALSE default value and full Property string passed in
public static void SetTrueFalseOptionNext(String PropSection){
SetTrueFalseOptionNextBase(Boolean.FALSE, PropSection, "", Boolean.FALSE);
}
//option for assuming a FALSE default value
public static void SetTrueFalseOptionNext(String PropSection, String PropName){
SetTrueFalseOptionNextBase(Boolean.FALSE, PropSection, PropName, Boolean.FALSE);
}
public static void SetTrueFalseOptionNext(String PropSection, String PropName, Boolean DefaultValue){
SetTrueFalseOptionNextBase(Boolean.FALSE, PropSection, PropName, DefaultValue);
}
public static void SetTrueFalseOptionNextBase(Boolean bFlow, String PropSection, String PropName, Boolean DefaultValue){
String tProp = "";
if (PropName.equals("")){ //expect the full property string in the PropSection
tProp = PropSection;
}else{
if (bFlow){
tProp = Flow.GetFlowBaseProp(PropSection) + Const.PropDivider + PropName;
}else{
tProp = Const.BaseProp + Const.PropDivider + PropSection + Const.PropDivider + PropName;
}
}
Boolean NewValue = !util.GetPropertyAsBoolean(tProp, DefaultValue);
util.SetProperty(tProp, NewValue.toString());
}
//option for full Property string passed in
public static void SetTrueFalseOption(String PropSection, Boolean NewValue){
SetTrueFalseOptionBase(Boolean.FALSE, PropSection, "", NewValue);
}
public static void SetTrueFalseOption(String PropSection, String PropName, Boolean NewValue){
SetTrueFalseOptionBase(Boolean.FALSE, PropSection, PropName, NewValue);
}
public static void SetTrueFalseOptionBase(Boolean bFlow, String PropSection, String PropName, Boolean NewValue){
String tProp = "";
if (PropName.equals("")){ //expect the full property string in the PropSection
tProp = PropSection;
}else{
if (bFlow){
tProp = Flow.GetFlowBaseProp(PropSection) + Const.PropDivider + PropName;
}else{
tProp = Const.BaseProp + Const.PropDivider + PropSection + Const.PropDivider + PropName;
}
}
util.SetProperty(tProp, NewValue.toString());
}
//Set of functions for Get/Set of generic passed in List
//List items must be separated by ListToken
public static String GetListOptionName(String PropSection, String PropName, String OptionList, String DefaultValue){
return GetListOptionNameBase(Boolean.FALSE, PropSection, PropName, OptionList, DefaultValue);
}
public static String GetListOptionNameBase(Boolean bFlow, String PropSection, String PropName, String OptionList, String DefaultValue){
String tProp = "";
if (bFlow){
tProp = Flow.GetFlowBaseProp(PropSection) + Const.PropDivider + PropName;
}else{
tProp = Const.BaseProp + Const.PropDivider + PropSection + Const.PropDivider + PropName;
}
String CurrentValue = util.GetProperty(tProp, DefaultValue);
if (ConvertStringtoList(OptionList).contains(CurrentValue)){
return CurrentValue;
}else{
return DefaultValue;
}
}
public static void SetListOptionNext(String PropSection, String PropName, String OptionList){
SetListOptionNextBase(Boolean.FALSE, PropSection, PropName, OptionList);
}
public static void SetListOptionNextBase(Boolean bFlow, String PropSection, String PropName, String OptionList){
String tProp = "";
if (bFlow){
tProp = Flow.GetFlowBaseProp(PropSection) + Const.PropDivider + PropName;
}else{
tProp = Const.BaseProp + Const.PropDivider + PropSection + Const.PropDivider + PropName;
}
String CurrentValue = util.GetProperty(tProp, OptionNotFound);
//LOG.debug("SetListOptionNextBase: currentvalue '" + CurrentValue + "' for '" + tProp + "'");
List<String> FullList = ConvertStringtoList(OptionList);
if (CurrentValue.equals(OptionNotFound)){
util.SetProperty(tProp, FullList.get(1)); //default to the 2nd item
}else{
Integer pos = FullList.indexOf(CurrentValue);
if (pos==-1){ //not found
util.SetProperty(tProp, FullList.get(0));
}else if(pos==FullList.size()-1){ //last item
util.SetProperty(tProp, FullList.get(0));
}else{ //get next item
util.SetProperty(tProp, FullList.get(pos+1));
}
}
}
//set of functions for generic String based properties
public static String GetOptionName(String PropSection, String PropName, String DefaultValue){
return GetOptionNameBase(Boolean.FALSE, PropSection, PropName, DefaultValue);
}
public static String GetOptionNameBase(Boolean bFlow, String PropSection, String PropName, String DefaultValue){
String tProp = "";
if (bFlow){
tProp = Flow.GetFlowBaseProp(PropSection) + Const.PropDivider + PropName;
}else{
tProp = Const.BaseProp + Const.PropDivider + PropSection + Const.PropDivider + PropName;
}
//LOG.debug("GetOptionNameBase: property '" + tProp + "'");
return util.GetProperty(tProp, DefaultValue);
}
public static void SetOption(String PropSection, String PropName, String NewValue){
SetOptionBase(Boolean.FALSE, PropSection, PropName, NewValue);
}
public static void SetOptionBase(Boolean bFlow, String PropSection, String PropName, String NewValue){
String tProp = "";
if (bFlow){
tProp = Flow.GetFlowBaseProp(PropSection) + Const.PropDivider + PropName;
}else{
tProp = Const.BaseProp + Const.PropDivider + PropSection + Const.PropDivider + PropName;
}
util.SetProperty(tProp, NewValue);
}
public static String PropertyListasString(String PropSection, String PropName){
return PropertyListasStringBase(Boolean.FALSE, PropSection, PropName);
}
public static String PropertyListasStringBase(Boolean bFlow, String PropSection, String PropName){
String tProp = "";
if (bFlow){
tProp = Flow.GetFlowBaseProp(PropSection) + Const.PropDivider + PropName;
}else{
tProp = Const.BaseProp + Const.PropDivider + PropSection + Const.PropDivider + PropName;
}
return ConvertListtoString(GetPropertyAsList(tProp),",");
}
public static List<String> PropertyList(String PropSection, String PropName){
return PropertyListBase(Boolean.FALSE, PropSection, PropName);
}
public static List<String> PropertyListBase(Boolean bFlow, String PropSection, String PropName){
String tProp = "";
if (bFlow){
tProp = Flow.GetFlowBaseProp(PropSection) + Const.PropDivider + PropName;
}else{
tProp = Const.BaseProp + Const.PropDivider + PropSection + Const.PropDivider + PropName;
}
TreeSet<String> tList = new TreeSet<String>();
tList.addAll(GetPropertyAsList(tProp));
return new ArrayList<String>(tList);
}
public static void PropertyListAdd( String PropSection, String PropName, String NewValue){
PropertyListAddBase(Boolean.FALSE, PropSection, PropName, NewValue);
}
public static void PropertyListAddBase(Boolean bFlow, String PropSection, String PropName, String NewValue){
String tProp = "";
if (bFlow){
tProp = Flow.GetFlowBaseProp(PropSection) + Const.PropDivider + PropName;
}else{
tProp = Const.BaseProp + Const.PropDivider + PropSection + Const.PropDivider + PropName;
}
ArrayList<String> tList = new ArrayList<String>(GetPropertyAsList(tProp));
tList.add(NewValue);
SetPropertyAsList(tProp, tList);
}
public static void PropertyListRemove(String PropSection, String PropName, String NewValue){
PropertyListRemoveBase(Boolean.FALSE, PropSection, PropName, NewValue);
}
public static void PropertyListRemoveBase(Boolean bFlow, String PropSection, String PropName, String NewValue){
String tProp = "";
if (bFlow){
tProp = Flow.GetFlowBaseProp(PropSection) + Const.PropDivider + PropName;
}else{
tProp = Const.BaseProp + Const.PropDivider + PropSection + Const.PropDivider + PropName;
}
ArrayList<String> tList = new ArrayList<String>(GetPropertyAsList(tProp));
tList.remove(NewValue);
SetPropertyAsList(tProp, tList);
}
public static void PropertyListRemoveAll(String PropSection, String PropName){
PropertyListRemoveAllBase(Boolean.FALSE, PropSection, PropName);
}
public static void PropertyListRemoveAllBase(Boolean bFlow, String PropSection, String PropName){
String tProp = "";
if (bFlow){
tProp = Flow.GetFlowBaseProp(PropSection) + Const.PropDivider + PropName;
}else{
tProp = Const.BaseProp + Const.PropDivider + PropSection + Const.PropDivider + PropName;
}
RemoveProperty(tProp);
}
public static Boolean PropertyListContains(String PropSection, String PropName, String NewValue){
return PropertyListContainsBase(Boolean.FALSE, PropSection, PropName, NewValue);
}
public static Boolean PropertyListContainsBase(Boolean bFlow, String PropSection, String PropName, String NewValue){
String tProp = "";
if (bFlow){
tProp = Flow.GetFlowBaseProp(PropSection) + Const.PropDivider + PropName;
}else{
tProp = Const.BaseProp + Const.PropDivider + PropSection + Const.PropDivider + PropName;
}
List<String> tList = GetPropertyAsList(tProp);
if (tList.contains(NewValue)){
return Boolean.TRUE;
}else{
return Boolean.FALSE;
}
}
public static Boolean PropertyListContains(String PropSection, String PropName, ViewFolder Folder){
return PropertyListContainsBase(Boolean.FALSE, PropSection, PropName, Folder);
}
public static Boolean PropertyListContainsBase(Boolean bFlow, String PropSection, String PropName, ViewFolder Folder){
String tProp = "";
if (bFlow){
tProp = Flow.GetFlowBaseProp(PropSection) + Const.PropDivider + PropName;
}else{
tProp = Const.BaseProp + Const.PropDivider + PropSection + Const.PropDivider + PropName;
}
List<String> tList = GetPropertyAsList(tProp);
if (tList.size()>0){
for (IMediaResource Child: Folder.getChildren()){
String NewValue = Child.getTitle();
if (tList.contains(NewValue)){
return Boolean.TRUE;
}
}
return Boolean.FALSE;
}else{
return Boolean.FALSE;
}
}
public static Integer PropertyListCount(String PropSection, String PropName){
return PropertyListCountBase(Boolean.FALSE, PropSection, PropName);
}
public static Integer PropertyListCountBase(Boolean bFlow, String PropSection, String PropName){
String tProp = "";
if (bFlow){
tProp = Flow.GetFlowBaseProp(PropSection) + Const.PropDivider + PropName;
}else{
tProp = Const.BaseProp + Const.PropDivider + PropSection + Const.PropDivider + PropName;
}
List<String> tList = GetPropertyAsList(tProp);
return tList.size();
}
public static String NotFound(){
return OptionNotFound;
}
public static String UnknownName(){
return Const.UnknownName;
}
public static Object PadMediaFiles(Integer PadBefore, Object MediaFiles, Integer PadAfter){
Object tMediaFiles = MediaFiles;
for (int index=0;index<PadBefore;index++){
tMediaFiles = sagex.api.Database.DataUnion(sagex.api.Utility.CreateArray("BlankItem" + (index+1)), tMediaFiles);
}
for (int index=0;index<PadAfter;index++){
tMediaFiles = sagex.api.Database.DataUnion(tMediaFiles, sagex.api.Utility.CreateArray("BlankItem"+(index+100)));
}
return tMediaFiles;
}
public static Object BlankArrayItems(Integer ItemCount, String UniqueID){
Object tArray = null;
for (int index=0;index<ItemCount;index++){
tArray = sagex.api.Database.DataUnion(sagex.api.Utility.CreateArray("BlankItem" + UniqueID + (index)), tArray);
}
return tArray;
}
//VFS utility functions
//Get the menu title based on the flow and the current folder
public static String GetMenuTitle(String FlowKey, Object thisFolder){
String tFlowName = Flow.GetFlowName(FlowKey);
String FolderName = phoenix.media.GetTitle(thisFolder);
String ParentName = phoenix.media.GetTitle(phoenix.umb.GetParent((sagex.phoenix.vfs.IMediaResource) thisFolder));
if (ParentName==null){
return tFlowName + " : " + FolderName;
}else{
return tFlowName + " : " + ParentName + "/" + FolderName;
}
}
public static ArrayList<String> GetFirstListItems(ArrayList<String> InList, Integer Items){
//filter out null values and return at most Items items
ArrayList<String> OutList = new ArrayList<String>();
Integer counter = 0;
for (String Item: InList){
if (Item==null){
//do nothing
}else{
OutList.add(Item);
counter++;
if (counter>=Items){
break;
}
}
}
return OutList;
}
public static String PrintDateSortable(){
DateFormat df = new SimpleDateFormat("yyyyMMdd-HHmm");
return df.format(new Date());
}
public static String PrintDateTime(){
DateFormat df = new SimpleDateFormat("HHmm MMM dd yyyy");
return df.format(new Date());
}
public static String PrintDateSortable(Date myDate){
DateFormat df = new SimpleDateFormat("yyyyMMdd-HHmm");
return df.format(myDate);
}
public static String PrintDateTime(Date myDate){
DateFormat df = new SimpleDateFormat("HHmm MMM dd yyyy");
return df.format(myDate);
}
public static String UserDataLocation(){
return GetSageTVRootDir() + File.separator + "userdata" + File.separator + "Gemstone";
}
public static String DefaultsLocation(){
return GetSageTVRootDir() + File.separator + "STVs" + File.separator + "Gemstone" + File.separator + "defaults";
}
public static String MenusLocation(){
return GetSageTVRootDir() + File.separator + "STVs" + File.separator + "Gemstone" + File.separator + "menus";
}
public static String GetSageTVRootDir(){
return sagex.phoenix.Phoenix.getInstance().getSageTVRootDir().toString();
}
public static Boolean IsADM(){
String ADMPluginID = "jusjokenADM";
String ADMWidgetSymbol = "JUSJOKEN-469564";
// check to see if the ADM Plugin is installed
Object[] FoundWidget = new Object[1];
FoundWidget[0] = sagex.api.WidgetAPI.FindWidgetBySymbol(new UIContext(sagex.api.Global.GetUIContextName()), ADMWidgetSymbol);
if (sagex.api.PluginAPI.IsPluginEnabled(sagex.api.PluginAPI.GetAvailablePluginForID(ADMPluginID)) || FoundWidget[0]!=null){
return Boolean.TRUE;
}
return Boolean.FALSE;
}
public static String repeat(String str, int times){
StringBuilder ret = new StringBuilder();
for(int i = 0;i < times;i++) ret.append(str);
return ret.toString();
}
public static String intToString(Integer num, Integer digits) {
if (digits<0){
return num.toString();
}
// create variable length array of zeros
char[] zeros = new char[digits];
Arrays.fill(zeros, '0');
// format number as String
DecimalFormat df = new DecimalFormat(String.valueOf(zeros));
return df.format(num);
}
public static String MD5(String md5) {
try {
byte[] bytesOfMessage;
try {
bytesOfMessage = md5.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] array = md.digest(bytesOfMessage);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < array.length; ++i) {
sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
}
return sb.toString();
} catch (UnsupportedEncodingException ex) {
java.util.logging.Logger.getLogger(util.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (NoSuchAlgorithmException e) {
}
return null;
}
public static Boolean HandleNonCompatiblePlugins(){
Boolean DisableForConflict = Boolean.TRUE;
Boolean ReloadUI = Boolean.FALSE;
//Boolean DisableForConflict = GetTrueFalseOption("Utility", "PluginConflictMode", Boolean.FALSE);
UIContext tUI = new UIContext(sagex.api.Global.GetUIContextName());
// //List plugins
// Object[] plugins = PluginAPI.GetAllAvailablePlugins();
// if (plugins != null && plugins.length > 0) {
// for (Object plugin : plugins) {
// LOG.debug("HandleNonCompatiblePlugins: Plugin '" + PluginAPI.GetPluginIdentifier(plugin)+ "' Installed '" + PluginAPI.IsPluginInstalled(plugin) + "' Enabled '" + PluginAPI.IsPluginEnabled(plugin) + "' C Installed '" + PluginAPI.IsClientPluginInstalled(plugin) + "'");
// }
// }
//
//check for CVF
Object thisPlugin = sagex.api.PluginAPI.GetAvailablePluginForID(tUI,"jusjokencvf");
if (sagex.api.PluginAPI.IsPluginEnabled(tUI,thisPlugin)){
if(DisableForConflict){
sagex.api.PluginAPI.DisablePlugin(tUI, thisPlugin);
String tMessage = "CVF Plugin is NOT compatible with Gemstone as Gemstone now contains similar functions.\n \n* CVF Plugin has been disabled.";
PostSytemMessage(Const.SystemMessagePluginConflictCode, Const.SystemMessagePluginConflictName, Const.SystemMessageAlertLevelInfo, tMessage);
ReloadUI = Boolean.TRUE;
LOG.debug("HandleNonCompatiblePlugins: CVF found and disabled");
}else{
String tMessage = "CVF Plugin is NOT compatible with Gemstone as Gemstone now contains similar functions.\n \n* Please disable the CVF Plugin and reload the UI.";
PostSytemMessage(Const.SystemMessagePluginConflictCode, Const.SystemMessagePluginConflictName, Const.SystemMessageAlertLevelError, tMessage);
LOG.debug("HandleNonCompatiblePlugins: CVF found and System Error message created");
}
}else{
LOG.debug("HandleNonCompatiblePlugins: checking for CVF - not found");
}
//check for ADM
thisPlugin = sagex.api.PluginAPI.GetAvailablePluginForID(tUI,"jusjokenadm");
if (sagex.api.PluginAPI.IsPluginEnabled(tUI, thisPlugin)){
if(DisableForConflict){
sagex.api.PluginAPI.DisablePlugin(tUI, thisPlugin);
String tMessage = "ADM Plugin is NOT compatible with Gemstone as Gemstone now contains similar functions.\n \n* ADM Plugin has been disabled.";
PostSytemMessage(Const.SystemMessagePluginConflictCode, Const.SystemMessagePluginConflictName, Const.SystemMessageAlertLevelInfo, tMessage);
ReloadUI = Boolean.TRUE;
LOG.debug("HandleNonCompatiblePlugins: ADM found and disabled");
}else{
String tMessage = "ADM Plugin is NOT compatible with Gemstone as Gemstone now contains similar functions.\n \n* Please disable the ADM Plugin and reload the UI.";
PostSytemMessage(Const.SystemMessagePluginConflictCode, Const.SystemMessagePluginConflictName, Const.SystemMessageAlertLevelError, tMessage);
LOG.debug("HandleNonCompatiblePlugins: ADM found and System Error message created");
}
}else{
LOG.debug("HandleNonCompatiblePlugins: checking for ADM - not found");
}
return ReloadUI;
}
public static void PostSytemMessage(Integer Code, String MessageType, Integer AlertLevel, String Message){
Properties MessageProp = new Properties();
MessageProp.setProperty("code", Code.toString());
MessageProp.setProperty("typename", MessageType);
sagex.api.SystemMessageAPI.PostSystemMessage(new UIContext(sagex.api.Global.GetUIContextName()), Code, AlertLevel, Message, MessageProp);
}
public static String CleanProperty(String PropLocation, String Default){
String tValue = GetProperty(PropLocation, Default);
//see if the value has Diamond_ or sagediamond_ in it and if so then return the default
if (tValue.startsWith("Diamond_") || tValue.startsWith("sagediamond_")){
//save the default so the old invalid property is overwritten
SetProperty(PropLocation, Default);
return Default;
}
return tValue;
}
public static void BuildActions(){
UIContext tUI = new UIContext(sagex.api.Global.GetUIContextName());
Properties Props = new Properties();
Object[] Menus = sagex.api.WidgetAPI.GetWidgetsByType(tUI,"Menu");
for (Object item: Menus){
String tName = sagex.api.WidgetAPI.GetWidgetName(item);
//LOG.debug("BuildActions: Menu '" + tName + "'");
if (tName.startsWith("PlayOn::")){
String tTitle = tName.substring(8);
if (tTitle.startsWith("Custom")){
continue;
}
String ActionName = tTitle.replaceAll("::", "_");
String ActionVal = tTitle.replaceAll("::", " ");
ActionName = "xItemPlayOn_" + ActionName.replaceAll(" ", "_");
String ActionTitle = tTitle.replaceAll("::", " - ");
LOG.debug("BuildActions: Item '" + ActionName + "' Title '" + ActionTitle + "'");
String Start = "ADM/custom_actions/";
Props.put(Start + ActionName + "/ActionCategory/1", "Online");
Props.put(Start + ActionName + "/ActionCategory/2", "PlayOn");
Props.put(Start + ActionName + "/ButtonText", ActionTitle);
Props.put(Start + ActionName + "/WidgetSymbol", "KMWIY-932161");
Props.put(Start + ActionName + "/ActionVariables/1/Val", ActionVal);
Props.put(Start + ActionName + "/ActionVariables/1/Var", "PlayOnMenuItem");
Props.put(Start + ActionName + "/ActionVariables/1/VarType", "VarTypeGlobal");
Props.put(Start + ActionName + "/CopyModeAttributeVar", "ThisItem");
}
}
String FilePath = util.UserDataLocation() + File.separator + "ActionTemp.properties";
if (Props.size()>0){
try {
FileOutputStream out = new FileOutputStream(FilePath);
try {
Props.store(out, Const.PropertyComment);
out.close();
} catch (IOException ex) {
LOG.debug("Execute: error exporting properties " + util.class.getName() + ex);
}
} catch (FileNotFoundException ex) {
LOG.debug("Execute: error exporting properties " + util.class.getName() + ex);
}
}
}
}
| Menu Manager - changing to external Menu.properties file - version 1.008 | Gemstone/src/Gemstone/util.java | Menu Manager - changing to external Menu.properties file - version 1.008 |
|
Java | apache-2.0 | 7571d2e07eb5a561f26eb58a6a9f9b2b608de709 | 0 | Sage-Bionetworks/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services | package org.sagebionetworks.repo.manager.authentication;
import java.util.Date;
import org.sagebionetworks.repo.manager.AuthenticationManager;
import org.sagebionetworks.repo.manager.UserCredentialValidator;
import org.sagebionetworks.repo.manager.oauth.OIDCTokenHelper;
import org.sagebionetworks.repo.manager.password.InvalidPasswordException;
import org.sagebionetworks.repo.manager.password.PasswordValidator;
import org.sagebionetworks.repo.model.AuthorizationUtils;
import org.sagebionetworks.repo.model.UnauthenticatedException;
import org.sagebionetworks.repo.model.UserInfo;
import org.sagebionetworks.repo.model.auth.AuthenticatedOn;
import org.sagebionetworks.repo.model.auth.AuthenticationDAO;
import org.sagebionetworks.repo.model.auth.ChangePasswordInterface;
import org.sagebionetworks.repo.model.auth.ChangePasswordWithCurrentPassword;
import org.sagebionetworks.repo.model.auth.ChangePasswordWithToken;
import org.sagebionetworks.repo.model.auth.LoginRequest;
import org.sagebionetworks.repo.model.auth.LoginResponse;
import org.sagebionetworks.repo.model.auth.PasswordResetSignedToken;
import org.sagebionetworks.repo.model.principal.AliasType;
import org.sagebionetworks.repo.model.principal.PrincipalAlias;
import org.sagebionetworks.repo.model.principal.PrincipalAliasDAO;
import org.sagebionetworks.repo.transactions.WriteTransaction;
import org.sagebionetworks.repo.web.NotFoundException;
import org.sagebionetworks.securitytools.PBKDF2Utils;
import org.sagebionetworks.util.Clock;
import org.sagebionetworks.util.ValidateArgument;
import org.springframework.beans.factory.annotation.Autowired;
public class AuthenticationManagerImpl implements AuthenticationManager {
public static final long LOCK_TIMOUTE_SEC = 5*60;
public static final int MAX_CONCURRENT_LOCKS = 10;
public static final String ACCOUNT_LOCKED_MESSAGE = "This account has been locked. Reason: too many requests. Please try again in five minutes.";
@Autowired
private AuthenticationDAO authDAO;
@Autowired
private AuthenticationReceiptTokenGenerator authenticationReceiptTokenGenerator;
@Autowired
private PasswordValidator passwordValidator;
@Autowired
private UserCredentialValidator userCredentialValidator;
@Autowired
private PrincipalAliasDAO principalAliasDAO;
@Autowired
private PasswordResetTokenGenerator passwordResetTokenGenerator;
@Autowired
private OIDCTokenHelper oidcTokenHelper;
@Autowired
private Clock clock;
@Override
@WriteTransaction
public void setPassword(Long principalId, String password) {
passwordValidator.validatePassword(password);
String passHash = PBKDF2Utils.hashPassword(password, null);
authDAO.changePassword(principalId, passHash);
}
@WriteTransaction
public long changePassword(ChangePasswordInterface changePasswordInterface){
ValidateArgument.required(changePasswordInterface, "changePasswordInterface");
final long userId;
if(changePasswordInterface instanceof ChangePasswordWithCurrentPassword){
userId = validateChangePassword((ChangePasswordWithCurrentPassword) changePasswordInterface);
}else if (changePasswordInterface instanceof ChangePasswordWithToken){
userId = validateChangePassword((ChangePasswordWithToken) changePasswordInterface);
}else{
throw new IllegalArgumentException("Unknown implementation of ChangePasswordInterface");
}
setPassword(userId, changePasswordInterface.getNewPassword());
userCredentialValidator.forceResetLoginThrottle(userId);
return userId;
}
/**
*
* @param changePasswordWithCurrentPassword
* @return id of user for which password change occurred
*/
long validateChangePassword(ChangePasswordWithCurrentPassword changePasswordWithCurrentPassword) {
ValidateArgument.required(changePasswordWithCurrentPassword.getUsername(), "changePasswordWithCurrentPassword.username");
ValidateArgument.required(changePasswordWithCurrentPassword.getCurrentPassword(), "changePasswordWithCurrentPassword.currentPassword");
final long userId = findUserIdForAuthentication(changePasswordWithCurrentPassword.getUsername());
//we can ignore the return value here because we are not generating a new authentication receipt on success
validateAuthReceiptAndCheckPassword(userId, changePasswordWithCurrentPassword.getCurrentPassword(), changePasswordWithCurrentPassword.getAuthenticationReceipt());
return userId;
}
/**
*
* @param changePasswordWithToken
* @return id of user for which password change occurred
*/
long validateChangePassword(ChangePasswordWithToken changePasswordWithToken){
ValidateArgument.required(changePasswordWithToken.getPasswordChangeToken(), "changePasswordWithToken.passwordChangeToken");
if(!passwordResetTokenGenerator.isValidToken(changePasswordWithToken.getPasswordChangeToken())){
throw new IllegalArgumentException("Password reset token is invalid");
}
return Long.parseLong(changePasswordWithToken.getPasswordChangeToken().getUserId());
}
@Override
public String getSecretKey(Long principalId) throws NotFoundException {
return authDAO.getSecretKey(principalId);
}
@Override
@WriteTransaction
public void changeSecretKey(Long principalId) {
authDAO.changeSecretKey(principalId);
}
@Override
public PasswordResetSignedToken createPasswordResetToken(long userId) throws NotFoundException {
return passwordResetTokenGenerator.getToken(userId);
}
@Override
public boolean hasUserAcceptedTermsOfUse(Long id) throws NotFoundException {
return authDAO.hasUserAcceptedToU(id);
}
@Override
@WriteTransaction
public void setTermsOfUseAcceptance(Long principalId, Boolean acceptance) {
if (acceptance == null) {
throw new IllegalArgumentException("Cannot \"unsign\" the terms of use");
}
authDAO.setTermsOfUseAcceptance(principalId, acceptance);
}
@Override
public LoginResponse login(LoginRequest request, String tokenIssuer){
ValidateArgument.required(request, "loginRequest");
ValidateArgument.required(request.getUsername(), "LoginRequest.username");
ValidateArgument.required(request.getPassword(), "LoginRequest.password");
final long userId = findUserIdForAuthentication(request.getUsername());
final String password = request.getPassword();
final String authenticationReceipt = request.getAuthenticationReceipt();
validateAuthReceiptAndCheckPassword(userId, password, authenticationReceipt);
return getLoginResponseAfterSuccessfulPasswordAuthentication(userId, tokenIssuer);
}
public AuthenticatedOn getAuthenticatedOn(UserInfo userInfo) {
if (AuthorizationUtils.isUserAnonymous(userInfo)) {
throw new UnauthenticatedException("Cannot retrieve authentication time stamp for anonymous user.");
}
// Note the date will be null if the user has not logged in
Date authenticatedOn = authDAO.getAuthenticatedOn(userInfo.getId());
AuthenticatedOn result = new AuthenticatedOn();
result.setAuthenticatedOn(authenticatedOn);
return result;
}
/**
* Validate authenticationReceipt and then checks that the password is correct for the given principalId
* @param userId id of the user
* @param password password of the user
* @param authenticationReceipt Can be null. When valid, does not throttle attempts on consecutive incorrect passwords.
* @return authenticationReceipt if it is valid and password check passed. null, if the authenticationReceipt was invalid, but password check passed.
* @throws UnauthenticatedException if password check failed
*/
void validateAuthReceiptAndCheckPassword(final long userId, final String password, final String authenticationReceipt) {
boolean isAuthenticationReceiptValid = authenticationReceiptTokenGenerator.isReceiptValid(userId, authenticationReceipt);
//callers that have previously logged in successfully are able to bypass lockout caused by failed attempts
boolean correctCredentials = isAuthenticationReceiptValid ? userCredentialValidator.checkPassword(userId, password) : userCredentialValidator.checkPasswordWithThrottling(userId, password);
if(!correctCredentials){
throw new UnauthenticatedException(UnauthenticatedException.MESSAGE_USERNAME_PASSWORD_COMBINATION_IS_INCORRECT);
}
// Now that the password has been verified,
// ensure that if the current password is a weak password, only allow the user to reset via emailed token
try{
passwordValidator.validatePassword(password);
} catch (InvalidPasswordException e){
throw new PasswordResetViaEmailRequiredException("You must change your password via email reset.");
}
}
@Override
public LoginResponse loginWithNoPasswordCheck(long principalId, String issuer){
return getLoginResponseAfterSuccessfulPasswordAuthentication(principalId, issuer);
}
LoginResponse getLoginResponseAfterSuccessfulPasswordAuthentication(long principalId, String issuer) {
String newAuthenticationReceipt = authenticationReceiptTokenGenerator.createNewAuthenticationReciept(principalId);
String accessToken = oidcTokenHelper.createClientTotalAccessToken(principalId, issuer);
boolean acceptsTermsOfUse = authDAO.hasUserAcceptedToU(principalId);
authDAO.setAuthenticatedOn(principalId, clock.now());
return createLoginResponse(accessToken, acceptsTermsOfUse, newAuthenticationReceipt);
}
private static LoginResponse createLoginResponse(String accessToken, boolean acceptsTermsOfUse, String newReceipt) {
LoginResponse response = new LoginResponse();
response.setAccessToken(accessToken);
response.setAcceptsTermsOfUse(acceptsTermsOfUse);
response.setAuthenticationReceipt(newReceipt);
return response;
}
long findUserIdForAuthentication(final String usernameOrEmail){
PrincipalAlias principalAlias = principalAliasDAO.findPrincipalWithAlias(usernameOrEmail, AliasType.USER_EMAIL, AliasType.USER_NAME);
if (principalAlias == null){
throw new UnauthenticatedException(UnauthenticatedException.MESSAGE_USERNAME_PASSWORD_COMBINATION_IS_INCORRECT);
}
return principalAlias.getPrincipalId();
}
}
| services/repository-managers/src/main/java/org/sagebionetworks/repo/manager/authentication/AuthenticationManagerImpl.java | package org.sagebionetworks.repo.manager.authentication;
import java.util.Date;
import org.sagebionetworks.repo.manager.AuthenticationManager;
import org.sagebionetworks.repo.manager.UserCredentialValidator;
import org.sagebionetworks.repo.manager.oauth.OIDCTokenHelper;
import org.sagebionetworks.repo.manager.password.InvalidPasswordException;
import org.sagebionetworks.repo.manager.password.PasswordValidator;
import org.sagebionetworks.repo.model.AuthorizationUtils;
import org.sagebionetworks.repo.model.UnauthenticatedException;
import org.sagebionetworks.repo.model.UserInfo;
import org.sagebionetworks.repo.model.auth.AuthenticatedOn;
import org.sagebionetworks.repo.model.auth.AuthenticationDAO;
import org.sagebionetworks.repo.model.auth.ChangePasswordInterface;
import org.sagebionetworks.repo.model.auth.ChangePasswordWithCurrentPassword;
import org.sagebionetworks.repo.model.auth.ChangePasswordWithToken;
import org.sagebionetworks.repo.model.auth.LoginRequest;
import org.sagebionetworks.repo.model.auth.LoginResponse;
import org.sagebionetworks.repo.model.auth.PasswordResetSignedToken;
import org.sagebionetworks.repo.model.principal.AliasType;
import org.sagebionetworks.repo.model.principal.PrincipalAlias;
import org.sagebionetworks.repo.model.principal.PrincipalAliasDAO;
import org.sagebionetworks.repo.transactions.WriteTransaction;
import org.sagebionetworks.repo.web.NotFoundException;
import org.sagebionetworks.securitytools.PBKDF2Utils;
import org.sagebionetworks.util.Clock;
import org.sagebionetworks.util.ValidateArgument;
import org.springframework.beans.factory.annotation.Autowired;
public class AuthenticationManagerImpl implements AuthenticationManager {
public static final long LOCK_TIMOUTE_SEC = 5*60;
public static final int MAX_CONCURRENT_LOCKS = 10;
public static final String ACCOUNT_LOCKED_MESSAGE = "This account has been locked. Reason: too many requests. Please try again in five minutes.";
@Autowired
private AuthenticationDAO authDAO;
@Autowired
private AuthenticationReceiptTokenGenerator authenticationReceiptTokenGenerator;
@Autowired
private PasswordValidator passwordValidator;
@Autowired
private UserCredentialValidator userCredentialValidator;
@Autowired
private PrincipalAliasDAO principalAliasDAO;
@Autowired
private PasswordResetTokenGenerator passwordResetTokenGenerator;
@Autowired
private OIDCTokenHelper oidcTokenHelper;
@Autowired
private Clock clock;
@Override
@WriteTransaction
public void setPassword(Long principalId, String password) {
passwordValidator.validatePassword(password);
String passHash = PBKDF2Utils.hashPassword(password, null);
authDAO.changePassword(principalId, passHash);
}
@WriteTransaction
public long changePassword(ChangePasswordInterface changePasswordInterface){
ValidateArgument.required(changePasswordInterface, "changePasswordInterface");
final long userId;
if(changePasswordInterface instanceof ChangePasswordWithCurrentPassword){
userId = validateChangePassword((ChangePasswordWithCurrentPassword) changePasswordInterface);
}else if (changePasswordInterface instanceof ChangePasswordWithToken){
userId = validateChangePassword((ChangePasswordWithToken) changePasswordInterface);
}else{
throw new IllegalArgumentException("Unknown implementation of ChangePasswordInterface");
}
setPassword(userId, changePasswordInterface.getNewPassword());
userCredentialValidator.forceResetLoginThrottle(userId);
return userId;
}
/**
*
* @param changePasswordWithCurrentPassword
* @return id of user for which password change occurred
*/
long validateChangePassword(ChangePasswordWithCurrentPassword changePasswordWithCurrentPassword) {
ValidateArgument.required(changePasswordWithCurrentPassword.getUsername(), "changePasswordWithCurrentPassword.userName");
ValidateArgument.required(changePasswordWithCurrentPassword.getCurrentPassword(), "changePasswordWithCurrentPassword.currentPassword");
final long userId = findUserIdForAuthentication(changePasswordWithCurrentPassword.getUsername());
//we can ignore the return value here because we are not generating a new authentication receipt on success
validateAuthReceiptAndCheckPassword(userId, changePasswordWithCurrentPassword.getCurrentPassword(), changePasswordWithCurrentPassword.getAuthenticationReceipt());
return userId;
}
/**
*
* @param changePasswordWithToken
* @return id of user for which password change occurred
*/
long validateChangePassword(ChangePasswordWithToken changePasswordWithToken){
ValidateArgument.required(changePasswordWithToken.getPasswordChangeToken(), "changePasswordWithToken.passwordChangeToken");
if(!passwordResetTokenGenerator.isValidToken(changePasswordWithToken.getPasswordChangeToken())){
throw new IllegalArgumentException("Password reset token is invalid");
}
return Long.parseLong(changePasswordWithToken.getPasswordChangeToken().getUserId());
}
@Override
public String getSecretKey(Long principalId) throws NotFoundException {
return authDAO.getSecretKey(principalId);
}
@Override
@WriteTransaction
public void changeSecretKey(Long principalId) {
authDAO.changeSecretKey(principalId);
}
@Override
public PasswordResetSignedToken createPasswordResetToken(long userId) throws NotFoundException {
return passwordResetTokenGenerator.getToken(userId);
}
@Override
public boolean hasUserAcceptedTermsOfUse(Long id) throws NotFoundException {
return authDAO.hasUserAcceptedToU(id);
}
@Override
@WriteTransaction
public void setTermsOfUseAcceptance(Long principalId, Boolean acceptance) {
if (acceptance == null) {
throw new IllegalArgumentException("Cannot \"unsign\" the terms of use");
}
authDAO.setTermsOfUseAcceptance(principalId, acceptance);
}
@Override
public LoginResponse login(LoginRequest request, String tokenIssuer){
ValidateArgument.required(request, "loginRequest");
ValidateArgument.required(request.getUsername(), "LoginRequest.username");
ValidateArgument.required(request.getPassword(), "LoginRequest.password");
final long userId = findUserIdForAuthentication(request.getUsername());
final String password = request.getPassword();
final String authenticationReceipt = request.getAuthenticationReceipt();
validateAuthReceiptAndCheckPassword(userId, password, authenticationReceipt);
return getLoginResponseAfterSuccessfulPasswordAuthentication(userId, tokenIssuer);
}
public AuthenticatedOn getAuthenticatedOn(UserInfo userInfo) {
if (AuthorizationUtils.isUserAnonymous(userInfo)) {
throw new UnauthenticatedException("Cannot retrieve authentication time stamp for anonymous user.");
}
// Note the date will be null if the user has not logged in
Date authenticatedOn = authDAO.getAuthenticatedOn(userInfo.getId());
AuthenticatedOn result = new AuthenticatedOn();
result.setAuthenticatedOn(authenticatedOn);
return result;
}
/**
* Validate authenticationReceipt and then checks that the password is correct for the given principalId
* @param userId id of the user
* @param password password of the user
* @param authenticationReceipt Can be null. When valid, does not throttle attempts on consecutive incorrect passwords.
* @return authenticationReceipt if it is valid and password check passed. null, if the authenticationReceipt was invalid, but password check passed.
* @throws UnauthenticatedException if password check failed
*/
void validateAuthReceiptAndCheckPassword(final long userId, final String password, final String authenticationReceipt) {
boolean isAuthenticationReceiptValid = authenticationReceiptTokenGenerator.isReceiptValid(userId, authenticationReceipt);
//callers that have previously logged in successfully are able to bypass lockout caused by failed attempts
boolean correctCredentials = isAuthenticationReceiptValid ? userCredentialValidator.checkPassword(userId, password) : userCredentialValidator.checkPasswordWithThrottling(userId, password);
if(!correctCredentials){
throw new UnauthenticatedException(UnauthenticatedException.MESSAGE_USERNAME_PASSWORD_COMBINATION_IS_INCORRECT);
}
// Now that the password has been verified,
// ensure that if the current password is a weak password, only allow the user to reset via emailed token
try{
passwordValidator.validatePassword(password);
} catch (InvalidPasswordException e){
throw new PasswordResetViaEmailRequiredException("You must change your password via email reset.");
}
}
@Override
public LoginResponse loginWithNoPasswordCheck(long principalId, String issuer){
return getLoginResponseAfterSuccessfulPasswordAuthentication(principalId, issuer);
}
LoginResponse getLoginResponseAfterSuccessfulPasswordAuthentication(long principalId, String issuer) {
String newAuthenticationReceipt = authenticationReceiptTokenGenerator.createNewAuthenticationReciept(principalId);
String accessToken = oidcTokenHelper.createClientTotalAccessToken(principalId, issuer);
boolean acceptsTermsOfUse = authDAO.hasUserAcceptedToU(principalId);
authDAO.setAuthenticatedOn(principalId, clock.now());
return createLoginResponse(accessToken, acceptsTermsOfUse, newAuthenticationReceipt);
}
private static LoginResponse createLoginResponse(String accessToken, boolean acceptsTermsOfUse, String newReceipt) {
LoginResponse response = new LoginResponse();
response.setAccessToken(accessToken);
response.setAcceptsTermsOfUse(acceptsTermsOfUse);
response.setAuthenticationReceipt(newReceipt);
return response;
}
long findUserIdForAuthentication(final String usernameOrEmail){
PrincipalAlias principalAlias = principalAliasDAO.findPrincipalWithAlias(usernameOrEmail, AliasType.USER_EMAIL, AliasType.USER_NAME);
if (principalAlias == null){
throw new UnauthenticatedException(UnauthenticatedException.MESSAGE_USERNAME_PASSWORD_COMBINATION_IS_INCORRECT);
}
return principalAlias.getPrincipalId();
}
}
| error message should match request object
| services/repository-managers/src/main/java/org/sagebionetworks/repo/manager/authentication/AuthenticationManagerImpl.java | error message should match request object |
|
Java | apache-2.0 | 27565810d55d2e16f8c3402cdf8ac18fc5f568be | 0 | evanchsa/eik,evanchsa/eik | /**
* Copyright (c) 2009 Stephen Evanchik
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Stephen Evanchik - initial implementation
*/
package info.evanchik.eclipse.karaf.ui;
/**
* @author Stephen Evanchik ([email protected])
*
*/
public final class KarafLaunchConfigurationConstants {
/**
* The list of features to use during Karaf boot
*/
public static final String KARAF_LAUNCH_BOOT_FEATURES = "karaf_boot_features"; //$NON-NLS-1$
/**
* The workspace project that contains all of the configuration data for the
* launch configuration
*/
public static final String KARAF_LAUNCH_CONFIGURATION_PROJECT = "karaf_configuration_project"; //$NON-NLS-1$
/**
* Determines whether or not the Karaf Features system is managed by the
* Eclipse launch configuration
*/
public static final String KARAF_LAUNCH_FEATURES_MANAGEMENT = "karaf_features_management"; //$NON-NLS-1$
/**
* PDE Launcher constant used for recording classpath entries used as part
* of the boot classpath for Karaf
*/
public static final String KARAF_LAUNCH_REQUIRED_BOOT_CLASSPATH = "karaf_required_boot_classpath"; //$NON-NLS-1$
/**
* Contains the root directory of the Karaf platform that this launch
* configuration is configured against
*/
public static final String KARAF_LAUNCH_SOURCE_RUNTIME = "karaf_source_runtime"; //$NON-NLS-1$
/**
* PDE Launcher constant used for determining if the local console should
* start
*/
public static final String KARAF_LAUNCH_START_LOCAL_CONSOLE = "karaf_start_local_console"; //$NON-NLS-1$
/**
* PDE Launcher constant used for determining if the remote console should
* start
*/
public static final String KARAF_LAUNCH_START_REMOTE_CONSOLE = "karaf_start_remote_console"; //$NON-NLS-1$
/**
* Private constructor to prevent instantiation.
*/
private KarafLaunchConfigurationConstants() {
throw new AssertionError(KarafLaunchConfigurationConstants.class.getName() + " cannot be instantiated");
}
}
| plugins/info.evanchik.eclipse.karaf.ui/src/main/java/info/evanchik/eclipse/karaf/ui/KarafLaunchConfigurationConstants.java | /**
* Copyright (c) 2009 Stephen Evanchik
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Stephen Evanchik - initial implementation
*/
package info.evanchik.eclipse.karaf.ui;
/**
* @author Stephen Evanchik ([email protected])
*
*/
public final class KarafLaunchConfigurationConstants {
/**
* The list of features to use during Karaf boot
*/
public static final String KARAF_LAUNCH_BOOT_FEATURES = "karaf_boot_features"; //$NON-NLS-1$
/**
* The workspace project that contains all of the configuration data for the
* launch configuration
*/
public static final String KARAF_LAUNCH_CONFIGURATION_PROJECT = "karaf_configuration_project"; //$NON-NLS-1$
/**
* Determines whether or not the Karaf Features system is managed by the
* Eclipse launch configuration
*/
public static final String KARAF_LAUNCH_FEATURES_MANAGEMENT = "karaf_features_management"; //$NON-NLS-1$
/**
* PDE Launcher constant used for recording classpath entries used as part
* of the boot classpath for Karaf
*/
public static final String KARAF_LAUNCH_REQUIRED_BOOT_CLASSPATH = "karaf_required_boot_classpath"; //$NON-NLS-1$
/**
* Contains the root directory that this launch configuration will use for
* its source configuration data
*/
public static final String KARAF_LAUNCH_SOURCE_RUNTIME = "karaf_source_runtime"; //$NON-NLS-1$
/**
* PDE Launcher constant used for determining if the local console should
* start
*/
public static final String KARAF_LAUNCH_START_LOCAL_CONSOLE = "karaf_start_local_console"; //$NON-NLS-1$
/**
* PDE Launcher constant used for determining if the remote console should
* start
*/
public static final String KARAF_LAUNCH_START_REMOTE_CONSOLE = "karaf_start_remote_console"; //$NON-NLS-1$
/**
* Private constructor to prevent instantiation.
*/
private KarafLaunchConfigurationConstants() {
throw new AssertionError(KarafLaunchConfigurationConstants.class.getName() + " cannot be instantiated");
}
}
| Updating comment to accurately describe source property
| plugins/info.evanchik.eclipse.karaf.ui/src/main/java/info/evanchik/eclipse/karaf/ui/KarafLaunchConfigurationConstants.java | Updating comment to accurately describe source property |
|
Java | apache-2.0 | 8f951f13f1b9898457d1ce42e24d0b3d35b191a4 | 0 | ChinaQuants/OG-Platform,ChinaQuants/OG-Platform,ChinaQuants/OG-Platform,jerome79/OG-Platform,nssales/OG-Platform,jerome79/OG-Platform,DevStreet/FinanceAnalytics,codeaudit/OG-Platform,jerome79/OG-Platform,jerome79/OG-Platform,nssales/OG-Platform,jeorme/OG-Platform,ChinaQuants/OG-Platform,McLeodMoores/starling,nssales/OG-Platform,codeaudit/OG-Platform,jeorme/OG-Platform,codeaudit/OG-Platform,McLeodMoores/starling,McLeodMoores/starling,jeorme/OG-Platform,DevStreet/FinanceAnalytics,McLeodMoores/starling,nssales/OG-Platform,jeorme/OG-Platform,codeaudit/OG-Platform,DevStreet/FinanceAnalytics,DevStreet/FinanceAnalytics | /**
* Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.financial.analytics.model.curve.interestrate;
import static com.opengamma.engine.value.ValuePropertyNames.CURVE;
import static com.opengamma.engine.value.ValuePropertyNames.CURVE_CALCULATION_CONFIG;
import static com.opengamma.engine.value.ValuePropertyNames.CURVE_CALCULATION_METHOD;
import static com.opengamma.engine.value.ValueRequirementNames.YIELD_CURVE;
import static com.opengamma.engine.value.ValueRequirementNames.YIELD_CURVE_JACOBIAN;
import static com.opengamma.financial.analytics.model.curve.interestrate.MultiYieldCurvePropertiesAndDefaults.PROPERTY_DECOMPOSITION;
import static com.opengamma.financial.analytics.model.curve.interestrate.MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_ABSOLUTE_TOLERANCE;
import static com.opengamma.financial.analytics.model.curve.interestrate.MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_MAX_ITERATIONS;
import static com.opengamma.financial.analytics.model.curve.interestrate.MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_RELATIVE_TOLERANCE;
import static com.opengamma.financial.analytics.model.curve.interestrate.MultiYieldCurvePropertiesAndDefaults.PROPERTY_USE_FINITE_DIFFERENCE;
import static com.opengamma.financial.convention.initializer.PerCurrencyConventionHelper.DEPOSIT;
import static com.opengamma.financial.convention.initializer.PerCurrencyConventionHelper.SCHEME_NAME;
import static com.opengamma.financial.convention.initializer.PerCurrencyConventionHelper.getConventionName;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.threeten.bp.Instant;
import org.threeten.bp.LocalTime;
import org.threeten.bp.ZoneOffset;
import org.threeten.bp.ZonedDateTime;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.analytics.financial.forex.method.FXMatrix;
import com.opengamma.analytics.financial.interestrate.InstrumentDerivative;
import com.opengamma.analytics.financial.interestrate.MultipleYieldCurveFinderDataBundle;
import com.opengamma.analytics.financial.interestrate.MultipleYieldCurveFinderFunction;
import com.opengamma.analytics.financial.interestrate.MultipleYieldCurveFinderJacobian;
import com.opengamma.analytics.financial.interestrate.ParRateCalculator;
import com.opengamma.analytics.financial.interestrate.ParRateCurveSensitivityCalculator;
import com.opengamma.analytics.financial.interestrate.YieldCurveBundle;
import com.opengamma.analytics.financial.interestrate.cash.derivative.Cash;
import com.opengamma.analytics.financial.interestrate.cash.method.CashDiscountingMethod;
import com.opengamma.analytics.financial.model.interestrate.curve.YieldAndDiscountCurve;
import com.opengamma.analytics.financial.model.interestrate.curve.YieldCurve;
import com.opengamma.analytics.financial.schedule.ScheduleCalculator;
import com.opengamma.analytics.math.curve.InterpolatedDoublesCurve;
import com.opengamma.analytics.math.function.Function1D;
import com.opengamma.analytics.math.interpolation.CombinedInterpolatorExtrapolator;
import com.opengamma.analytics.math.interpolation.CombinedInterpolatorExtrapolatorFactory;
import com.opengamma.analytics.math.interpolation.Interpolator1D;
import com.opengamma.analytics.math.linearalgebra.Decomposition;
import com.opengamma.analytics.math.linearalgebra.DecompositionFactory;
import com.opengamma.analytics.math.matrix.DoubleMatrix1D;
import com.opengamma.analytics.math.matrix.DoubleMatrix2D;
import com.opengamma.analytics.math.rootfinding.newton.BroydenVectorRootFinder;
import com.opengamma.analytics.math.rootfinding.newton.NewtonVectorRootFinder;
import com.opengamma.analytics.util.time.TimeCalculator;
import com.opengamma.core.convention.ConventionSource;
import com.opengamma.core.holiday.HolidaySource;
import com.opengamma.engine.ComputationTarget;
import com.opengamma.engine.ComputationTargetSpecification;
import com.opengamma.engine.function.AbstractFunction;
import com.opengamma.engine.function.CompiledFunctionDefinition;
import com.opengamma.engine.function.FunctionCompilationContext;
import com.opengamma.engine.function.FunctionExecutionContext;
import com.opengamma.engine.function.FunctionInputs;
import com.opengamma.engine.target.ComputationTargetType;
import com.opengamma.engine.value.ComputedValue;
import com.opengamma.engine.value.ValueProperties;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.value.ValueSpecification;
import com.opengamma.financial.OpenGammaExecutionContext;
import com.opengamma.financial.analytics.conversion.CalendarUtils;
import com.opengamma.financial.analytics.ircurve.FixedIncomeStrip;
import com.opengamma.financial.analytics.ircurve.StripInstrumentType;
import com.opengamma.financial.analytics.ircurve.YieldCurveDefinition;
import com.opengamma.financial.analytics.ircurve.calcconfig.MultiCurveCalculationConfig;
import com.opengamma.financial.analytics.model.InterpolatedDataProperties;
import com.opengamma.financial.config.ConfigSourceQuery;
import com.opengamma.financial.convention.DepositConvention;
import com.opengamma.financial.convention.businessday.BusinessDayConvention;
import com.opengamma.financial.convention.businessday.BusinessDayConventions;
import com.opengamma.financial.convention.calendar.Calendar;
import com.opengamma.financial.convention.daycount.DayCount;
import com.opengamma.financial.convention.daycount.DayCounts;
import com.opengamma.id.ExternalId;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.async.AsynchronousExecution;
import com.opengamma.util.money.Currency;
import com.opengamma.util.time.Tenor;
/**
* Constructs a single yield curve and its Jacobian from an FX-implied yield curve calculation configuration and a yield curve definition that contains <b>only</b> {@link StripInstrumentType#CASH}
* strips. The transformation of the yield curve allows risk to be displayed with respect to implied deposit rates, not FX forwards.
*/
public class ImpliedDepositCurveFunction extends AbstractFunction {
/** The calculation method property value */
public static final String IMPLIED_DEPOSIT = "ImpliedDeposit";
/** The Cash instrument method */
private static final CashDiscountingMethod METHOD_CASH = CashDiscountingMethod.getInstance();
/** Calculates the par rate */
private static final ParRateCalculator PAR_RATE_CALCULATOR = ParRateCalculator.getInstance();
/** Calculates the sensitivity of the par rate to the curves */
private static final ParRateCurveSensitivityCalculator PAR_RATE_SENSITIVITY_CALCULATOR = ParRateCurveSensitivityCalculator.getInstance();
/** The business day convention used for FX forward dates computation **/
private static final BusinessDayConvention MOD_FOL = BusinessDayConventions.MODIFIED_FOLLOWING;
/** The logger */
private static final Logger s_logger = LoggerFactory.getLogger(ImpliedDepositCurveFunction.class);
/** The curve name */
private final String _curveCalculationConfig;
private ConfigSourceQuery<MultiCurveCalculationConfig> _multiCurveCalculationConfig;
private ConfigSourceQuery<YieldCurveDefinition> _yieldCurveDefinition;
/**
* @param curveCalculationConfig The curve name, not null
*/
public ImpliedDepositCurveFunction(final String curveCalculationConfig) {
ArgumentChecker.notNull(curveCalculationConfig, "curve name");
_curveCalculationConfig = curveCalculationConfig;
}
@Override
public void init(final FunctionCompilationContext context) {
_multiCurveCalculationConfig = ConfigSourceQuery.init(context, this, MultiCurveCalculationConfig.class);
_yieldCurveDefinition = ConfigSourceQuery.init(context, this, YieldCurveDefinition.class);
}
@Override
public CompiledFunctionDefinition compile(final FunctionCompilationContext context, final Instant atInstant) {
final MultiCurveCalculationConfig impliedConfiguration = _multiCurveCalculationConfig.get(_curveCalculationConfig);
if (impliedConfiguration == null) {
throw new OpenGammaRuntimeException("Multi-curve calculation called " + _curveCalculationConfig + " was null");
}
ComputationTarget target = context.getComputationTargetResolver().resolve(impliedConfiguration.getTarget());
if (!(target.getValue() instanceof Currency)) {
throw new OpenGammaRuntimeException("Target of curve calculation configuration was not a currency");
}
final Currency impliedCurrency = (Currency) target.getValue();
if (!IMPLIED_DEPOSIT.equals(impliedConfiguration.getCalculationMethod())) {
throw new OpenGammaRuntimeException("Curve calculation method was not " + IMPLIED_DEPOSIT + " for configuration called " + _curveCalculationConfig);
}
final String[] impliedCurveNames = impliedConfiguration.getYieldCurveNames();
if (impliedCurveNames.length != 1) {
throw new OpenGammaRuntimeException("Can only handle configurations with a single implied curve");
}
final LinkedHashMap<String, String[]> originalConfigurationName = impliedConfiguration.getExogenousConfigData();
if (originalConfigurationName == null || originalConfigurationName.size() != 1) {
throw new OpenGammaRuntimeException("Need a configuration with one exogenous configuration");
}
final Map.Entry<String, String[]> entry = Iterables.getOnlyElement(originalConfigurationName.entrySet());
final String[] originalCurveNames = entry.getValue();
if (originalCurveNames.length != 1) {
s_logger.warn("Found more than one exogenous configuration name; using only the first");
}
final MultiCurveCalculationConfig originalConfiguration = _multiCurveCalculationConfig.get(entry.getKey());
if (originalConfiguration == null) {
throw new OpenGammaRuntimeException("Multi-curve calculation called " + entry.getKey() + " was null");
}
target = context.getComputationTargetResolver().resolve(originalConfiguration.getTarget());
if (!(target.getValue() instanceof Currency)) {
throw new OpenGammaRuntimeException("Target of curve calculation configuration was not a currency");
}
final Currency originalCurrency = (Currency) target.getValue();
if (!originalCurrency.equals(impliedCurrency)) {
throw new OpenGammaRuntimeException("Currency targets for configurations " + _curveCalculationConfig + " and " + entry.getKey() + " did not match");
}
final YieldCurveDefinition impliedDefinition = _yieldCurveDefinition.get(impliedCurveNames[0] + "_" + impliedCurrency.getCode());
if (impliedDefinition == null) {
throw new OpenGammaRuntimeException("Could not get implied definition called " + impliedCurveNames[0] + "_" + impliedCurrency.getCode());
}
final Set<FixedIncomeStrip> strips = impliedDefinition.getStrips();
for (final FixedIncomeStrip strip : strips) {
if (strip.getInstrumentType() != StripInstrumentType.CASH) {
throw new OpenGammaRuntimeException("Can only handle yield curve definitions with CASH strips");
}
}
final ZonedDateTime atZDT = ZonedDateTime.ofInstant(atInstant, ZoneOffset.UTC);
return new MyCompiledFunction(atZDT.with(LocalTime.MIDNIGHT), atZDT.plusDays(1).with(LocalTime.MIDNIGHT).minusNanos(1000000), impliedConfiguration, impliedDefinition,
originalConfiguration, originalCurveNames[0]);
};
private class MyCompiledFunction extends AbstractInvokingCompiledFunction {
/** The definition of the implied curve */
private final YieldCurveDefinition _impliedDefinition;
/** The implied curve calculation configuration */
private final MultiCurveCalculationConfig _impliedConfiguration;
/** The original curve calculation configuration */
private final MultiCurveCalculationConfig _originalConfiguration;
/** The implied curve name */
private final String _impliedCurveName;
/** The original curve name */
private final String _originalCurveName;
/** The currency */
private final Currency _currency;
/** The interpolator */
private final String _interpolatorName;
/** The left extrapolator */
private final String _leftExtrapolatorName;
/** The right extrapolator */
private final String _rightExtrapolatorName;
public MyCompiledFunction(final ZonedDateTime earliestInvokation, final ZonedDateTime latestInvokation, final MultiCurveCalculationConfig impliedConfiguration,
final YieldCurveDefinition impliedDefinition, final MultiCurveCalculationConfig originalConfiguration, final String originalCurveName) {
super(earliestInvokation, latestInvokation);
_impliedConfiguration = impliedConfiguration;
_impliedDefinition = impliedDefinition;
_originalConfiguration = originalConfiguration;
_impliedCurveName = impliedDefinition.getName();
_originalCurveName = originalCurveName;
_currency = impliedDefinition.getCurrency();
_interpolatorName = impliedDefinition.getInterpolatorName();
_leftExtrapolatorName = impliedDefinition.getLeftExtrapolatorName();
_rightExtrapolatorName = impliedDefinition.getRightExtrapolatorName();
}
@Override
public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target, final Set<ValueRequirement> desiredValues)
throws AsynchronousExecution {
final Object originalCurveObject = inputs.getValue(YIELD_CURVE);
if (originalCurveObject == null) {
throw new OpenGammaRuntimeException("Could not get original curve");
}
ValueProperties resultCurveProperties = null;
String absoluteToleranceName = null;
String relativeToleranceName = null;
String iterationsName = null;
String decompositionName = null;
String useFiniteDifferenceName = null;
for (final ValueRequirement desiredValue : desiredValues) {
if (desiredValue.getValueName().equals(YIELD_CURVE)) {
absoluteToleranceName = desiredValue.getConstraint(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_ABSOLUTE_TOLERANCE);
relativeToleranceName = desiredValue.getConstraint(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_RELATIVE_TOLERANCE);
iterationsName = desiredValue.getConstraint(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_MAX_ITERATIONS);
decompositionName = desiredValue.getConstraint(MultiYieldCurvePropertiesAndDefaults.PROPERTY_DECOMPOSITION);
useFiniteDifferenceName = desiredValue.getConstraint(MultiYieldCurvePropertiesAndDefaults.PROPERTY_USE_FINITE_DIFFERENCE);
resultCurveProperties = desiredValue.getConstraints().copy().get();
break;
}
}
if (resultCurveProperties == null) {
throw new OpenGammaRuntimeException("Could not get result curve properties");
}
final ValueProperties resultJacobianProperties = resultCurveProperties.withoutAny(CURVE);
ZonedDateTime valuationDateTime = executionContext.getValuationTime().atZone(executionContext.getValuationClock().getZone());
final HolidaySource holidaySource = OpenGammaExecutionContext.getHolidaySource(executionContext);
final ConventionSource conventionSource = OpenGammaExecutionContext.getConventionSource(executionContext);
final Calendar calendar = CalendarUtils.getCalendar(holidaySource, _currency);
final DepositConvention convention = conventionSource.getSingle(ExternalId.of(SCHEME_NAME, getConventionName(_currency, DEPOSIT)), DepositConvention.class);
final int spotLag = convention.getSettlementDays();
final ExternalId conventionSettlementRegion = convention.getRegionCalendar();
ZonedDateTime spotDate;
if (spotLag == 0 && conventionSettlementRegion == null) {
spotDate = valuationDateTime;
} else {
spotDate = ScheduleCalculator.getAdjustedDate(valuationDateTime, spotLag, calendar);;
}
final YieldCurveBundle curves = new YieldCurveBundle();
final String fullYieldCurveName = _originalCurveName + "_" + _currency;
curves.setCurve(fullYieldCurveName, (YieldAndDiscountCurve) originalCurveObject);
final int n = _impliedDefinition.getStrips().size();
final double[] t = new double[n];
final double[] r = new double[n];
int i = 0;
final DayCount dayCount = DayCounts.ACT_365; //TODO
final String impliedDepositCurveName = _curveCalculationConfig + "_" + _currency.getCode();
final List<InstrumentDerivative> derivatives = new ArrayList<>();
for (final FixedIncomeStrip strip : _impliedDefinition.getStrips()) {
final Tenor tenor = strip.getCurveNodePointTime();
final ZonedDateTime paymentDate = ScheduleCalculator.getAdjustedDate(spotDate, tenor.getPeriod(), MOD_FOL, calendar, true);
final double startTime = TimeCalculator.getTimeBetween(valuationDateTime, spotDate);
final double endTime = TimeCalculator.getTimeBetween(valuationDateTime, paymentDate);
final double accrualFactor = dayCount.getDayCountFraction(valuationDateTime, valuationDateTime.plus(tenor.getPeriod()), calendar);
final Cash cashFXCurve = new Cash(_currency, startTime, endTime, 1, 0, accrualFactor, fullYieldCurveName);
final double parRate = METHOD_CASH.parRate(cashFXCurve, curves);
final Cash cashDepositCurve = new Cash(_currency, startTime, endTime, 1, 0, accrualFactor, impliedDepositCurveName);
derivatives.add(cashDepositCurve);
t[i] = endTime;
r[i++] = parRate;
}
final CombinedInterpolatorExtrapolator interpolator = CombinedInterpolatorExtrapolatorFactory.getInterpolator(_interpolatorName, _leftExtrapolatorName, _rightExtrapolatorName);
final double absoluteTolerance = Double.parseDouble(absoluteToleranceName);
final double relativeTolerance = Double.parseDouble(relativeToleranceName);
final int iterations = Integer.parseInt(iterationsName);
final Decomposition<?> decomposition = DecompositionFactory.getDecomposition(decompositionName);
final boolean useFiniteDifference = Boolean.parseBoolean(useFiniteDifferenceName);
final LinkedHashMap<String, double[]> curveNodes = new LinkedHashMap<>();
final LinkedHashMap<String, Interpolator1D> interpolators = new LinkedHashMap<>();
curveNodes.put(impliedDepositCurveName, t);
interpolators.put(impliedDepositCurveName, interpolator);
final FXMatrix fxMatrix = new FXMatrix();
final YieldCurveBundle knownCurve = new YieldCurveBundle();
final MultipleYieldCurveFinderDataBundle data = new MultipleYieldCurveFinderDataBundle(derivatives, r, knownCurve, curveNodes, interpolators, useFiniteDifference, fxMatrix);
final NewtonVectorRootFinder rootFinder = new BroydenVectorRootFinder(absoluteTolerance, relativeTolerance, iterations, decomposition);
final Function1D<DoubleMatrix1D, DoubleMatrix1D> curveCalculator = new MultipleYieldCurveFinderFunction(data, PAR_RATE_CALCULATOR);
final Function1D<DoubleMatrix1D, DoubleMatrix2D> jacobianCalculator = new MultipleYieldCurveFinderJacobian(data, PAR_RATE_SENSITIVITY_CALCULATOR);
final double[] fittedYields = rootFinder.getRoot(curveCalculator, jacobianCalculator, new DoubleMatrix1D(r)).getData();
final DoubleMatrix2D jacobianMatrix = jacobianCalculator.evaluate(new DoubleMatrix1D(fittedYields));
final YieldCurve impliedDepositCurve = new YieldCurve(impliedDepositCurveName, InterpolatedDoublesCurve.from(t, fittedYields, interpolator));
final ValueSpecification curveSpec = new ValueSpecification(YIELD_CURVE, target.toSpecification(), resultCurveProperties);
final ValueSpecification jacobianSpec = new ValueSpecification(YIELD_CURVE_JACOBIAN, target.toSpecification(), resultJacobianProperties);
return Sets.newHashSet(new ComputedValue(curveSpec, impliedDepositCurve), new ComputedValue(jacobianSpec, jacobianMatrix));
}
@Override
public ComputationTargetType getTargetType() {
return ComputationTargetType.CURRENCY;
}
@Override
public Set<ValueSpecification> getResults(final FunctionCompilationContext compilationContext, final ComputationTarget target) {
final ValueProperties curveProperties = getCurveProperties(_impliedCurveName, _impliedConfiguration.getCalculationConfigName());
final ValueProperties jacobianProperties = getJacobianProperties(_impliedConfiguration.getCalculationConfigName());
final ComputationTargetSpecification targetSpec = target.toSpecification();
final ValueSpecification curve = new ValueSpecification(YIELD_CURVE, targetSpec, curveProperties);
final ValueSpecification jacobian = new ValueSpecification(YIELD_CURVE_JACOBIAN, targetSpec, jacobianProperties);
return Sets.newHashSet(curve, jacobian);
}
@Override
public Set<ValueRequirement> getRequirements(final FunctionCompilationContext compilationContext, final ComputationTarget target, final ValueRequirement desiredValue) {
final ValueProperties constraints = desiredValue.getConstraints();
final Set<String> rootFinderAbsoluteTolerance = constraints.getValues(PROPERTY_ROOT_FINDER_ABSOLUTE_TOLERANCE);
if (rootFinderAbsoluteTolerance == null || rootFinderAbsoluteTolerance.size() != 1) {
return null;
}
final Set<String> rootFinderRelativeTolerance = constraints.getValues(PROPERTY_ROOT_FINDER_RELATIVE_TOLERANCE);
if (rootFinderRelativeTolerance == null || rootFinderRelativeTolerance.size() != 1) {
return null;
}
final Set<String> maxIterations = constraints.getValues(PROPERTY_ROOT_FINDER_MAX_ITERATIONS);
if (maxIterations == null || maxIterations.size() != 1) {
return null;
}
final Set<String> decomposition = constraints.getValues(PROPERTY_DECOMPOSITION);
if (decomposition == null || decomposition.size() != 1) {
return null;
}
final Set<String> useFiniteDifference = constraints.getValues(PROPERTY_USE_FINITE_DIFFERENCE);
if (useFiniteDifference == null || useFiniteDifference.size() != 1) {
return null;
}
if (!_originalConfiguration.getTarget().equals(target.toSpecification())) {
s_logger.info("Invalid target, was {} - expected {}", target, _originalConfiguration.getTarget());
return null;
}
final ValueProperties properties = ValueProperties.builder().with(CURVE_CALCULATION_METHOD, _originalConfiguration.getCalculationMethod())
.with(CURVE_CALCULATION_CONFIG, _originalConfiguration.getCalculationConfigName()).with(CURVE, _originalCurveName).get();
return Collections.singleton(new ValueRequirement(YIELD_CURVE, target.toSpecification(), properties));
}
/**
* Gets the properties of the implied yield curve.
*
* @param curveName The implied curve name
* @return The properties
*/
private ValueProperties getCurveProperties(final String curveName, final String curveCalculationConfig) {
return createValueProperties().with(CURVE_CALCULATION_METHOD, IMPLIED_DEPOSIT).with(CURVE, curveName).with(CURVE_CALCULATION_CONFIG, curveCalculationConfig)
.withAny(PROPERTY_ROOT_FINDER_ABSOLUTE_TOLERANCE).withAny(PROPERTY_ROOT_FINDER_RELATIVE_TOLERANCE).withAny(PROPERTY_ROOT_FINDER_MAX_ITERATIONS).withAny(PROPERTY_DECOMPOSITION)
.withAny(PROPERTY_USE_FINITE_DIFFERENCE).with(InterpolatedDataProperties.X_INTERPOLATOR_NAME, _interpolatorName)
.with(InterpolatedDataProperties.LEFT_X_EXTRAPOLATOR_NAME, _leftExtrapolatorName).with(InterpolatedDataProperties.RIGHT_X_EXTRAPOLATOR_NAME, _rightExtrapolatorName).get();
}
/**
* Gets the properties of the Jacobian with no values set.
*
* @return The properties.
*/
private ValueProperties getJacobianProperties(final String curveCalculationConfig) {
return createValueProperties().with(CURVE_CALCULATION_METHOD, IMPLIED_DEPOSIT).with(CURVE_CALCULATION_CONFIG, curveCalculationConfig).withAny(PROPERTY_ROOT_FINDER_ABSOLUTE_TOLERANCE)
.withAny(PROPERTY_ROOT_FINDER_RELATIVE_TOLERANCE).withAny(PROPERTY_ROOT_FINDER_MAX_ITERATIONS).withAny(PROPERTY_DECOMPOSITION).withAny(PROPERTY_USE_FINITE_DIFFERENCE)
.with(InterpolatedDataProperties.X_INTERPOLATOR_NAME, _interpolatorName).with(InterpolatedDataProperties.LEFT_X_EXTRAPOLATOR_NAME, _leftExtrapolatorName)
.with(InterpolatedDataProperties.RIGHT_X_EXTRAPOLATOR_NAME, _rightExtrapolatorName).get();
}
}
}
| projects/OG-Financial/src/main/java/com/opengamma/financial/analytics/model/curve/interestrate/ImpliedDepositCurveFunction.java | /**
* Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.financial.analytics.model.curve.interestrate;
import static com.opengamma.engine.value.ValuePropertyNames.CURVE;
import static com.opengamma.engine.value.ValuePropertyNames.CURVE_CALCULATION_CONFIG;
import static com.opengamma.engine.value.ValuePropertyNames.CURVE_CALCULATION_METHOD;
import static com.opengamma.engine.value.ValueRequirementNames.YIELD_CURVE;
import static com.opengamma.engine.value.ValueRequirementNames.YIELD_CURVE_JACOBIAN;
import static com.opengamma.financial.analytics.model.curve.interestrate.MultiYieldCurvePropertiesAndDefaults.PROPERTY_DECOMPOSITION;
import static com.opengamma.financial.analytics.model.curve.interestrate.MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_ABSOLUTE_TOLERANCE;
import static com.opengamma.financial.analytics.model.curve.interestrate.MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_MAX_ITERATIONS;
import static com.opengamma.financial.analytics.model.curve.interestrate.MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_RELATIVE_TOLERANCE;
import static com.opengamma.financial.analytics.model.curve.interestrate.MultiYieldCurvePropertiesAndDefaults.PROPERTY_USE_FINITE_DIFFERENCE;
import static com.opengamma.financial.convention.initializer.PerCurrencyConventionHelper.DEPOSIT;
import static com.opengamma.financial.convention.initializer.PerCurrencyConventionHelper.SCHEME_NAME;
import static com.opengamma.financial.convention.initializer.PerCurrencyConventionHelper.getConventionName;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.threeten.bp.Instant;
import org.threeten.bp.LocalTime;
import org.threeten.bp.ZoneOffset;
import org.threeten.bp.ZonedDateTime;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.analytics.financial.forex.method.FXMatrix;
import com.opengamma.analytics.financial.interestrate.InstrumentDerivative;
import com.opengamma.analytics.financial.interestrate.MultipleYieldCurveFinderDataBundle;
import com.opengamma.analytics.financial.interestrate.MultipleYieldCurveFinderFunction;
import com.opengamma.analytics.financial.interestrate.MultipleYieldCurveFinderJacobian;
import com.opengamma.analytics.financial.interestrate.ParRateCalculator;
import com.opengamma.analytics.financial.interestrate.ParRateCurveSensitivityCalculator;
import com.opengamma.analytics.financial.interestrate.YieldCurveBundle;
import com.opengamma.analytics.financial.interestrate.cash.derivative.Cash;
import com.opengamma.analytics.financial.interestrate.cash.method.CashDiscountingMethod;
import com.opengamma.analytics.financial.model.interestrate.curve.YieldAndDiscountCurve;
import com.opengamma.analytics.financial.model.interestrate.curve.YieldCurve;
import com.opengamma.analytics.financial.schedule.ScheduleCalculator;
import com.opengamma.analytics.math.curve.InterpolatedDoublesCurve;
import com.opengamma.analytics.math.function.Function1D;
import com.opengamma.analytics.math.interpolation.CombinedInterpolatorExtrapolator;
import com.opengamma.analytics.math.interpolation.CombinedInterpolatorExtrapolatorFactory;
import com.opengamma.analytics.math.interpolation.Interpolator1D;
import com.opengamma.analytics.math.linearalgebra.Decomposition;
import com.opengamma.analytics.math.linearalgebra.DecompositionFactory;
import com.opengamma.analytics.math.matrix.DoubleMatrix1D;
import com.opengamma.analytics.math.matrix.DoubleMatrix2D;
import com.opengamma.analytics.math.rootfinding.newton.BroydenVectorRootFinder;
import com.opengamma.analytics.math.rootfinding.newton.NewtonVectorRootFinder;
import com.opengamma.analytics.util.time.TimeCalculator;
import com.opengamma.core.convention.ConventionSource;
import com.opengamma.core.holiday.HolidaySource;
import com.opengamma.engine.ComputationTarget;
import com.opengamma.engine.ComputationTargetSpecification;
import com.opengamma.engine.function.AbstractFunction;
import com.opengamma.engine.function.CompiledFunctionDefinition;
import com.opengamma.engine.function.FunctionCompilationContext;
import com.opengamma.engine.function.FunctionExecutionContext;
import com.opengamma.engine.function.FunctionInputs;
import com.opengamma.engine.target.ComputationTargetType;
import com.opengamma.engine.value.ComputedValue;
import com.opengamma.engine.value.ValueProperties;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.value.ValueSpecification;
import com.opengamma.financial.OpenGammaExecutionContext;
import com.opengamma.financial.analytics.conversion.CalendarUtils;
import com.opengamma.financial.analytics.ircurve.FixedIncomeStrip;
import com.opengamma.financial.analytics.ircurve.StripInstrumentType;
import com.opengamma.financial.analytics.ircurve.YieldCurveDefinition;
import com.opengamma.financial.analytics.ircurve.calcconfig.MultiCurveCalculationConfig;
import com.opengamma.financial.analytics.model.InterpolatedDataProperties;
import com.opengamma.financial.config.ConfigSourceQuery;
import com.opengamma.financial.convention.DepositConvention;
import com.opengamma.financial.convention.businessday.BusinessDayConvention;
import com.opengamma.financial.convention.businessday.BusinessDayConventions;
import com.opengamma.financial.convention.calendar.Calendar;
import com.opengamma.financial.convention.daycount.DayCount;
import com.opengamma.financial.convention.daycount.DayCounts;
import com.opengamma.id.ExternalId;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.async.AsynchronousExecution;
import com.opengamma.util.money.Currency;
import com.opengamma.util.time.Tenor;
/**
* Constructs a single yield curve and its Jacobian from an FX-implied yield curve calculation configuration and a yield curve definition that contains <b>only</b> {@link StripInstrumentType#CASH}
* strips. The transformation of the yield curve allows risk to be displayed with respect to implied deposit rates, not FX forwards.
*/
public class ImpliedDepositCurveFunction extends AbstractFunction {
/** The calculation method property value */
public static final String IMPLIED_DEPOSIT = "ImpliedDeposit";
/** The Cash instrument method */
private static final CashDiscountingMethod METHOD_CASH = CashDiscountingMethod.getInstance();
/** Calculates the par rate */
private static final ParRateCalculator PAR_RATE_CALCULATOR = ParRateCalculator.getInstance();
/** Calculates the sensitivity of the par rate to the curves */
private static final ParRateCurveSensitivityCalculator PAR_RATE_SENSITIVITY_CALCULATOR = ParRateCurveSensitivityCalculator.getInstance();
/** The business day convention used for FX forward dates computation **/
private static final BusinessDayConvention MOD_FOL = BusinessDayConventions.MODIFIED_FOLLOWING;
/** The logger */
private static final Logger s_logger = LoggerFactory.getLogger(ImpliedDepositCurveFunction.class);
/** The curve name */
private final String _curveCalculationConfig;
private ConfigSourceQuery<MultiCurveCalculationConfig> _multiCurveCalculationConfig;
private ConfigSourceQuery<YieldCurveDefinition> _yieldCurveDefinition;
/**
* @param curveCalculationConfig The curve name, not null
*/
public ImpliedDepositCurveFunction(final String curveCalculationConfig) {
ArgumentChecker.notNull(curveCalculationConfig, "curve name");
_curveCalculationConfig = curveCalculationConfig;
}
@Override
public void init(final FunctionCompilationContext context) {
_multiCurveCalculationConfig = ConfigSourceQuery.init(context, this, MultiCurveCalculationConfig.class);
_yieldCurveDefinition = ConfigSourceQuery.init(context, this, YieldCurveDefinition.class);
}
@Override
public CompiledFunctionDefinition compile(final FunctionCompilationContext context, final Instant atInstant) {
final MultiCurveCalculationConfig impliedConfiguration = _multiCurveCalculationConfig.get(_curveCalculationConfig);
if (impliedConfiguration == null) {
throw new OpenGammaRuntimeException("Multi-curve calculation called " + _curveCalculationConfig + " was null");
}
ComputationTarget target = context.getComputationTargetResolver().resolve(impliedConfiguration.getTarget());
if (!(target.getValue() instanceof Currency)) {
throw new OpenGammaRuntimeException("Target of curve calculation configuration was not a currency");
}
final Currency impliedCurrency = (Currency) target.getValue();
if (!IMPLIED_DEPOSIT.equals(impliedConfiguration.getCalculationMethod())) {
throw new OpenGammaRuntimeException("Curve calculation method was not " + IMPLIED_DEPOSIT + " for configuration called " + _curveCalculationConfig);
}
final String[] impliedCurveNames = impliedConfiguration.getYieldCurveNames();
if (impliedCurveNames.length != 1) {
throw new OpenGammaRuntimeException("Can only handle configurations with a single implied curve");
}
final LinkedHashMap<String, String[]> originalConfigurationName = impliedConfiguration.getExogenousConfigData();
if (originalConfigurationName == null || originalConfigurationName.size() != 1) {
throw new OpenGammaRuntimeException("Need a configuration with one exogenous configuration");
}
final Map.Entry<String, String[]> entry = Iterables.getOnlyElement(originalConfigurationName.entrySet());
final String[] originalCurveNames = entry.getValue();
if (originalCurveNames.length != 1) {
s_logger.warn("Found more than one exogenous configuration name; using only the first");
}
final MultiCurveCalculationConfig originalConfiguration = _multiCurveCalculationConfig.get(entry.getKey());
if (originalConfiguration == null) {
throw new OpenGammaRuntimeException("Multi-curve calculation called " + entry.getKey() + " was null");
}
target = context.getComputationTargetResolver().resolve(originalConfiguration.getTarget());
if (!(target.getValue() instanceof Currency)) {
throw new OpenGammaRuntimeException("Target of curve calculation configuration was not a currency");
}
final Currency originalCurrency = (Currency) target.getValue();
if (!originalCurrency.equals(impliedCurrency)) {
throw new OpenGammaRuntimeException("Currency targets for configurations " + _curveCalculationConfig + " and " + entry.getKey() + " did not match");
}
final YieldCurveDefinition impliedDefinition = _yieldCurveDefinition.get(impliedCurveNames[0] + "_" + impliedCurrency.getCode());
if (impliedDefinition == null) {
throw new OpenGammaRuntimeException("Could not get implied definition called " + impliedCurveNames[0] + "_" + impliedCurrency.getCode());
}
final Set<FixedIncomeStrip> strips = impliedDefinition.getStrips();
for (final FixedIncomeStrip strip : strips) {
if (strip.getInstrumentType() != StripInstrumentType.CASH) {
throw new OpenGammaRuntimeException("Can only handle yield curve definitions with CASH strips");
}
}
final ZonedDateTime atZDT = ZonedDateTime.ofInstant(atInstant, ZoneOffset.UTC);
return new MyCompiledFunction(atZDT.with(LocalTime.MIDNIGHT), atZDT.plusDays(1).with(LocalTime.MIDNIGHT).minusNanos(1000000), impliedConfiguration, impliedDefinition,
originalConfiguration, originalCurveNames[0]);
};
private class MyCompiledFunction extends AbstractInvokingCompiledFunction {
/** The definition of the implied curve */
private final YieldCurveDefinition _impliedDefinition;
/** The implied curve calculation configuration */
private final MultiCurveCalculationConfig _impliedConfiguration;
/** The original curve calculation configuration */
private final MultiCurveCalculationConfig _originalConfiguration;
/** The implied curve name */
private final String _impliedCurveName;
/** The original curve name */
private final String _originalCurveName;
/** The currency */
private final Currency _currency;
/** The interpolator */
private final String _interpolatorName;
/** The left extrapolator */
private final String _leftExtrapolatorName;
/** The right extrapolator */
private final String _rightExtrapolatorName;
public MyCompiledFunction(final ZonedDateTime earliestInvokation, final ZonedDateTime latestInvokation, final MultiCurveCalculationConfig impliedConfiguration,
final YieldCurveDefinition impliedDefinition, final MultiCurveCalculationConfig originalConfiguration, final String originalCurveName) {
super(earliestInvokation, latestInvokation);
_impliedConfiguration = impliedConfiguration;
_impliedDefinition = impliedDefinition;
_originalConfiguration = originalConfiguration;
_impliedCurveName = impliedDefinition.getName();
_originalCurveName = originalCurveName;
_currency = impliedDefinition.getCurrency();
_interpolatorName = impliedDefinition.getInterpolatorName();
_leftExtrapolatorName = impliedDefinition.getLeftExtrapolatorName();
_rightExtrapolatorName = impliedDefinition.getRightExtrapolatorName();
}
@Override
public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target, final Set<ValueRequirement> desiredValues)
throws AsynchronousExecution {
final Object originalCurveObject = inputs.getValue(YIELD_CURVE);
if (originalCurveObject == null) {
throw new OpenGammaRuntimeException("Could not get original curve");
}
ValueProperties resultCurveProperties = null;
String absoluteToleranceName = null;
String relativeToleranceName = null;
String iterationsName = null;
String decompositionName = null;
String useFiniteDifferenceName = null;
for (final ValueRequirement desiredValue : desiredValues) {
if (desiredValue.getValueName().equals(YIELD_CURVE)) {
absoluteToleranceName = desiredValue.getConstraint(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_ABSOLUTE_TOLERANCE);
relativeToleranceName = desiredValue.getConstraint(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_RELATIVE_TOLERANCE);
iterationsName = desiredValue.getConstraint(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_MAX_ITERATIONS);
decompositionName = desiredValue.getConstraint(MultiYieldCurvePropertiesAndDefaults.PROPERTY_DECOMPOSITION);
useFiniteDifferenceName = desiredValue.getConstraint(MultiYieldCurvePropertiesAndDefaults.PROPERTY_USE_FINITE_DIFFERENCE);
resultCurveProperties = desiredValue.getConstraints().copy().get();
break;
}
}
if (resultCurveProperties == null) {
throw new OpenGammaRuntimeException("Could not get result curve properties");
}
final ValueProperties resultJacobianProperties = resultCurveProperties.withoutAny(CURVE);
final ZonedDateTime now = ZonedDateTime.now(executionContext.getValuationClock());
final HolidaySource holidaySource = OpenGammaExecutionContext.getHolidaySource(executionContext);
final ConventionSource conventionSource = OpenGammaExecutionContext.getConventionSource(executionContext);
final Calendar calendar = CalendarUtils.getCalendar(holidaySource, _currency);
final DepositConvention convention = conventionSource.getSingle(ExternalId.of(SCHEME_NAME, getConventionName(_currency, DEPOSIT)), DepositConvention.class);
final int spotLag = convention.getSettlementDays();
final ExternalId conventionSettlementRegion = convention.getRegionCalendar();
ZonedDateTime spotDate;
if (spotLag == 0 && conventionSettlementRegion == null) {
spotDate = now;
} else {
spotDate = now;
}
final YieldCurveBundle curves = new YieldCurveBundle();
final String fullYieldCurveName = _originalCurveName + "_" + _currency;
curves.setCurve(fullYieldCurveName, (YieldAndDiscountCurve) originalCurveObject);
final int n = _impliedDefinition.getStrips().size();
final double[] t = new double[n];
final double[] r = new double[n];
int i = 0;
final DayCount dayCount = DayCounts.ACT_365; //TODO
final String impliedDepositCurveName = _curveCalculationConfig + "_" + _currency.getCode();
final List<InstrumentDerivative> derivatives = new ArrayList<>();
for (final FixedIncomeStrip strip : _impliedDefinition.getStrips()) {
final Tenor tenor = strip.getCurveNodePointTime();
final ZonedDateTime paymentDate = ScheduleCalculator.getAdjustedDate(spotDate, tenor.getPeriod(), MOD_FOL, calendar, true);
final double startTime = TimeCalculator.getTimeBetween(now, spotDate);
final double endTime = TimeCalculator.getTimeBetween(now, paymentDate);
final double accrualFactor = dayCount.getDayCountFraction(now, now.plus(tenor.getPeriod()), calendar);
final Cash cashFXCurve = new Cash(_currency, startTime, endTime, 1, 0, accrualFactor, fullYieldCurveName);
final double parRate = METHOD_CASH.parRate(cashFXCurve, curves);
final Cash cashDepositCurve = new Cash(_currency, startTime, endTime, 1, 0, accrualFactor, impliedDepositCurveName);
derivatives.add(cashDepositCurve);
t[i] = endTime;
r[i++] = parRate;
}
final CombinedInterpolatorExtrapolator interpolator = CombinedInterpolatorExtrapolatorFactory.getInterpolator(_interpolatorName, _leftExtrapolatorName, _rightExtrapolatorName);
final double absoluteTolerance = Double.parseDouble(absoluteToleranceName);
final double relativeTolerance = Double.parseDouble(relativeToleranceName);
final int iterations = Integer.parseInt(iterationsName);
final Decomposition<?> decomposition = DecompositionFactory.getDecomposition(decompositionName);
final boolean useFiniteDifference = Boolean.parseBoolean(useFiniteDifferenceName);
final LinkedHashMap<String, double[]> curveNodes = new LinkedHashMap<>();
final LinkedHashMap<String, Interpolator1D> interpolators = new LinkedHashMap<>();
curveNodes.put(impliedDepositCurveName, t);
interpolators.put(impliedDepositCurveName, interpolator);
final FXMatrix fxMatrix = new FXMatrix();
final YieldCurveBundle knownCurve = new YieldCurveBundle();
final MultipleYieldCurveFinderDataBundle data = new MultipleYieldCurveFinderDataBundle(derivatives, r, knownCurve, curveNodes, interpolators, useFiniteDifference, fxMatrix);
final NewtonVectorRootFinder rootFinder = new BroydenVectorRootFinder(absoluteTolerance, relativeTolerance, iterations, decomposition);
final Function1D<DoubleMatrix1D, DoubleMatrix1D> curveCalculator = new MultipleYieldCurveFinderFunction(data, PAR_RATE_CALCULATOR);
final Function1D<DoubleMatrix1D, DoubleMatrix2D> jacobianCalculator = new MultipleYieldCurveFinderJacobian(data, PAR_RATE_SENSITIVITY_CALCULATOR);
final double[] fittedYields = rootFinder.getRoot(curveCalculator, jacobianCalculator, new DoubleMatrix1D(r)).getData();
final DoubleMatrix2D jacobianMatrix = jacobianCalculator.evaluate(new DoubleMatrix1D(fittedYields));
final YieldCurve impliedDepositCurve = new YieldCurve(impliedDepositCurveName, InterpolatedDoublesCurve.from(t, fittedYields, interpolator));
final ValueSpecification curveSpec = new ValueSpecification(YIELD_CURVE, target.toSpecification(), resultCurveProperties);
final ValueSpecification jacobianSpec = new ValueSpecification(YIELD_CURVE_JACOBIAN, target.toSpecification(), resultJacobianProperties);
return Sets.newHashSet(new ComputedValue(curveSpec, impliedDepositCurve), new ComputedValue(jacobianSpec, jacobianMatrix));
}
@Override
public ComputationTargetType getTargetType() {
return ComputationTargetType.CURRENCY;
}
@Override
public Set<ValueSpecification> getResults(final FunctionCompilationContext compilationContext, final ComputationTarget target) {
final ValueProperties curveProperties = getCurveProperties(_impliedCurveName, _impliedConfiguration.getCalculationConfigName());
final ValueProperties jacobianProperties = getJacobianProperties(_impliedConfiguration.getCalculationConfigName());
final ComputationTargetSpecification targetSpec = target.toSpecification();
final ValueSpecification curve = new ValueSpecification(YIELD_CURVE, targetSpec, curveProperties);
final ValueSpecification jacobian = new ValueSpecification(YIELD_CURVE_JACOBIAN, targetSpec, jacobianProperties);
return Sets.newHashSet(curve, jacobian);
}
@Override
public Set<ValueRequirement> getRequirements(final FunctionCompilationContext compilationContext, final ComputationTarget target, final ValueRequirement desiredValue) {
final ValueProperties constraints = desiredValue.getConstraints();
final Set<String> rootFinderAbsoluteTolerance = constraints.getValues(PROPERTY_ROOT_FINDER_ABSOLUTE_TOLERANCE);
if (rootFinderAbsoluteTolerance == null || rootFinderAbsoluteTolerance.size() != 1) {
return null;
}
final Set<String> rootFinderRelativeTolerance = constraints.getValues(PROPERTY_ROOT_FINDER_RELATIVE_TOLERANCE);
if (rootFinderRelativeTolerance == null || rootFinderRelativeTolerance.size() != 1) {
return null;
}
final Set<String> maxIterations = constraints.getValues(PROPERTY_ROOT_FINDER_MAX_ITERATIONS);
if (maxIterations == null || maxIterations.size() != 1) {
return null;
}
final Set<String> decomposition = constraints.getValues(PROPERTY_DECOMPOSITION);
if (decomposition == null || decomposition.size() != 1) {
return null;
}
final Set<String> useFiniteDifference = constraints.getValues(PROPERTY_USE_FINITE_DIFFERENCE);
if (useFiniteDifference == null || useFiniteDifference.size() != 1) {
return null;
}
if (!_originalConfiguration.getTarget().equals(target.toSpecification())) {
s_logger.info("Invalid target, was {} - expected {}", target, _originalConfiguration.getTarget());
return null;
}
final ValueProperties properties = ValueProperties.builder().with(CURVE_CALCULATION_METHOD, _originalConfiguration.getCalculationMethod())
.with(CURVE_CALCULATION_CONFIG, _originalConfiguration.getCalculationConfigName()).with(CURVE, _originalCurveName).get();
return Collections.singleton(new ValueRequirement(YIELD_CURVE, target.toSpecification(), properties));
}
/**
* Gets the properties of the implied yield curve.
*
* @param curveName The implied curve name
* @return The properties
*/
private ValueProperties getCurveProperties(final String curveName, final String curveCalculationConfig) {
return createValueProperties().with(CURVE_CALCULATION_METHOD, IMPLIED_DEPOSIT).with(CURVE, curveName).with(CURVE_CALCULATION_CONFIG, curveCalculationConfig)
.withAny(PROPERTY_ROOT_FINDER_ABSOLUTE_TOLERANCE).withAny(PROPERTY_ROOT_FINDER_RELATIVE_TOLERANCE).withAny(PROPERTY_ROOT_FINDER_MAX_ITERATIONS).withAny(PROPERTY_DECOMPOSITION)
.withAny(PROPERTY_USE_FINITE_DIFFERENCE).with(InterpolatedDataProperties.X_INTERPOLATOR_NAME, _interpolatorName)
.with(InterpolatedDataProperties.LEFT_X_EXTRAPOLATOR_NAME, _leftExtrapolatorName).with(InterpolatedDataProperties.RIGHT_X_EXTRAPOLATOR_NAME, _rightExtrapolatorName).get();
}
/**
* Gets the properties of the Jacobian with no values set.
*
* @return The properties.
*/
private ValueProperties getJacobianProperties(final String curveCalculationConfig) {
return createValueProperties().with(CURVE_CALCULATION_METHOD, IMPLIED_DEPOSIT).with(CURVE_CALCULATION_CONFIG, curveCalculationConfig).withAny(PROPERTY_ROOT_FINDER_ABSOLUTE_TOLERANCE)
.withAny(PROPERTY_ROOT_FINDER_RELATIVE_TOLERANCE).withAny(PROPERTY_ROOT_FINDER_MAX_ITERATIONS).withAny(PROPERTY_DECOMPOSITION).withAny(PROPERTY_USE_FINITE_DIFFERENCE)
.with(InterpolatedDataProperties.X_INTERPOLATOR_NAME, _interpolatorName).with(InterpolatedDataProperties.LEFT_X_EXTRAPOLATOR_NAME, _leftExtrapolatorName)
.with(InterpolatedDataProperties.RIGHT_X_EXTRAPOLATOR_NAME, _rightExtrapolatorName).get();
}
}
}
| [PLAT-5502] Brought implied depo curve function in line with the curve series function
| projects/OG-Financial/src/main/java/com/opengamma/financial/analytics/model/curve/interestrate/ImpliedDepositCurveFunction.java | [PLAT-5502] Brought implied depo curve function in line with the curve series function |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.